Example usage for java.util SortedMap isEmpty

List of usage examples for java.util SortedMap isEmpty

Introduction

In this page you can find the example usage for java.util SortedMap isEmpty.

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this map contains no key-value mappings.

Usage

From source file:okuyama.imdst.util.DataDispatcher.java

/**
 * Rule?????????KeyNode?????????.<br>
 * ConsistentHash.<br>/*w w  w . j  a  v  a2  s .c o m*/
 * ????????????????6?Third????9??<br>
 *
 * @param key 
 * @param useOldCircle 
 * @return String[] ?(??????)
 */
private static String[] decisionConsistentHashKeyNode(String key, boolean useOldCircle) {
    String[] ret = null;
    boolean noWaitFlg = false;
    SortedMap useNodeCircle = null;
    String targetNode = null;
    String[] mainDataNodeInfo = null;
    String[] slaveDataNodeInfo = null;
    String[] thirdDataNodeInfo = null;

    // ??
    String[][] allNodeDetailList = (String[][]) keyNodeMap.get("list");

    // Key?Hash?
    int execKeyInt = sha1Hash4Int(key);

    // ??
    // useOldCircle???????
    if (useOldCircle && oldCircle != null) {
        useNodeCircle = oldCircle;
    } else {
        useNodeCircle = nodeCircle;
    }

    // ?
    int hash = sha1Hash4Int(key);

    if (!useNodeCircle.containsKey(hash)) {
        SortedMap<Integer, Map> tailMap = useNodeCircle.tailMap(hash);
        if (tailMap.isEmpty()) {
            hash = ((Integer) useNodeCircle.firstKey()).intValue();
        } else {
            hash = ((Integer) tailMap.firstKey()).intValue();
        }
    }

    // ???
    targetNode = (String) useNodeCircle.get(hash);

    // ??
    mainDataNodeInfo = (String[]) keyNodeMap.get(targetNode);
    // ??
    slaveDataNodeInfo = (String[]) keyNodeMap.get(targetNode + "_sub");
    // ??
    thirdDataNodeInfo = (String[]) keyNodeMap.get(targetNode + "_third");

    // ????????
    if (thirdDataNodeInfo != null) {
        ret = new String[9];

        ret[3] = slaveDataNodeInfo[0];
        ret[4] = slaveDataNodeInfo[1];
        ret[5] = slaveDataNodeInfo[2];
        ret[6] = thirdDataNodeInfo[0];
        ret[7] = thirdDataNodeInfo[1];
        ret[8] = thirdDataNodeInfo[2];

    } else if (slaveDataNodeInfo != null) {
        // ????????
        ret = new String[6];

        ret[3] = slaveDataNodeInfo[0];
        ret[4] = slaveDataNodeInfo[1];
        ret[5] = slaveDataNodeInfo[2];
    } else {
        ret = new String[3];
    }

    ret[0] = mainDataNodeInfo[0];
    ret[1] = mainDataNodeInfo[1];
    ret[2] = mainDataNodeInfo[2];

    // ??????????(???)
    // ????????Wait
    while (true) {
        noWaitFlg = false;
        // ????
        if (ret.length == 3) {
            if (!StatusUtil.isWaitStatus(mainDataNodeInfo[2]))
                noWaitFlg = true;
        }

        if (ret.length == 6) {
            if (!StatusUtil.isWaitStatus(mainDataNodeInfo[2])
                    && !StatusUtil.isWaitStatus(slaveDataNodeInfo[2])) {

                noWaitFlg = true;
            }
        }

        if (ret.length == 9) {
            if (!StatusUtil.isWaitStatus(mainDataNodeInfo[2]) && !StatusUtil.isWaitStatus(slaveDataNodeInfo[2])
                    && !StatusUtil.isWaitStatus(thirdDataNodeInfo[2])) {

                noWaitFlg = true;
            }
        }

        if (noWaitFlg)
            break;

        try {
            //System.out.println("DataDispatcher - ?");
            Thread.sleep(50);
        } catch (Exception e) {
        }
    }

    // ??
    // ?MasterManagerHelper??
    StatusUtil.addNodeUse(mainDataNodeInfo[2]);

    if (ret.length > 3) {
        StatusUtil.addNodeUse(slaveDataNodeInfo[2]);
    }

    if (ret.length > 6) {
        StatusUtil.addNodeUse(thirdDataNodeInfo[2]);
    }

    return ret;
}

From source file:org.apache.sling.commons.metrics.internal.MetricWebConsolePlugin.java

private void addMeterDetails(PrintWriter pw, SortedMap<String, Meter> meters) {
    if (meters.isEmpty()) {
        return;//from  w  ww .  jav a  2s  .  c o m
    }
    pw.println("<br>");
    pw.println("<div class='table'>");
    pw.println("<div class='ui-widget-header ui-corner-top buttonGroup'>Meters</div>");
    pw.println("<table class='nicetable' id='data-meters'>");
    pw.println("<thead>");
    pw.println("<tr>");
    pw.println("<th class='header'>Name</th>");
    pw.println("<th class='header'>Count</th>");
    pw.println("<th class='header'>Mean Rate</th>");
    pw.println("<th class='header'>OneMinuteRate</th>");
    pw.println("<th class='header'>FiveMinuteRate</th>");
    pw.println("<th class='header'>FifteenMinuteRate</ th>");
    pw.println("<th>RateUnit</th>");
    pw.println("</tr>");
    pw.println("</thead>");
    pw.println("<tbody>");

    String rowClass = "odd";
    for (Map.Entry<String, Meter> e : meters.entrySet()) {
        Meter m = e.getValue();
        String name = e.getKey();

        double rateFactor = timeUnit.rateFor(name).toSeconds(1);
        String rateUnit = "events/" + calculateRateUnit(timeUnit.rateFor(name));
        pw.printf("<tr class='%s ui-state-default'>%n", rowClass);

        pw.printf("<td>%s</td>", name);
        pw.printf("<td>%d</td>", m.getCount());
        pw.printf("<td>%f</td>", m.getMeanRate() * rateFactor);
        pw.printf("<td>%f</td>", m.getOneMinuteRate() * rateFactor);
        pw.printf("<td>%f</td>", m.getFiveMinuteRate() * rateFactor);
        pw.printf("<td>%f</td>", m.getFifteenMinuteRate() * rateFactor);
        pw.printf("<td>%s</td>", rateUnit);

        pw.println("</tr>");
        rowClass = "odd".equals(rowClass) ? "even" : "odd";
    }

    pw.println("</tbody>");
    pw.println("</table>");
    pw.println("</div>");
}

From source file:co.rsk.peg.BridgeStorageProviderTest.java

@Test
public void createSaveAndRecreateInstance() throws IOException {
    Repository repository = new RepositoryImpl();
    Repository track = repository.startTracking();

    BridgeStorageProvider provider0 = new BridgeStorageProvider(track, PrecompiledContracts.BRIDGE_ADDR);
    provider0.getBtcTxHashesAlreadyProcessed();
    provider0.getRskTxsWaitingForBroadcasting();
    provider0.getRskTxsWaitingForConfirmations();
    provider0.getRskTxsWaitingForSignatures();
    provider0.getBtcUTXOs();/*ww w .java2s .  com*/
    provider0.save();
    track.commit();

    track = repository.startTracking();

    byte[] contractAddress = Hex.decode(PrecompiledContracts.BRIDGE_ADDR);

    Assert.assertNotNull(repository.getContractDetails(contractAddress));
    Assert.assertNotNull(repository.getStorageBytes(contractAddress, new DataWord("btcTxHashesAP".getBytes())));
    Assert.assertNotNull(
            repository.getStorageBytes(contractAddress, new DataWord("rskTxsWaitingFC".getBytes())));
    Assert.assertNotNull(
            repository.getStorageBytes(contractAddress, new DataWord("rskTxsWaitingFS".getBytes())));
    Assert.assertNotNull(
            repository.getStorageBytes(contractAddress, new DataWord("rskTxsWaitingFB".getBytes())));
    Assert.assertNotNull(repository.getStorageBytes(contractAddress, new DataWord("btcUTXOs".getBytes())));

    BridgeStorageProvider provider = new BridgeStorageProvider(track, PrecompiledContracts.BRIDGE_ADDR);

    SortedSet<Sha256Hash> processed = provider.getBtcTxHashesAlreadyProcessed();

    Assert.assertNotNull(processed);
    Assert.assertTrue(processed.isEmpty());

    SortedMap<Sha3Hash, Pair<BtcTransaction, Long>> broadcasting = provider.getRskTxsWaitingForBroadcasting();

    Assert.assertNotNull(broadcasting);
    Assert.assertTrue(broadcasting.isEmpty());

    SortedMap<Sha3Hash, BtcTransaction> confirmations = provider.getRskTxsWaitingForConfirmations();

    Assert.assertNotNull(confirmations);
    Assert.assertTrue(confirmations.isEmpty());

    SortedMap<Sha3Hash, BtcTransaction> signatures = provider.getRskTxsWaitingForSignatures();

    Assert.assertNotNull(signatures);
    Assert.assertTrue(signatures.isEmpty());

    List<UTXO> utxos = provider.getBtcUTXOs();

    Assert.assertNotNull(utxos);
    Assert.assertTrue(utxos.isEmpty());

    Wallet wallet = provider.getWallet();

    Assert.assertNotNull(wallet);
    Assert.assertNotNull(wallet.getCoinSelector());
}

From source file:org.cloudata.core.client.TabletLocationCache.java

protected TabletInfo findFromCache(String tableName, TreeMap<Row.Key, TabletInfo> cache, Row.Key cacheRowKey,
        Row.Key dataRowKey) {/*w w  w. j  a  va 2 s.c o  m*/
    cacheLock.obtainReadLock();
    try {
        if (cache.containsKey(cacheRowKey)) {
            TabletInfo tabletInfo = cache.get(cacheRowKey);
            if (tabletInfo.belongRowRange(cacheRowKey)) {
                return tabletInfo;
            } else {
                return null;
            }
        }

        SortedMap<Row.Key, TabletInfo> tailMap = cache.tailMap(cacheRowKey);
        if (tailMap.isEmpty()) {
            return null;
        }
        Row.Key tailFirst = tailMap.firstKey();

        TabletInfo tabletInfo = tailMap.get(tailFirst);
        if (tableName.equals(tabletInfo.getTableName()) && tabletInfo.belongRowRange(dataRowKey)) {
            return tabletInfo;
        } else {
            return null;
        }
    } finally {
        cacheLock.releaseReadLock();
    }
}

From source file:org.apache.tajo.util.metrics.reporter.MetricsStreamScheduledReporter.java

@Override
public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters,
        SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters,
        SortedMap<String, Timer> timers) {
    final String dateTime = dateFormat == null ? "" + clock.getTime()
            : dateFormat.format(new Date(clock.getTime()));

    if (!gauges.isEmpty()) {
        Map<String, Map<String, Gauge>> gaugeGroups = findMetricsItemGroup(gauges);

        for (Map.Entry<String, Map<String, Gauge>> eachGroup : gaugeGroups.entrySet()) {
            printGaugeGroup(dateTime, eachGroup.getKey(), eachGroup.getValue());
        }/*www . j a  v a  2  s.com*/
    }

    if (!counters.isEmpty()) {
        Map<String, Map<String, Counter>> counterGroups = findMetricsItemGroup(counters);

        for (Map.Entry<String, Map<String, Counter>> eachGroup : counterGroups.entrySet()) {
            printCounterGroup(dateTime, eachGroup.getKey(), eachGroup.getValue());
        }
    }

    if (!histograms.isEmpty()) {
        Map<String, Map<String, Histogram>> histogramGroups = findMetricsItemGroup(histograms);

        for (Map.Entry<String, Map<String, Histogram>> eachGroup : histogramGroups.entrySet()) {
            printHistogramGroup(dateTime, eachGroup.getKey(), eachGroup.getValue());
        }
    }

    if (!meters.isEmpty()) {
        Map<String, Map<String, Meter>> meterGroups = findMetricsItemGroup(meters);

        for (Map.Entry<String, Map<String, Meter>> eachGroup : meterGroups.entrySet()) {
            printMeterGroup(dateTime, eachGroup.getKey(), eachGroup.getValue());
        }
    }

    if (!timers.isEmpty()) {
        Map<String, Map<String, Timer>> timerGroups = findMetricsItemGroup(timers);

        for (Map.Entry<String, Map<String, Timer>> eachGroup : timerGroups.entrySet()) {
            printTimerGroup(dateTime, eachGroup.getKey(), eachGroup.getValue());
        }
    }
    try {
        output.flush();
    } catch (IOException e) {
    }
}

From source file:org.apache.sling.commons.metrics.internal.MetricWebConsolePlugin.java

private void addHistogramDetails(PrintWriter pw, SortedMap<String, Histogram> histograms) {
    if (histograms.isEmpty()) {
        return;// w w  w .ja  v a  2s  .  co  m
    }

    pw.println("<br>");
    pw.println("<div class='table'>");
    pw.println("<div class='ui-widget-header ui-corner-top buttonGroup'>Histograms</div>");
    pw.println("<table class='nicetable' id='data-histograms'>");
    pw.println("<thead>");
    pw.println("<tr>");
    pw.println("<th class='header'>Name</th>");
    pw.println("<th class='header'>Count</th>");
    pw.println("<th class='header'>50%</th>");
    pw.println("<th class='header'>Min</th>");
    pw.println("<th class='header'>Max</th>");
    pw.println("<th class='header'>Mean</th>");
    pw.println("<th class='header'>StdDev</th>");
    pw.println("<th class='header'>75%</th>");
    pw.println("<th class='header'>95%</th>");
    pw.println("<th class='header'>98%</th>");
    pw.println("<th class='header'>99%</th>");
    pw.println("<th class='header'>999%</th>");
    pw.println("<th>Duration Unit</th>");
    pw.println("</tr>");
    pw.println("</thead>");
    pw.println("<tbody>");

    String rowClass = "odd";
    for (Map.Entry<String, Histogram> e : histograms.entrySet()) {
        Histogram h = e.getValue();
        Snapshot s = h.getSnapshot();
        String name = e.getKey();

        double durationFactor = 1.0 / timeUnit.durationFor(name).toNanos(1);
        String durationUnit = timeUnit.durationFor(name).toString().toLowerCase(Locale.US);
        pw.printf("<tr class='%s ui-state-default'>%n", rowClass);

        pw.printf("<td>%s</td>", name);
        pw.printf("<td>%d</td>", h.getCount());
        pw.printf("<td>%f</td>", s.getMedian() * durationFactor);
        pw.printf("<td>%f</td>", s.getMin() * durationFactor);
        pw.printf("<td>%f</td>", s.getMax() * durationFactor);
        pw.printf("<td>%f</td>", s.getMean() * durationFactor);
        pw.printf("<td>%f</td>", s.getStdDev() * durationFactor);

        pw.printf("<td>%f</td>", s.get75thPercentile() * durationFactor);
        pw.printf("<td>%f</td>", s.get95thPercentile() * durationFactor);
        pw.printf("<td>%f</td>", s.get98thPercentile() * durationFactor);
        pw.printf("<td>%f</td>", s.get99thPercentile() * durationFactor);
        pw.printf("<td>%f</td>", s.get999thPercentile() * durationFactor);

        pw.printf("<td>%s</td>", durationUnit);

        pw.println("</tr>");
        rowClass = "odd".equals(rowClass) ? "even" : "odd";
    }

    pw.println("</tbody>");
    pw.println("</table>");
    pw.println("</div>");
}

From source file:org.apache.sling.commons.metrics.internal.MetricWebConsolePlugin.java

private void addTimerDetails(PrintWriter pw, SortedMap<String, Timer> timers) {
    if (timers.isEmpty()) {
        return;/*from   w w w .  j  a va  2  s.co m*/
    }

    pw.println("<br>");
    pw.println("<div class='table'>");
    pw.println("<div class='ui-widget-header ui-corner-top buttonGroup'>Timers</div>");
    pw.println("<table class='nicetable' id='data-timers'>");
    pw.println("<thead>");
    pw.println("<tr>");
    pw.println("<th class='header'>Name</th>");
    pw.println("<th class='header'>Count</th>");
    pw.println("<th class='header'>Mean Rate</th>");
    pw.println("<th class='header'>1 min rate</th>");
    pw.println("<th class='header'>5 mins rate</th>");
    pw.println("<th class='header'>15 mins rate</th>");
    pw.println("<th class='header'>50%</th>");
    pw.println("<th class='header'>Min</th>");
    pw.println("<th class='header'>Max</th>");
    pw.println("<th class='header'>Mean</th>");
    pw.println("<th class='header'>StdDev</th>");
    pw.println("<th class='header'>75%</th>");
    pw.println("<th class='header'>95%</th>");
    pw.println("<th class='header'>98%</th>");
    pw.println("<th class='header'>99%</th>");
    pw.println("<th class='header'>999%</th>");
    pw.println("<th>Rate Unit</th>");
    pw.println("<th>Duration Unit</th>");
    pw.println("</tr>");
    pw.println("</thead>");
    pw.println("<tbody>");

    String rowClass = "odd";
    for (Map.Entry<String, Timer> e : timers.entrySet()) {
        Timer t = e.getValue();
        Snapshot s = t.getSnapshot();
        String name = e.getKey();

        double rateFactor = timeUnit.rateFor(name).toSeconds(1);
        String rateUnit = "events/" + calculateRateUnit(timeUnit.rateFor(name));

        double durationFactor = 1.0 / timeUnit.durationFor(name).toNanos(1);
        String durationUnit = timeUnit.durationFor(name).toString().toLowerCase(Locale.US);

        pw.printf("<tr class='%s ui-state-default'>%n", rowClass);

        pw.printf("<td>%s</td>", name);
        pw.printf("<td>%d</td>", t.getCount());
        pw.printf("<td>%f</td>", t.getMeanRate() * rateFactor);
        pw.printf("<td>%f</td>", t.getOneMinuteRate() * rateFactor);
        pw.printf("<td>%f</td>", t.getFiveMinuteRate() * rateFactor);
        pw.printf("<td>%f</td>", t.getFifteenMinuteRate() * rateFactor);

        pw.printf("<td>%f</td>", s.getMedian() * durationFactor);
        pw.printf("<td>%f</td>", s.getMin() * durationFactor);
        pw.printf("<td>%f</td>", s.getMax() * durationFactor);
        pw.printf("<td>%f</td>", s.getMean() * durationFactor);
        pw.printf("<td>%f</td>", s.getStdDev() * durationFactor);

        pw.printf("<td>%f</td>", s.get75thPercentile() * durationFactor);
        pw.printf("<td>%f</td>", s.get95thPercentile() * durationFactor);
        pw.printf("<td>%f</td>", s.get98thPercentile() * durationFactor);
        pw.printf("<td>%f</td>", s.get99thPercentile() * durationFactor);
        pw.printf("<td>%f</td>", s.get999thPercentile() * durationFactor);

        pw.printf("<td>%s</td>", rateUnit);
        pw.printf("<td>%s</td>", durationUnit);

        pw.println("</tr>");
        rowClass = "odd".equals(rowClass) ? "even" : "odd";
    }

    pw.println("</tbody>");
    pw.println("</table>");
    pw.println("</div>");
}

From source file:edu.mit.ll.graphulo.pig.backend.GraphuloOneTableStorage.java

@Override
protected Tuple getTuple(Key key, Value value) throws IOException {
    SortedMap<Key, Value> rowKVs = WholeRowIterator.decodeRow(key, value);
    Tuple tuple = TupleFactory.getInstance().newTuple(columns.size() + 1);

    final Text cfHolder = new Text();
    final Text cqHolder = new Text();
    final Text row = key.getRow();
    int tupleOffset = 0;

    tuple.set(tupleOffset, new DataByteArray(Text.decode(row.getBytes(), 0, row.getLength())));

    for (Column column : this.columns) {
        tupleOffset++;//from w  w w  .ja  v  a 2  s . c om

        switch (column.getType()) {
        case LITERAL:
            cfHolder.set(column.getColumnFamily());
            if (null != column.getColumnQualifier()) {
                cqHolder.set(column.getColumnQualifier());
            } else {
                cqHolder.set(EMPTY_TEXT);
            }

            // Get the key where our literal would exist (accounting for
            // "colf:colq" or "colf:" empty colq)
            Key literalStartKey = new Key(row, cfHolder, cqHolder);

            SortedMap<Key, Value> tailMap = rowKVs.tailMap(literalStartKey);

            // Find the element
            if (tailMap.isEmpty()) {
                tuple.set(tupleOffset, EMPTY_DATA_BYTE_ARRAY);
            } else {
                Key actualKey = tailMap.firstKey();

                // Only place it in the tuple if it matches the user
                // request, avoid using a value from a
                // key with the wrong colqual
                if (0 == literalStartKey.compareTo(actualKey, PartialKey.ROW_COLFAM_COLQUAL)) {
                    tuple.set(tupleOffset, new DataByteArray(tailMap.get(actualKey).get()));
                } else {
                    // This row doesn't have the column we were looking for
                    tuple.set(tupleOffset, EMPTY_DATA_BYTE_ARRAY);
                }
            }

            break;
        case COLFAM_PREFIX:
            cfHolder.set(column.getColumnFamily());
            Range colfamPrefixRange = Range.prefix(row, cfHolder);
            Key colfamPrefixStartKey = new Key(row, cfHolder);

            SortedMap<Key, Value> cfTailMap = rowKVs.tailMap(colfamPrefixStartKey);

            // Find the element
            if (cfTailMap.isEmpty()) {
                tuple.set(tupleOffset, EMPTY_DATA_BYTE_ARRAY);
            } else {
                HashMap<String, DataByteArray> tupleMap = new HashMap<String, DataByteArray>();

                // Build up a map for all the entries in this row that match
                // the colfam prefix
                for (Entry<Key, Value> entry : cfTailMap.entrySet()) {
                    if (colfamPrefixRange.contains(entry.getKey())) {
                        entry.getKey().getColumnFamily(cfHolder);
                        entry.getKey().getColumnQualifier(cqHolder);
                        DataByteArray val = new DataByteArray(entry.getValue().get());

                        // Avoid adding an extra ':' when colqual is empty
                        if (0 == cqHolder.getLength()) {
                            tupleMap.put(cfHolder.toString(), val);
                        } else {
                            tupleMap.put(cfHolder.toString() + COLON + cqHolder.toString(), val);
                        }
                    } else {
                        break;
                    }
                }

                if (!tupleMap.isEmpty()) {
                    tuple.set(tupleOffset, tupleMap);
                }
            }

            break;
        case COLQUAL_PREFIX:
            cfHolder.set(column.getColumnFamily());
            cqHolder.set(column.getColumnQualifier());
            Range colqualPrefixRange = Range.prefix(row, cfHolder, cqHolder);
            Key colqualPrefixStartKey = new Key(row, cfHolder, cqHolder);

            SortedMap<Key, Value> cqTailMap = rowKVs.tailMap(colqualPrefixStartKey);
            if (cqTailMap.isEmpty()) {
                tuple.set(tupleOffset, EMPTY_DATA_BYTE_ARRAY);
            } else {
                HashMap<String, DataByteArray> tupleMap = new HashMap<String, DataByteArray>();

                // Build up a map for all the entries in this row that match
                // the colqual prefix
                for (Entry<Key, Value> entry : cqTailMap.entrySet()) {
                    if (colqualPrefixRange.contains(entry.getKey())) {
                        entry.getKey().getColumnFamily(cfHolder);
                        entry.getKey().getColumnQualifier(cqHolder);
                        DataByteArray val = new DataByteArray(entry.getValue().get());

                        // Avoid the extra ':' on empty colqual
                        if (0 == cqHolder.getLength()) {
                            tupleMap.put(cfHolder.toString(), val);
                        } else {
                            tupleMap.put(cfHolder.toString() + COLON + cqHolder.toString(), val);
                        }
                    } else {
                        break;
                    }
                }

                if (!tupleMap.isEmpty()) {
                    tuple.set(tupleOffset, tupleMap);
                }
            }

            break;
        default:
            break;
        }
    }

    return tuple;
}

From source file:org.apache.hadoop.mapred.MockSimulatorJobTracker.java

@Override
public HeartbeatResponse heartbeat(TaskTrackerStatus status, boolean restarted, boolean initialContact,
        boolean acceptNewTasks, short responseId) throws IOException {
    if (!(status instanceof SimulatorTaskTrackerStatus)) {
        throw new IllegalArgumentException(
                "Expecting SimulatorTaskTrackerStatus, actual status type " + status.getClass());
    }/*from  ww  w.  j  ava 2s  . c  o  m*/
    SimulatorTaskTrackerStatus trackerStatus = (SimulatorTaskTrackerStatus) status;
    long now = trackerStatus.getCurrentSimulationTime();
    String trackerName = status.getTrackerName();

    LOG.debug("Received heartbeat() from trackerName=" + trackerName + ", now=" + now);

    HeartbeatResponse response = new HeartbeatResponse();
    response.setHeartbeatInterval(heartbeatInterval);
    response.setActions(new TaskTrackerAction[0]);

    if (checkHeartbeats) {
        Assert.assertFalse("No more heartbeats were expected ", heartbeats.isEmpty());
        long nextToCheck = heartbeats.firstKey();
        // Missing heartbeat check
        Assert.assertTrue(nextToCheck <= now);
        if (nextToCheck < now) {
            LOG.debug("Simulation time progressed, last checked heartbeat at=" + nextToCheck + ", now=" + now
                    + ". Checking if no " + "required heartbeats were missed in the past");
            SortedMap<String, HeartbeatHelper> previousHeartbeats = heartbeats.get(nextToCheck);
            Assert.assertNotNull(previousHeartbeats);
            Assert.assertTrue(previousHeartbeats.isEmpty());
            heartbeats.remove(nextToCheck);
            nextToCheck = heartbeats.firstKey();
        }
        Assert.assertEquals("Heartbeat at the wrong time", nextToCheck, now);

        SortedMap<String, HeartbeatHelper> currentHeartbeats = heartbeats.get(now);
        HeartbeatHelper currentHeartbeat = currentHeartbeats.get(trackerName);
        Assert.assertNotNull("Unknown task tracker name=" + trackerName, currentHeartbeat);
        currentHeartbeats.remove(trackerName);

        currentHeartbeat.checkHeartbeatParameters(status, acceptNewTasks);

        response.setActions(currentHeartbeat.getTaskTrackerActions());
    }
    return response;
}

From source file:com.palantir.atlasdb.keyvalue.impl.InMemoryKeyValueService.java

private <T> ClosableIterator<RowResult<T>> getRangeInternal(String tableName, final RangeRequest range,
        final ResultProducer<T> resultProducer) {
    ConcurrentNavigableMap<Key, byte[]> tableMap = getTableMap(tableName).entries;
    if (range.isReverse()) {
        tableMap = tableMap.descendingMap();
    }/* ww w. jav a  2s.  com*/
    if (range.getStartInclusive().length != 0) {
        if (range.isReverse()) {
            Cell startCell = Cells.createLargestCellForRow(range.getStartInclusive());
            tableMap = tableMap.tailMap(new Key(startCell, Long.MIN_VALUE));
        } else {
            Cell startCell = Cells.createSmallestCellForRow(range.getStartInclusive());
            tableMap = tableMap.tailMap(new Key(startCell, Long.MIN_VALUE));
        }
    }
    if (range.getEndExclusive().length != 0) {
        if (range.isReverse()) {
            Cell endCell = Cells.createLargestCellForRow(range.getEndExclusive());
            tableMap = tableMap.headMap(new Key(endCell, Long.MAX_VALUE));
        } else {
            Cell endCell = Cells.createSmallestCellForRow(range.getEndExclusive());
            tableMap = tableMap.headMap(new Key(endCell, Long.MAX_VALUE));
        }
    }
    final PeekingIterator<Entry<Key, byte[]>> it = Iterators.peekingIterator(tableMap.entrySet().iterator());
    return ClosableIterators.wrap(new AbstractIterator<RowResult<T>>() {
        @Override
        protected RowResult<T> computeNext() {
            while (true) {
                if (!it.hasNext()) {
                    return endOfData();
                }
                ImmutableSortedMap.Builder<byte[], T> result = ImmutableSortedMap
                        .orderedBy(UnsignedBytes.lexicographicalComparator());
                Key key = it.peek().getKey();
                byte[] row = key.row;
                Iterator<Entry<Key, byte[]>> cellIter = takeCell(it, key);
                collectValueForTimestamp(key.col, cellIter, result, range, resultProducer);

                while (it.hasNext()) {
                    if (!it.peek().getKey().matchesRow(row)) {
                        break;
                    }
                    key = it.peek().getKey();
                    cellIter = takeCell(it, key);
                    collectValueForTimestamp(key.col, cellIter, result, range, resultProducer);
                }
                SortedMap<byte[], T> columns = result.build();
                if (!columns.isEmpty()) {
                    return RowResult.create(row, columns);
                }
            }
        }

    });
}