Example usage for java.math BigInteger add

List of usage examples for java.math BigInteger add

Introduction

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

Prototype

BigInteger add(long val) 

Source Link

Document

Package private methods used by BigDecimal code to add a BigInteger with a long.

Usage

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 a va  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:com.ephesoft.dcma.tablefinder.share.TableRowFinderUtility.java

/**
 * Gets sorted list of spans of the page.
 * /* w w  w  . j a v  a  2  s.  com*/
 * @param spans {@link Spans}
 * @return {@link List}<{@link Span}>
 */
private static List<Span> getSortedSpanList(final Spans spans) {
    final List<Span> spanList = spans.getSpan();
    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();
            int halfOfSecSpan = (s2Y1.intValue() - s2Y0.intValue()) / 2;
            int y1 = s2Y1.intValue() + halfOfSecSpan;
            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);
            }
            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> linkedList = new LinkedList<Span>();
    linkedList.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 linkedList;
}

From source file:opennlp.tools.similarity.apps.solr.WordDocBuilderEndNotes.java

public String buildWordDoc(List<HitBase> content, String title) {

    String outputDocFinename = absPath + "written/" + title.replace(' ', '_').replace('\"', ' ').trim()
            + ".docx";

    WordprocessingMLPackage wordMLPackage = null;

    List<String> imageURLs = getAllImageSearchResults(title);
    int count = 0;
    BigInteger refId = BigInteger.ONE;
    try {/*from www  .j  a  v  a2  s  . c  om*/
        wordMLPackage = WordprocessingMLPackage.createPackage();

        CTEndnotes endnotes = null;
        try {
            EndnotesPart ep = new EndnotesPart();
            endnotes = Context.getWmlObjectFactory().createCTEndnotes();
            ep.setJaxbElement(endnotes);
            wordMLPackage.getMainDocumentPart().addTargetPart(ep);
        } catch (InvalidFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        wordMLPackage.getMainDocumentPart().addStyledParagraphOfText("Title", title.toUpperCase());
        for (HitBase para : content) {
            if (para.getFragments() == null || para.getFragments().size() < 1) // no found content in this hit
                continue;
            try {
                String processedParaTitle = processParagraphTitle(para.getTitle());

                if (processedParaTitle != null && !processedParaTitle.endsWith("..")
                        || StringUtils.isAlphanumeric(processedParaTitle)) {
                    wordMLPackage.getMainDocumentPart().addStyledParagraphOfText("Subtitle",
                            processedParaTitle);
                }
                String paraText = processParagraphText(para.getFragments().toString());
                wordMLPackage.getMainDocumentPart().addParagraphOfText(paraText);

                CTFtnEdn endnote = Context.getWmlObjectFactory().createCTFtnEdn();
                endnotes.getEndnote().add(endnote);

                endnote.setId(refId);
                refId.add(BigInteger.ONE);
                String url = para.getUrl();
                String endnoteBody = "<w:p xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" ><w:pPr><w:pStyle w:val=\"EndnoteText\"/></w:pPr><w:r><w:rPr>"
                        + "<w:rStyle w:val=\"EndnoteReference\"/></w:rPr><w:endnoteRef/></w:r><w:r><w:t xml:space=\"preserve\"> "
                        + url + "</w:t></w:r></w:p>";
                try {
                    endnote.getEGBlockLevelElts().add(XmlUtils.unmarshalString(endnoteBody));
                } catch (JAXBException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                // Add the body text referencing it
                String docBody = "<w:p xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" ><w:r><w:t>"//+ paraText
                        /*+ refId.toString()*/ + "</w:t></w:r><w:r><w:rPr><w:rStyle w:val=\"EndnoteReference\"/></w:rPr><w:endnoteReference w:id=\""
                        + refId.toString() + "\"/></w:r></w:p>";

                try {
                    wordMLPackage.getMainDocumentPart().addParagraph(docBody);
                } catch (JAXBException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                try {
                    addImageByImageURLToPackage(count, wordMLPackage, imageURLs);
                } catch (Exception e) {
                    // no need to report issues
                    //e.printStackTrace();
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            count++;
        }
        // now add URLs
        wordMLPackage.getMainDocumentPart().addStyledParagraphOfText("Subtitle", "REFERENCES");
        for (HitBase para : content) {
            if (para.getFragments() == null || para.getFragments().size() < 1) // no found content in this hit
                continue;
            try {
                wordMLPackage.getMainDocumentPart().addStyledParagraphOfText("Subtitle", para.getTitle());
                String paraText = para.getUrl();
                wordMLPackage.getMainDocumentPart().addParagraphOfText(paraText);

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        try {
            wordMLPackage.save(new File(outputDocFinename));
            System.out.println("Finished creating docx =" + outputDocFinename);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            String fileNameToDownload = "/var/www/wrt_latest/"
                    + title.replace(' ', '_').replace('\"', ' ').trim() + ".docx";
            wordMLPackage.save(new File(fileNameToDownload));
            System.out.println("Wrote a doc for download :" + fileNameToDownload);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return outputDocFinename;
}

From source file:com.kncwallet.wallet.ui.SendCoinsFragment.java

private void showConfirmDialog(final SendRequest sendRequest) {

    final BigInteger amount = amountCalculatorLink.getAmount();

    BigInteger fee = sendRequest.fee;

    BigInteger amountIncludingFee = amount.add(fee);

    View view = activity.getLayoutInflater().inflate(R.layout.dialog_transaction_fee, null);

    CurrencyTextView dialogCurrencyBtc = (CurrencyTextView) view.findViewById(R.id.currency_text_view_btc);
    dialogCurrencyBtc.setPrecision(btcPrecision, btcShift);
    dialogCurrencyBtc.setAmount(amountIncludingFee);
    final String suffix = DenominationUtil.getCurrencyCode(btcShift);
    dialogCurrencyBtc.setSuffix(suffix);

    CurrencyTextView dialogCurrencyLocal = (CurrencyTextView) view.findViewById(R.id.currency_text_view_local);

    if (exchangeRate != null && exchangeRate.rate != null) {
        final BigInteger localValue = WalletUtils.localValue(amountIncludingFee, exchangeRate.rate);
        dialogCurrencyLocal.setSuffix(exchangeRate.currencyCode);
        dialogCurrencyLocal.setPrecision(Constants.LOCAL_PRECISION, 0);
        dialogCurrencyLocal.setStrikeThru(Constants.TEST);
        dialogCurrencyLocal.setAmount(localValue);

    } else {/*from  w w  w  .  j  a  va  2  s .c  o  m*/
        dialogCurrencyLocal.setVisibility(View.GONE);
    }

    String toName = validatedAddress.label;
    if (toName == null) {
        toName = validatedAddress.address.toString();

        LinearLayout currencyParent = (LinearLayout) view.findViewById(R.id.currency_parent);
        currencyParent.setOrientation(LinearLayout.VERTICAL);

    }

    String textViewToText = getString(R.string.dialog_transaction_to_user, toName);

    TextView textViewTo = (TextView) view.findViewById(R.id.text_view_trail);
    textViewTo.setText(textViewToText);

    final CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBox);

    KnCDialog.Builder builder = new KnCDialog.Builder(activity);
    builder.setTitle(getString(R.string.dialog_transaction_title, amountIncludingFee)).setView(view)
            .setPositiveButton(R.string.send_tab_text, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                    if (checkBox.isChecked()) {
                        prefs.edit().putBoolean(Constants.PREFS_KEY_FEE_INFO, false).commit();
                    }
                    commitSendRequest(sendRequest);
                }
            }).setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    resetSendRequest();
                }
            }).show();

}

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

/**
 * Counts the size of a directory recursively (sum of the length of all files).
 * //from ww w. j ava2 s.co  m
 * @param directory
 *            directory to inspect, must not be {@code null}
 * @return size of directory in bytes, 0 if directory is security restricted.
 * @throws NullPointerException
 *             if the directory is {@code null}
 *  @since 2.4
 */
public static BigInteger sizeOfDirectoryAsBigInteger(File directory) {
    checkDirectory(directory);

    final File[] files = directory.listFiles();
    if (files == null) { // null if security restricted
        return BigInteger.ZERO;
    }
    BigInteger size = BigInteger.ZERO;

    for (final File file : files) {
        try {
            if (!isSymlink(file)) {
                size = size.add(BigInteger.valueOf(sizeOf(file)));
            }
        } catch (IOException ioe) {
            // Ignore exceptions caught when asking if a File is a symlink.
        }
    }

    return size;
}

From source file:piuk.blockchain.android.MyRemoteWallet.java

public void sendCoinsAsync(final HashMap<String, BigInteger> sendingAddresses, final String toAddress,
        final BigInteger amount, final FeePolicy feePolicy, final BigInteger fee, final String changeAddress,
        final SendProgress progress) {
    BigInteger sum = BigInteger.ZERO;
    for (Iterator<Entry<String, BigInteger>> iterator = sendingAddresses.entrySet().iterator(); iterator
            .hasNext();) {//from   www .  j av  a 2  s . co m
        Entry<String, BigInteger> entry = iterator.next();
        sum = sum.add(entry.getValue());
    }

    if (sum.compareTo(amount) != 0) {
        progress.onError("Internal error input amounts not validating correctly");
        return;
    }

    HashMap<String, BigInteger> receivingAddresses = new HashMap<String, BigInteger>();
    receivingAddresses.put(toAddress, amount);

    sendCoinsAsync(false, sendingAddresses, receivingAddresses, feePolicy, fee, changeAddress, progress);
}

From source file:org.fenixedu.treasury.services.integration.erp.ERPExporter.java

private WorkDocument convertToSAFTWorkDocument(Invoice document,
        Map<String, oecd.standardauditfile_tax.pt_1.Customer> baseCustomers,
        Map<String, oecd.standardauditfile_tax.pt_1.Product> baseProducts) {
    WorkDocument workDocument = new WorkDocument();

    // Find the Customer in BaseCustomers
    oecd.standardauditfile_tax.pt_1.Customer customer = null;

    if (baseCustomers.containsKey(document.getDebtAccount().getCustomer().getCode())) {
        customer = baseCustomers.get(document.getDebtAccount().getCustomer().getCode());
    } else {/*  w w w.  j ava  2s  . c  om*/
        // If not found, create a new one and add it to baseCustomers
        customer = convertCustomerToSAFTCustomer(document.getDebtAccount().getCustomer());
        baseCustomers.put(customer.getCustomerID(), customer);
    }

    //check the PayorDebtAccount
    if (document.getPayorDebtAccount() != null) {
        if (baseCustomers.containsKey(document.getPayorDebtAccount().getCustomer().getCode())) {
            //do nothing
        } else {
            // If not found, create a new one and add it to baseCustomers
            oecd.standardauditfile_tax.pt_1.Customer payorCustomer = convertCustomerToSAFTCustomer(
                    document.getPayorDebtAccount().getCustomer());
            baseCustomers.put(payorCustomer.getCustomerID(), payorCustomer);
        }
    }

    // MovementDate
    DatatypeFactory dataTypeFactory;
    try {
        dataTypeFactory = DatatypeFactory.newInstance();
        DateTime documentDate = document.getDocumentDate();

        // SystemEntryDate
        workDocument.setSystemEntryDate(convertToXMLDateTime(dataTypeFactory, documentDate));

        workDocument.setWorkDate(convertToXMLDateTime(dataTypeFactory, documentDate));

        // DocumentNumber
        workDocument.setDocumentNumber(document.getUiDocumentNumber());

        // CustomerID
        workDocument.setCustomerID(document.getDebtAccount().getCustomer().getCode());

        //PayorID
        if (document.getPayorDebtAccount() != null) {
            workDocument.setPayorCustomerID(document.getPayorDebtAccount().getCustomer().getCode());
        }

        // DocumentStatus
        /*
         * Deve ser preenchido com: ?N? ? Normal; Texto 1 ?T? ? Por conta de
         * terceiros; ?A? ? Documento anulado.
         */
        SourceDocuments.WorkingDocuments.WorkDocument.DocumentStatus status = new SourceDocuments.WorkingDocuments.WorkDocument.DocumentStatus();
        if (document.isAnnulled()) {
            status.setWorkStatus("A");
        } else {
            status.setWorkStatus("N");
        }

        status.setWorkStatusDate(workDocument.getSystemEntryDate());
        // status.setReason("");
        // Utilizador responsvel pelo estado atual do docu-mento.
        status.setSourceID(document.getVersioningUpdatedBy());
        // Deve ser preenchido com:
        // 'P' - Documento produzido na aplicacao;
        if (Boolean.TRUE.equals(document.getDocumentNumberSeries().getSeries().getExternSeries())) {
            status.setSourceBilling(SAFTPTSourceBilling.I);
        } else {
            status.setSourceBilling(SAFTPTSourceBilling.P);
        }

        workDocument.setDocumentStatus(status);

        // DocumentTotals
        SourceDocuments.WorkingDocuments.WorkDocument.DocumentTotals docTotals = new SourceDocuments.WorkingDocuments.WorkDocument.DocumentTotals();
        docTotals.setGrossTotal(document.getTotalAmount().setScale(2, RoundingMode.HALF_EVEN));
        docTotals.setNetTotal(document.getTotalNetAmount().setScale(2, RoundingMode.HALF_EVEN));
        docTotals.setTaxPayable(document.getTotalAmount().subtract(document.getTotalNetAmount()).setScale(2,
                RoundingMode.HALF_EVEN));
        workDocument.setDocumentTotals(docTotals);

        // WorkType
        /*
         * Deve ser preenchido com: Texto 2 "DC"  Documentos emitidos que
         * sejam suscetiveis de apresentacao ao cliente para conferencia de
         * entrega de mercadorias ou da prestacao de servicos. "FC"  Fatura
         * de consignacao nos termos do artigo 38 do codigo do IVA.
         */
        workDocument.setWorkType("DC");

        // Period
        /*
         * Per?odo contabil?stico (Period) . . . . . . . . . . Deve ser
         * indicado o n?mero do m?s do per?odo de tributa??o, de ?1? a ?12?,
         * contado desde a data do in?cio. Pode ainda ser preenchido com
         * ?13?, ?14?, ?15? ou ?16? para movimentos efectuados no ?ltimo m?s
         * do per?odo de tributa??o, relacionados com o apuramento do
         * resultado. Ex.: movimentos de apuramentos de invent?rios,
         * deprecia??es, ajustamentos ou apuramentos de resultados.
         */
        workDocument.setPeriod(document.getDocumentDate().getMonthOfYear());

        // SourceID
        /*
         * C?digo do utilizador que registou o movimento (SourceID).
         */
        workDocument.setSourceID(document.getVersioningCreator());

    } catch (DatatypeConfigurationException e) {

        e.printStackTrace();
    }

    List<oecd.standardauditfile_tax.pt_1.SourceDocuments.WorkingDocuments.WorkDocument.Line> productLines = workDocument
            .getLine();

    // Process individual
    BigInteger i = BigInteger.ONE;
    for (FinantialDocumentEntry docLine : document.getFinantialDocumentEntriesSet()) {
        InvoiceEntry orderNoteLine = (InvoiceEntry) docLine;
        oecd.standardauditfile_tax.pt_1.SourceDocuments.WorkingDocuments.WorkDocument.Line line = convertToSAFTWorkDocumentLine(
                orderNoteLine, baseProducts);

        // LineNumber
        line.setLineNumber(i);

        // Add to productLines
        i = i.add(BigInteger.ONE);
        productLines.add(line);
    }

    return workDocument;
}

From source file:com.cisco.dvbu.ps.common.util.CommonUtils.java

/**
* Returns a sum of CRC32 checksums of all lines/rows in a file.
* This method is used to compare files with the same lines/rows, which may be in different order, in which case we
* still want to consider them equal (from the point of view of containing the same data)
* In such case this method will return the same result.
* 
* This is useful when the file contains results of a database query and we need to compare
* results of two queries that may return the same data but in different order.
*      //from  w w  w. j av a  2s.  c  o m
* @author             SST
* @param filePath      file name with full path
* @return            sum of checksums of each line(row) from the input file
*                   The type of this value could be long for files up to probably several GB in size.
*                   BigInteger was chosen in case even bigger files are used.
* @throws IOException
*/
public static BigInteger fileChecksumByRow(String filePath) throws IOException {

    BigInteger sumOfcheckSumValues = new BigInteger("0");
    long currentLineCheckSumValue = 0L;
    Checksum checksum = new CRC32();

    BufferedReader br = new BufferedReader(new FileReader(filePath));
    String line;

    //       System.out.println("currentLineCheckSumValue: ");
    while ((line = br.readLine()) != null) {
        // Read one line at a time

        byte bytes[] = line.getBytes();
        checksum.reset();
        checksum.update(bytes, 0, bytes.length);

        currentLineCheckSumValue = checksum.getValue();
        //          System.out.println(currentLineCheckSumValue);

        sumOfcheckSumValues = sumOfcheckSumValues.add(BigInteger.valueOf(currentLineCheckSumValue));
    }
    br.close();
    //       System.out.println("fileChecksumByRow(): sumOfcheckSumValues = " + sumOfcheckSumValues);      
    return sumOfcheckSumValues;
}

From source file:com.amazonaws.services.kinesis.clientlibrary.proxies.KinesisLocalFileProxy.java

@Override
public GetRecordsResult get(String serializedKinesisIterator, int maxRecords)
        throws ResourceNotFoundException, InvalidArgumentException, ExpiredIteratorException {
    IteratorInfo iterator = deserializeIterator(serializedKinesisIterator);

    BigInteger startingPosition = new BigInteger(iterator.sequenceNumber);
    BigInteger lastRecordsSeqNo = BigInteger.ONE;
    List<Record> recordsToReturn = new ArrayList<Record>();
    List<Record> shardRecords = shardedDataRecords.get(iterator.shardId);
    if (shardRecords == null) {
        throw new ResourceNotFoundException(iterator.shardId + " does not exist");
    }/*from w ww.  j  ava2s  .  c o  m*/

    boolean isHasMoreShards = false;

    for (int i = 0; i < shardRecords.size(); i++) {
        Record record = shardRecords.get(i);
        BigInteger recordSequenceNumber = new BigInteger(record.getSequenceNumber());
        // update lastRecordsSeqNo so if we return no records, it will be the seqNo of the last record.
        lastRecordsSeqNo = recordSequenceNumber;
        if (recordSequenceNumber.compareTo(startingPosition) >= 0) {
            // Set endIndex (of sublist) to cap at either maxRecords or end of list.
            int endIndex = Math.min(i + maxRecords, shardRecords.size());
            recordsToReturn.addAll(shardRecords.subList(i, endIndex));

            lastRecordsSeqNo = new BigInteger(shardRecords.get(endIndex - 1).getSequenceNumber());
            if (endIndex < shardRecords.size()) {
                isHasMoreShards = true;
            }

            break;
        }
    }

    GetRecordsResult response = new GetRecordsResult();
    response.setRecords(recordsToReturn);

    // Set iterator only if the shard is not closed.
    if (isHasMoreShards || (!closedShards.contains(iterator.shardId))) {
        /*
         * Use the sequence number of the last record returned + 1 to compute the next iterator.
         */
        response.setNextShardIterator(
                serializeIterator(iterator.shardId, lastRecordsSeqNo.add(BigInteger.ONE).toString()));
        LOG.debug("Returning a non null iterator for shard " + iterator.shardId);
    } else {
        LOG.info("Returning null iterator for shard " + iterator.shardId);
    }

    return response;
}

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);
            }//from w ww. j a v  a2  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;

}