Example usage for java.util SortedMap tailMap

List of usage examples for java.util SortedMap tailMap

Introduction

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

Prototype

SortedMap<K, V> tailMap(K fromKey);

Source Link

Document

Returns a view of the portion of this map whose keys are greater than or equal to fromKey .

Usage

From source file:edu.vt.middleware.ldap.search.SearchExecutor.java

/**
 * This performs a Ldap search with the supplied <code>Query</code>.
 *
 * @param  ldapPool  <code>LdapPool</code> to use for searching
 * @param  query  <code>Query</code> to search for
 *
 * @return  <code>Iterator</code> - of search results
 *
 * @throws  PeopleSearchException  if an error occurs searching the Ldap
 *//*from w w w.java2s  .co m*/
public Iterator<SearchResult> executeSearch(final LdapPool<Ldap> ldapPool, final Query query)
        throws PeopleSearchException {
    final SortedMap<Integer, SearchResult> m = new TreeMap<Integer, SearchResult>();
    final List<String> l = new ArrayList<String>();

    if (this.queryTemplates != null && this.queryTemplates.size() > 0) {
        final SearchThread[] threads = new SearchThread[this.queryTemplates.size()];
        for (int i = 1; i <= this.queryTemplates.size(); i++) {
            final String ldapQuery = this.buildLdapQuery(this.getQueryTemplate(query.getQueryParameters(), i),
                    query.getSearchRestrictions());
            if (ldapQuery != null) {
                threads[i - 1] = new SearchThread(ldapPool, ldapQuery, query.getQueryAttributes());
            } else {
                threads[i - 1] = null;
            }
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Performing search with " + threads.length + " threads");
        }

        int count = 0;
        boolean loop = true;
        while (loop && count < threads.length) {
            List<QueryResult> results = null;
            if (additive) {
                results = this.doAdditiveSearch(threads);
            } else {
                results = this.doIterativeSearch(threads[count]);
            }

            if (LOG.isDebugEnabled()) {
                LOG.debug("Loop " + count + " found " + results.size() + " results");
            }
            for (int i = 0; i < results.size(); i++) {
                int j = m.size();
                final QueryResult qr = results.get(i);
                if (qr != null) {
                    final SearchResult sr = qr.getSearchResult();
                    if (sr != null) {
                        if (!l.contains(sr.getName())) {
                            if (additive) {
                                qr.setSearchIteration(i);
                                qr.setTermCount(this.termCount);
                                this.processResults(qr);
                            } else {
                                qr.setSearchIteration(count);
                                qr.setTermCount(this.termCount);
                                this.processResults(qr);
                            }
                            // store for results
                            m.put(new Integer(j++), sr);
                            l.add(sr.getName());
                            if (LOG.isDebugEnabled()) {
                                if (LOG.isDebugEnabled()) {
                                    LOG.debug("Query " + (additive ? i : count) + " found: " + sr.getName());
                                }
                            }
                        }
                    }
                }
            }
            if (additive || !m.isEmpty()) {
                loop = false;
            } else {
                count++;
            }
        }
    } else {
        if (LOG.isWarnEnabled()) {
            LOG.warn("No searches configured");
        }
    }

    Iterator<SearchResult> i = null;
    if (query.getFromResult() != null) {
        if (query.getToResult() != null) {
            if (query.getFromResult().intValue() <= query.getToResult().intValue()) {
                i = m.subMap(query.getFromResult(), query.getToResult()).values().iterator();
            }
        } else {
            i = m.tailMap(query.getFromResult()).values().iterator();
        }
    } else if (query.getToResult() != null) {
        i = m.headMap(query.getToResult()).values().iterator();
    } else {
        i = m.values().iterator();
    }
    return i;
}

From source file:com.google.gwt.emultest.java.util.TreeMapTest.java

/**
 * Test method for 'java.util.SortedMap.lastKey()'.
 *
 * @see java.util.SortedMap#lastKey()//from   w  w  w  .ja  v  a 2 s .  c  o m
 */
public void testLastKey() {
    K[] keys = getSortedKeys();
    V[] values = getSortedValues();
    SortedMap<K, V> map = createNavigableMap();

    // test with a single entry map
    map.put(keys[0], values[0]);
    assertEquals(keys[0], map.lastKey());
    // is it consistent with other methods
    assertEquals(map.keySet().toArray()[0], map.lastKey());
    assertEquals(keys[0], map.firstKey());
    assertEquals(map.firstKey(), map.lastKey());

    // test with two entry map
    map.put(keys[1], values[1]);
    assertEquals(keys[1], map.lastKey());
    assertFalse(keys[0].equals(map.lastKey()));
    // is it consistent with other methods
    assertEquals(map.keySet().toArray()[1], map.lastKey());
    assertEquals(keys[0], map.firstKey());
    assertFalse(map.firstKey().equals(map.lastKey()));

    map.put(keys[2], values[2]);
    map.put(keys[3], values[3]);
    assertEquals(keys[0], map.headMap(keys[1]).lastKey());
    assertEquals(keys[keys.length - 1], map.tailMap(keys[2]).lastKey());
    assertEquals(keys[2], map.subMap(keys[1], keys[3]).lastKey());
}

From source file:com.google.gwt.emultest.java.util.TreeMapTest.java

/**
 * Test method for 'java.util.Map.put(Object, Object)'. This test shows some
 * bad behavior of the TreeMap class before JDK 7. A mapping with null key can
 * be put in but several methods are are unusable afterward.
 *
 * A SortedMap with natural ordering (no comparator) is supposed to throw a
 * null pointer exception if a null keys are "not supported". For a natural
 * ordered TreeMap before JDK 7, a null pointer exception is not thrown. But,
 * the map is left in a state where any other key based methods result in a
 * null pointer exception.//from   www  .j  a  v  a  2  s .c  o  m
 *
 * @see java.util.Map#put(Object, Object)
 */
public void testPut_nullKey() {
    K[] keys = getSortedKeys();
    V[] values = getSortedValues();
    SortedMap<K, V> sortedMap = createNavigableMap();

    if (useNullKey()) {
        assertNull(sortedMap.put(null, values[0]));
        assertTrue(sortedMap.containsValue(values[0]));

        // the map methods the continue to function
        sortedMap.containsValue(null);
        sortedMap.containsValue(values[0]);
        sortedMap.entrySet();
        sortedMap.equals(createMap());
        sortedMap.hashCode();
        sortedMap.isEmpty();
        sortedMap.keySet();
        sortedMap.putAll(createMap());
        sortedMap.size();
        sortedMap.values();

        // all of the sorted map methods still function
        sortedMap.comparator();
        sortedMap.firstKey();
        sortedMap.lastKey();
        sortedMap.subMap(getLessThanMinimumKey(), getGreaterThanMaximumKey());
        sortedMap.headMap(getLessThanMinimumKey());
        sortedMap.tailMap(getLessThanMinimumKey());
    } else if (TestUtils.getJdkVersion() > 6) {
        // nulls are rejected immediately and don't poison the map anymore
        try {
            assertNull(sortedMap.put(null, values[0]));
            fail("should have thrown");
        } catch (NullPointerException e) {
            // expected outcome
        }
        try {
            assertNull(sortedMap.put(null, values[1]));
            fail("expected exception adding second null");
        } catch (NullPointerException e) {
            // expected outcome
        }
        try {
            sortedMap.containsKey(null);
            fail("expected exception on containsKey(null)");
        } catch (NullPointerException e) {
            // expected outcome
        }
        sortedMap.containsKey(keys[0]);
        try {
            sortedMap.get(null);
            fail("expected exception on get(null)");
        } catch (NullPointerException e) {
            // expected outcome
        }
        sortedMap.get(keys[0]);
        try {
            sortedMap.remove(null);
        } catch (NullPointerException e) {
            // expected
        }
        sortedMap.remove(keys[0]);
    } else {
        // before JDK 7, nulls poisoned the map
        try {
            assertNull(sortedMap.put(null, values[0]));
            // note: first null added is not required to throw NPE since no
            // comparisons are needed
        } catch (NullPointerException e) {
            // expected outcome
        }
        try {
            assertNull(sortedMap.put(null, values[1]));
            fail("expected exception adding second null");
        } catch (NullPointerException e) {
            // expected outcome
        }
        try {
            sortedMap.containsKey(null);
            fail("expected exception on containsKey(null)");
        } catch (NullPointerException e) {
            // expected outcome
        }
        try {
            sortedMap.containsKey(keys[0]);
            fail("expected exception on contains(key)");
        } catch (NullPointerException e) {
            // expected outcome
        }
        try {
            sortedMap.get(null);
            fail("expected exception on get(null)");
        } catch (NullPointerException e) {
            // expected outcome
        }
        try {
            sortedMap.get(keys[0]);
            fail("expected exception on get(key)");
        } catch (NullPointerException e) {
            // expected outcome
        }
        try {
            sortedMap.remove(null);
            fail("expected exception on remove(null)");
        } catch (NullPointerException e) {
            // expected outcome
        }
        try {
            sortedMap.remove(keys[0]);
            fail("expected exception on remove(key)");
        } catch (NullPointerException e) {
            // expected outcome
        }
    }
}

From source file:net.sourceforge.subsonic.service.SonosService.java

@Override
public ReorderContainerResult reorderContainer(String id, String from, int to, String updateId) {
    if (id.startsWith(ID_PLAYLIST_PREFIX)) {
        int playlistId = Integer.parseInt(id.replace(ID_PLAYLIST_PREFIX, ""));
        Playlist playlist = playlistService.getPlaylist(playlistId);
        if (playlist != null && playlist.getUsername().equals(getUsername())) {

            SortedMap<Integer, MediaFile> indexToSong = new ConcurrentSkipListMap<Integer, MediaFile>();
            List<MediaFile> songs = playlistService.getFilesInPlaylist(playlistId);
            for (int i = 0; i < songs.size(); i++) {
                indexToSong.put(i, songs.get(i));
            }//w  ww .java2  s.co m

            List<MediaFile> movedSongs = new ArrayList<MediaFile>();
            for (Integer i : parsePlaylistIndices(from)) {
                movedSongs.add(indexToSong.remove(i));
            }

            List<MediaFile> updatedSongs = new ArrayList<MediaFile>();
            updatedSongs.addAll(indexToSong.headMap(to).values());
            updatedSongs.addAll(movedSongs);
            updatedSongs.addAll(indexToSong.tailMap(to).values());

            playlistService.setFilesInPlaylist(playlistId, updatedSongs);
        }
    }
    return new ReorderContainerResult();
}

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

/**
 * Rule?????????KeyNode?????????.<br>
 * ConsistentHash.<br>//from   w  w  w.j  a  va2 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.hadoop.dfs.LeaseManager.java

static private List<Map.Entry<String, Lease>> findLeaseWithPrefixPath(String prefix,
        SortedMap<String, Lease> path2lease) {
    if (LOG.isDebugEnabled()) {
        LOG.debug(LeaseManager.class.getSimpleName() + ".findLease: prefix=" + prefix);
    }//from  ww w .  j a va  2  s .c om

    List<Map.Entry<String, Lease>> entries = new ArrayList<Map.Entry<String, Lease>>();
    final int srclen = prefix.length();

    for (Map.Entry<String, Lease> entry : path2lease.tailMap(prefix).entrySet()) {
        final String p = entry.getKey();
        if (!p.startsWith(prefix)) {
            return entries;
        }
        if (p.length() == srclen || p.charAt(srclen) == Path.SEPARATOR_CHAR) {
            entries.add(entry);
        }
    }
    return entries;
}

From source file:org.apache.hadoop.hbase.client.TestClientNoCluster.java

static ScanResponse doMetaScanResponse(final SortedMap<byte[], Pair<HRegionInfo, ServerName>> meta,
        final AtomicLong sequenceids, final ScanRequest request) {
    ScanResponse.Builder builder = ScanResponse.newBuilder();
    int max = request.getNumberOfRows();
    int count = 0;
    Map<byte[], Pair<HRegionInfo, ServerName>> tail = request.hasScan()
            ? meta.tailMap(request.getScan().getStartRow().toByteArray())
            : meta;//www.ja v  a  2s.c  om
    ClientProtos.Result.Builder resultBuilder = ClientProtos.Result.newBuilder();
    for (Map.Entry<byte[], Pair<HRegionInfo, ServerName>> e : tail.entrySet()) {
        // Can be 0 on open of a scanner -- i.e. rpc to setup scannerid only.
        if (max <= 0)
            break;
        if (++count > max)
            break;
        HRegionInfo hri = e.getValue().getFirst();
        ByteString row = HBaseZeroCopyByteString.wrap(hri.getRegionName());
        resultBuilder.clear();
        resultBuilder.addCell(getRegionInfo(row, hri));
        resultBuilder.addCell(getServer(row, e.getValue().getSecond()));
        resultBuilder.addCell(getStartCode(row));
        builder.addResults(resultBuilder.build());
        // Set more to false if we are on the last region in table.
        if (hri.getEndKey().length <= 0)
            builder.setMoreResults(false);
        else
            builder.setMoreResults(true);
    }
    // If no scannerid, set one.
    builder.setScannerId(request.hasScannerId() ? request.getScannerId() : sequenceids.incrementAndGet());
    return builder.build();
}

From source file:org.apache.hadoop.hbase.security.visibility.VisibilityNewVersionBehaivorTracker.java

@Override
public DeleteResult isDeleted(Cell cell) {
    try {//  ww  w  .j  ava 2 s  . c  o  m
        long duplicateMvcc = prepare(cell);

        for (Map.Entry<Long, DeleteVersionsNode> e : delColMap.tailMap(cell.getSequenceId()).entrySet()) {
            VisibilityDeleteVersionsNode node = (VisibilityDeleteVersionsNode) e.getValue();
            long deleteMvcc = Long.MAX_VALUE;
            SortedMap<Long, TagInfo> deleteVersionMvccs = node.deletesMap.get(cell.getTimestamp());
            if (deleteVersionMvccs != null) {
                SortedMap<Long, TagInfo> tail = deleteVersionMvccs.tailMap(cell.getSequenceId());
                for (Map.Entry<Long, TagInfo> entry : tail.entrySet()) {
                    if (tagMatched(cell, entry.getValue())) {
                        deleteMvcc = tail.firstKey();
                        break;
                    }
                }
            }
            SortedMap<Long, SortedSet<Long>> subMap = node.mvccCountingMap.subMap(cell.getSequenceId(), true,
                    Math.min(duplicateMvcc, deleteMvcc), true);
            for (Map.Entry<Long, SortedSet<Long>> seg : subMap.entrySet()) {
                if (seg.getValue().size() >= maxVersions) {
                    return DeleteResult.VERSION_MASKED;
                }
                seg.getValue().add(cell.getSequenceId());
            }
            if (deleteMvcc < Long.MAX_VALUE) {
                return DeleteResult.VERSION_DELETED;
            }

            if (cell.getTimestamp() <= node.ts && tagMatched(cell, node.tagInfo)) {
                return DeleteResult.COLUMN_DELETED;
            }
        }
        if (duplicateMvcc < Long.MAX_VALUE) {
            return DeleteResult.VERSION_MASKED;
        }
    } catch (IOException e) {
        LOG.error("Error in isDeleted() check! Will treat cell as not deleted", e);
    }
    return DeleteResult.NOT_DELETED;
}

From source file:org.apache.hadoop.yarn.util.Log4jWarningErrorMetricsAppender.java

private List<Integer> getCounts(SortedMap<Long, Integer> map, List<Long> cutoffs) {
    List<Integer> ret = new ArrayList<>();
    Long largestCutoff = Collections.min(cutoffs);
    for (int i = 0; i < cutoffs.size(); ++i) {
        ret.add(0);/* w  w w. j  a va2s. c o m*/
    }
    synchronized (lock) {
        Map<Long, Integer> submap = map.tailMap(largestCutoff);
        for (Map.Entry<Long, Integer> entry : submap.entrySet()) {
            for (int i = 0; i < cutoffs.size(); ++i) {
                if (entry.getKey() >= cutoffs.get(i)) {
                    int tmp = ret.get(i);
                    ret.set(i, tmp + entry.getValue());
                }
            }
        }
    }
    return ret;
}

From source file:org.formix.dsx.serialization.XmlSerializer.java

/**
 * Deserialize an XML tree into the given type.
 * /*from   w  w  w  . ja v a  2 s  . c  o m*/
 * @param root
 *            The XML root element.
 * 
 * @param type
 *            The type of the desired object.
 * 
 * @param <T>
 *            The infered type for the parameter {code type}.
 * 
 * @return a deserialized object from the given XML.
 * 
 * @throws XmlException
 *             Thrown when a problem occurs during deserialization.
 */
public <T> T deserialize(XmlElement root, Class<T> type) throws XmlException {

    if (type.toString().equals("class [B")) {
        @SuppressWarnings("unchecked")
        T value = (T) Base64.decodeBase64(root.getChild(0).toString());
        return value;
    }

    // If the type is a base type from java.util or java.sql or is a
    // collection then decode it directly.
    if (type.getName().startsWith("java.") || Collection.class.isAssignableFrom(type)) {
        @SuppressWarnings("unchecked")
        T value = (T) this.getValue(root, type, null, null);
        return value;
    }

    String rootName = this.capitalize(root.getName());

    String childName = "";
    XmlElement childElem = null;
    if (root.getChild(0) instanceof XmlElement) {
        childElem = (XmlElement) root.getChild(0);
        childName = this.capitalize(childElem.getName());
        if (rootName.equals(childName))
            return this.deserialize(childElem, type);
    }

    T target;
    try {
        target = type.newInstance();
    } catch (Exception e) {
        throw new XmlException("Unable to instanciate type " + type.getName(), e);
    }

    this.onBeforeDeserialization(new SerializationEvent(this, root, target));

    SortedMap<String, Method> methods = this.createMethodMap(type);
    for (XmlContent content : root.getChilds()) {
        if (content instanceof XmlElement) {

            XmlElement elem = (XmlElement) content;
            String methodName = "set" + this.capitalize(elem.getName());
            String signature = methods.tailMap(methodName).firstKey();

            // If the setter is not found for the specified methodName, skip
            // this setter.
            if (signature.startsWith(methodName)) {

                Method setMethod = methods.get(signature);

                Class<?> paramType = setMethod.getParameterTypes()[0];
                try {
                    Object value = this.getValue(elem, paramType, methods, target);
                    setMethod.invoke(target, new Object[] { value });
                } catch (Exception e) {
                    String msg = String.format(
                            "Unable to assign the XMLElement %s to" + " the property [%s.%s] (%s)", elem,
                            type.getName(), setMethod.getName(), signature);
                    throw new XmlException(msg, e);
                }

            } else {
                throw new XmlException(String.format("Unable to find the method %s.", methodName));
            }
        }
    }

    this.onAfterDeserialization(new SerializationEvent(this, root, target));

    return target;
}