Example usage for java.util NavigableMap put

List of usage examples for java.util NavigableMap put

Introduction

In this page you can find the example usage for java.util NavigableMap put.

Prototype

V put(K key, V value);

Source Link

Document

Associates the specified value with the specified key in this map (optional operation).

Usage

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

/**
 * Test method for 'java.util.SortedMap.tailMap(Object, Object)'.
 *
 * @see java.util.SortedMap#tailMap(Object)
 *//*w  ww  .j  a v a2 s .c o  m*/
@SuppressWarnings("unchecked")
public void testTailMap_throwsClassCastException() {
    K[] keys = getKeys();
    V[] values = getValues();
    NavigableMap map = createNavigableMap();
    if (isNaturalOrder()) {
        // TODO Why does this succeed with natural ordering when subMap doesn't?
        map.tailMap(getConflictingKey());
    } else {
        try {
            map.tailMap(getConflictingKey());
            fail("ClassCastException expected");
        } catch (ClassCastException expected) {
        }
    }

    map.put(keys[0], values[0]);
    if (isNaturalOrder()) {
        // TODO Why does this succeed with natural ordering when subMap doesn't?
        map.tailMap(getConflictingKey());
    } else {
        try {
            map.tailMap(getConflictingKey());
            fail("ClassCastException expected");
        } catch (ClassCastException expected) {
        }
    }
}

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

/**
 * Test method for 'java.util.SortedMap.subMap(Object, Object)' and
 * 'java.util.NavigableMap.subMap(Object, boolean, Object, boolean)'.
 *
 * @see java.util.SortedMap#subMap(Object, Object)
 * @see java.util.NavigableMap#subMap(Object, boolean, Object, boolean)
 */// ww w . j  a  v  a 2s  .c  o m
public void testSubMap() {
    K[] keys = getSortedKeys();
    V[] values = getSortedValues();
    NavigableMap<K, V> map = createNavigableMap();
    // test with no entries
    assertEquals(0, map.subMap(keys[0], keys[0]).size());
    assertEquals(0, map.subMap(keys[0], false, keys[0], false).size());
    assertEquals(0, map.subMap(keys[0], true, keys[0], false).size());
    assertEquals(0, map.subMap(keys[0], false, keys[0], true).size());
    assertEquals(0, map.subMap(keys[0], true, keys[0], true).size());

    // test with a single entry map
    map.put(keys[0], values[0]);

    assertEquals(0, map.subMap(keys[0], keys[0]).size());
    // bounded by a "wide" range
    assertEquals(1, map.subMap(getLessThanMinimumKey(), getGreaterThanMaximumKey()).size());
    assertEquals(1, map.subMap(getLessThanMinimumKey(), false, getGreaterThanMaximumKey(), false).size());
    assertEquals(1, map.subMap(getLessThanMinimumKey(), true, getGreaterThanMaximumKey(), false).size());
    assertEquals(1, map.subMap(getLessThanMinimumKey(), false, getGreaterThanMaximumKey(), true).size());
    assertEquals(1, map.subMap(getLessThanMinimumKey(), true, getGreaterThanMaximumKey(), true).size());

    // test with two entry map
    map.put(keys[1], values[1]);

    assertEquals(1, map.subMap(keys[0], keys[1]).size());
    assertEquals(keys[0], map.subMap(keys[0], keys[1]).keySet().toArray()[0]);

    assertEquals(0, map.subMap(keys[0], false, keys[1], false).size());

    assertEquals(1, map.subMap(keys[0], false, keys[1], true).size());
    assertEquals(keys[1], map.subMap(keys[0], false, keys[1], true).keySet().toArray()[0]);

    assertEquals(1, map.subMap(keys[0], true, keys[1], false).size());
    assertEquals(keys[0], map.subMap(keys[0], true, keys[1], false).keySet().toArray()[0]);

    assertEquals(2, map.subMap(keys[0], true, keys[1], true).size());
    assertEquals(keys[0], map.subMap(keys[0], true, keys[1], true).keySet().toArray()[0]);
    assertEquals(keys[1], map.subMap(keys[0], true, keys[1], true).keySet().toArray()[1]);

    // bounded by a "wide" range
    assertEquals(2, map.subMap(getLessThanMinimumKey(), getGreaterThanMaximumKey()).size());

    assertEquals(2, map.subMap(getLessThanMinimumKey(), false, getGreaterThanMaximumKey(), false).size());
    assertEquals(1, map.subMap(keys[0], false, getGreaterThanMaximumKey(), false).size());
    assertEquals(0, map.subMap(keys[0], false, keys[1], false).size());
    assertEquals(2, map.subMap(keys[0], true, getGreaterThanMaximumKey(), false).size());
    assertEquals(1, map.subMap(keys[0], true, keys[1], false).size());
    assertEquals(2, map.subMap(keys[0], true, getGreaterThanMaximumKey(), true).size());
    assertEquals(2, map.subMap(keys[0], true, keys[1], true).size());
}

From source file:org.alfresco.repo.imap.ImapServiceImpl.java

/**
 * Search for emails in specified folder depending on view mode.
 * //from ww  w.j ava2  s. c o  m
 * Shallow list of files
 * 
 * @param contextNodeRef context folder for search
 * @param viewMode context folder view mode
 * @return list of emails that context folder contains.
 */
public FolderStatus getFolderStatus(final String userName, final NodeRef contextNodeRef,
        ImapViewMode viewMode) {
    if (logger.isDebugEnabled()) {
        logger.debug("getFolderStatus contextNodeRef=" + contextNodeRef + ", viewMode=" + viewMode);
    }

    // No need to ACL check the change token read
    String changeToken = AuthenticationUtil.runAs(new RunAsWork<String>() {
        @Override
        public String doWork() throws Exception {
            return (String) nodeService.getProperty(contextNodeRef, ImapModel.PROP_CHANGE_TOKEN);
        }
    }, AuthenticationUtil.getSystemUserName());

    Pair<String, String> cacheKey = null;
    if (changeToken != null) {
        cacheKey = new Pair<String, String>(userName, changeToken);
        this.folderCacheLock.readLock().lock();
        try {
            FolderStatus result = this.folderCache.get(cacheKey);
            if (result != null) {
                return result;
            }
        } finally {
            this.folderCacheLock.readLock().unlock();
        }
    }

    List<FileInfo> fileInfos = null;
    FileFilterMode.setClient(Client.imap);
    try {
        fileInfos = fileFolderService.listFiles(contextNodeRef);
    } finally {
        FileFilterMode.clearClient();
    }

    final NavigableMap<Long, FileInfo> currentSearch = new TreeMap<Long, FileInfo>();

    switch (viewMode) {
    case MIXED:
        for (FileInfo fileInfo : fileInfos) {
            currentSearch.put((Long) fileInfo.getProperties().get(ContentModel.PROP_NODE_DBID), fileInfo);
        }
        break;
    case ARCHIVE:
        for (FileInfo fileInfo : fileInfos) {
            if (nodeService.hasAspect(fileInfo.getNodeRef(), ImapModel.ASPECT_IMAP_CONTENT)) {
                currentSearch.put((Long) fileInfo.getProperties().get(ContentModel.PROP_NODE_DBID), fileInfo);
            }
        }
        break;
    case VIRTUAL:
        for (FileInfo fileInfo : fileInfos) {
            if (!nodeService.hasAspect(fileInfo.getNodeRef(), ImapModel.ASPECT_IMAP_CONTENT)) {
                currentSearch.put((Long) fileInfo.getProperties().get(ContentModel.PROP_NODE_DBID), fileInfo);
            }
        }
        break;
    }

    int messageCount = currentSearch.size(), recentCount = 0, unseenCount = 0, firstUnseen = 0;
    int i = 1;
    for (FileInfo fileInfo : currentSearch.values()) {
        Flags flags = getFlags(fileInfo);
        if (flags.contains(Flags.Flag.RECENT)) {
            recentCount++;
        }
        if (!flags.contains(Flags.Flag.SEEN)) {
            if (firstUnseen == 0) {
                firstUnseen = i;
            }
            unseenCount++;
        }
        i++;
    }
    // Add the IMAP folder aspect with appropriate initial values if it is not already there
    if (changeToken == null) {
        changeToken = GUID.generate();
        cacheKey = new Pair<String, String>(userName, changeToken);
        final String finalToken = changeToken;
        doAsSystem(new RunAsWork<Void>() {
            @Override
            public Void doWork() throws Exception {
                nodeService.setProperty(contextNodeRef, ImapModel.PROP_CHANGE_TOKEN, finalToken);
                nodeService.setProperty(contextNodeRef, ImapModel.PROP_MAXUID,
                        currentSearch.isEmpty() ? 0 : currentSearch.lastKey());
                return null;
            }
        });
    }
    Long uidValidity = (Long) nodeService.getProperty(contextNodeRef, ImapModel.PROP_UIDVALIDITY);
    FolderStatus result = new FolderStatus(messageCount, recentCount, firstUnseen, unseenCount,
            uidValidity == null ? 0 : uidValidity, changeToken, currentSearch);
    this.folderCacheLock.writeLock().lock();
    try {
        FolderStatus oldResult = this.folderCache.get(cacheKey);
        if (oldResult != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("At end of getFolderStatus. Found info in cache, changeToken:" + changeToken);
            }

            return oldResult;
        }
        this.folderCache.put(cacheKey, result);

        if (logger.isDebugEnabled()) {
            logger.debug("At end of getFolderStatus. Found files:" + currentSearch.size() + ", changeToken:"
                    + changeToken);
        }
        return result;
    } finally {
        this.folderCacheLock.writeLock().unlock();
    }
}

From source file:org.apache.cassandra.dht.tokenallocator.TokenAllocation.java

static TokenAllocator<InetAddress> create(TokenMetadata tokenMetadata, StrategyAdapter strategy) {
    NavigableMap<Token, InetAddress> sortedTokens = new TreeMap<>();
    for (Map.Entry<Token, InetAddress> en : tokenMetadata.getNormalAndBootstrappingTokenToEndpointMap()
            .entrySet()) {/*from   w  ww .ja va 2s .c o  m*/
        if (strategy.inAllocationRing(en.getValue()))
            sortedTokens.put(en.getKey(), en.getValue());
    }
    return new ReplicationAwareTokenAllocator<>(sortedTokens, strategy, tokenMetadata.partitioner);
}

From source file:org.apache.ctakes.ytex.kernel.SvmlinEvaluationParser.java

/**
 * support multi-class classification/*from  www .  j ava2 s .c  o  m*/
 * 
 * @param dataDir
 * @param outputDir
 * @param eval
 * @param fileBaseName
 * @param props
 * @param predict
 * @param listClassInfo
 * @throws IOException
 */
private void parseSvmlinOutput(File dataDir, File outputDir, SVMClassifierEvaluation eval, String fileBaseName,
        Properties props, List<InstanceClassInfo> listClassInfo, BiMap<Integer, String> classIdToNameMap)
        throws IOException {
    Properties codeProps = FileUtil
            .loadProperties(dataDir.getAbsolutePath() + "/" + fileBaseName + "code.properties", false);
    String[] codes = codeProps.getProperty("codes", "").split(",");
    SortedMap<String, double[]> codeToPredictionMap = new TreeMap<String, double[]>();
    if (codes.length == 0) {
        throw new IOException("invalid code.properties: " + fileBaseName);
    }
    // int otherClassId = 0;
    String otherClassName = null;
    if (codes.length == 1) {
        // otherClassId = Integer
        // .parseInt(codeProps.getProperty("classOther"));
        otherClassName = codeProps.getProperty("classOtherName");
    }
    for (String code : codes) {
        // determine class for given code
        // String strClassId = codeProps.getProperty(code+".class");
        // if (strClassId == null) {
        // throw new IOException("invalid code.properties: "
        // + fileBaseName);
        // }
        // int classId = Integer.parseInt(strClassId);
        String className = codeProps.getProperty(code + ".className");
        String codeBase = code.substring(0, code.length() - ".txt".length());
        // read predictions for given class
        codeToPredictionMap.put(className, readPredictions(
                outputDir.getAbsolutePath() + "/" + codeBase + ".outputs", listClassInfo.size()));
    }
    // iterate over predictions for each instance, figure out which class is
    // the winner
    String[] classPredictions = new String[listClassInfo.size()];
    for (int i = 0; i < listClassInfo.size(); i++) {
        if (otherClassName != null) {
            Map.Entry<String, double[]> classToPred = codeToPredictionMap.entrySet().iterator().next();
            classPredictions[i] = classToPred.getValue()[i] > 0 ? classToPred.getKey() : otherClassName;
        } else {
            NavigableMap<Double, String> predToClassMap = new TreeMap<Double, String>();
            for (Map.Entry<String, double[]> classToPred : codeToPredictionMap.entrySet()) {
                predToClassMap.put(classToPred.getValue()[i], classToPred.getKey());
            }
            classPredictions[i] = predToClassMap.lastEntry().getValue();
        }
    }
    boolean storeUnlabeled = YES.equalsIgnoreCase(props.getProperty(ParseOption.STORE_UNLABELED.getOptionKey(),
            ParseOption.STORE_UNLABELED.getDefaultValue()));
    updateSemiSupervisedPredictions(eval, listClassInfo, storeUnlabeled, classPredictions,
            classIdToNameMap.inverse());
}

From source file:org.apache.hadoop.hbase.catalog.MetaReader.java

/**
 * @param catalogTracker/* w ww .ja v a2s  . co m*/
 * @param serverName
 * @return List of user regions installed on this server (does not include
 * catalog regions).
 * @throws IOException
 */
public static NavigableMap<HRegionInfo, Result> getServerUserRegions(CatalogTracker catalogTracker,
        final ServerName serverName) throws IOException {
    final NavigableMap<HRegionInfo, Result> hris = new TreeMap<HRegionInfo, Result>();
    // Fill the above hris map with entries from hbase:meta that have the passed
    // servername.
    CollectingVisitor<Result> v = new CollectingVisitor<Result>() {
        @Override
        void add(Result r) {
            if (r == null || r.isEmpty())
                return;
            ServerName sn = HRegionInfo.getServerName(r);
            if (sn != null && sn.equals(serverName))
                this.results.add(r);
        }
    };
    fullScan(catalogTracker, v);
    List<Result> results = v.getResults();
    if (results != null && !results.isEmpty()) {
        // Convert results to Map keyed by HRI
        for (Result r : results) {
            Pair<HRegionInfo, ServerName> p = HRegionInfo.getHRegionInfoAndServerName(r);
            if (p != null && p.getFirst() != null)
                hris.put(p.getFirst(), r);
        }
    }
    return hris;
}

From source file:org.apache.hadoop.hbase.client.coprocessor.AggregationClient.java

/**
 * It helps locate the region with median for a given column whose weight 
 * is specified in an optional column./*from  w ww  .java  2 s  . co m*/
 * From individual regions, it obtains sum of values and sum of weights.
 * @param table
 * @param ci
 * @param scan
 * @return pair whose first element is a map between start row of the region
 *  and (sum of values, sum of weights) for the region, the second element is
 *  (sum of values, sum of weights) for all the regions chosen
 * @throws Throwable
 */
private <R, S, P extends Message, Q extends Message, T extends Message> Pair<NavigableMap<byte[], List<S>>, List<S>> getMedianArgs(
        final HTable table, final ColumnInterpreter<R, S, P, Q, T> ci, final Scan scan) throws Throwable {
    final AggregateRequest requestArg = validateArgAndGetPB(scan, ci, false);
    final NavigableMap<byte[], List<S>> map = new TreeMap<byte[], List<S>>(Bytes.BYTES_COMPARATOR);
    class StdCallback implements Batch.Callback<List<S>> {
        S sumVal = null, sumWeights = null;

        public synchronized Pair<NavigableMap<byte[], List<S>>, List<S>> getMedianParams() {
            List<S> l = new ArrayList<S>();
            l.add(sumVal);
            l.add(sumWeights);
            Pair<NavigableMap<byte[], List<S>>, List<S>> p = new Pair<NavigableMap<byte[], List<S>>, List<S>>(
                    map, l);
            return p;
        }

        @Override
        public synchronized void update(byte[] region, byte[] row, List<S> result) {
            map.put(row, result);
            sumVal = ci.add(sumVal, result.get(0));
            sumWeights = ci.add(sumWeights, result.get(1));
        }
    }
    StdCallback stdCallback = new StdCallback();
    table.coprocessorService(AggregateService.class, scan.getStartRow(), scan.getStopRow(),
            new Batch.Call<AggregateService, List<S>>() {
                @Override
                public List<S> call(AggregateService instance) throws IOException {
                    ServerRpcController controller = new ServerRpcController();
                    BlockingRpcCallback<AggregateResponse> rpcCallback = new BlockingRpcCallback<AggregateResponse>();
                    instance.getMedian(controller, requestArg, rpcCallback);
                    AggregateResponse response = rpcCallback.get();
                    if (controller.failedOnException()) {
                        throw controller.getFailedOn();
                    }

                    List<S> list = new ArrayList<S>();
                    for (int i = 0; i < response.getFirstPartCount(); i++) {
                        ByteString b = response.getFirstPart(i);
                        T t = ProtobufUtil.getParsedGenericInstance(ci.getClass(), 4, b);
                        S s = ci.getPromotedValueFromProto(t);
                        list.add(s);
                    }
                    return list;
                }

            }, stdCallback);
    return stdCallback.getMedianParams();
}

From source file:org.apache.hadoop.hbase.client.coprocessor.AggregationClient.java

/**
 * It helps locate the region with median for a given column whose weight 
 * is specified in an optional column./*from w  w w.ja  v  a  2 s .c o  m*/
 * From individual regions, it obtains sum of values and sum of weights.
 * @param table
 * @param ci
 * @param scan
 * @return pair whose first element is a map between start row of the region
 *  and (sum of values, sum of weights) for the region, the second element is
 *  (sum of values, sum of weights) for all the regions chosen
 * @throws Throwable
 */
private <R, S, P extends Message, Q extends Message, T extends Message> Pair<NavigableMap<byte[], List<S>>, List<S>> getMedianArgs(
        final HTable table, final ColumnInterpreter<R, S, P, Q, T> ci, final Scan scan) throws Throwable {
    final AggregateRequest requestArg = validateArgAndGetPB(scan, ci, false);
    final NavigableMap<byte[], List<S>> map = new TreeMap<byte[], List<S>>(Bytes.BYTES_COMPARATOR);
    class StdCallback implements Batch.Callback<List<S>> {
        S sumVal = null, sumWeights = null;

        public Pair<NavigableMap<byte[], List<S>>, List<S>> getMedianParams() {
            List<S> l = new ArrayList<S>();
            l.add(sumVal);
            l.add(sumWeights);
            Pair<NavigableMap<byte[], List<S>>, List<S>> p = new Pair<NavigableMap<byte[], List<S>>, List<S>>(
                    map, l);
            return p;
        }

        @Override
        public synchronized void update(byte[] region, byte[] row, List<S> result) {
            map.put(row, result);
            sumVal = ci.add(sumVal, result.get(0));
            sumWeights = ci.add(sumWeights, result.get(1));
        }
    }
    StdCallback stdCallback = new StdCallback();
    table.coprocessorService(AggregateService.class, scan.getStartRow(), scan.getStopRow(),
            new Batch.Call<AggregateService, List<S>>() {
                @Override
                public List<S> call(AggregateService instance) throws IOException {
                    ServerRpcController controller = new ServerRpcController();
                    BlockingRpcCallback<AggregateResponse> rpcCallback = new BlockingRpcCallback<AggregateResponse>();
                    instance.getMedian(controller, requestArg, rpcCallback);
                    AggregateResponse response = rpcCallback.get();
                    if (controller.failedOnException()) {
                        throw controller.getFailedOn();
                    }

                    List<S> list = new ArrayList<S>();
                    for (int i = 0; i < response.getFirstPartCount(); i++) {
                        ByteString b = response.getFirstPart(i);
                        T t = ProtobufUtil.getParsedGenericInstance(ci.getClass(), 4, b);
                        S s = ci.getPromotedValueFromProto(t);
                        list.add(s);
                    }
                    return list;
                }

            }, stdCallback);
    return stdCallback.getMedianParams();
}

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

/**
 * Lists all of the table regions currently in META.
 * @param conf//ww w.  j av  a2s.com
 * @param offlined True if we are to include offlined regions, false and we'll
 * leave out offlined regions from returned list.
 * @return Map of all user-space regions to servers
 * @throws IOException
 */
public static NavigableMap<HRegionInfo, ServerName> allTableRegions(Configuration conf,
        ClusterConnection connection, final TableName tableName, final boolean offlined) throws IOException {
    final NavigableMap<HRegionInfo, ServerName> regions = new TreeMap<HRegionInfo, ServerName>();
    MetaScannerVisitor visitor = new TableMetaScannerVisitor(tableName) {
        @Override
        public boolean processRowInternal(Result rowResult) throws IOException {
            HRegionInfo info = getHRegionInfo(rowResult);
            ServerName serverName = HRegionInfo.getServerName(rowResult);
            regions.put(new UnmodifyableHRegionInfo(info), serverName);
            return true;
        }
    };
    metaScan(conf, connection, visitor, tableName);
    return regions;
}

From source file:org.apache.hadoop.hbase.client.transactional.TransactionalAggregationClient.java

/**
 * It helps locate the region with median for a given column whose weight 
 * is specified in an optional column./* w  w  w .  j  a  v  a2  s.  co  m*/
 * From individual regions, it obtains sum of values and sum of weights.
 * @param table
 * @param ci
 * @param scan
 * @return pair whose first element is a map between start row of the region
 *  and (sum of values, sum of weights) for the region, the second element is
 *  (sum of values, sum of weights) for all the regions chosen
 * @throws Throwable
 */
private <R, S, P extends Message, Q extends Message, T extends Message> Pair<NavigableMap<byte[], List<S>>, List<S>> getMedianArgs(
        final long transactionId, final TransactionalTable table, final ColumnInterpreter<R, S, P, Q, T> ci,
        final Scan scan) throws Throwable {
    byte[] currentBeginKey = scan.getStartRow();
    HRegionInfo currentRegion = table.getRegionLocation(currentBeginKey).getRegionInfo();
    com.google.protobuf.ByteString regionName = ByteString.copyFromUtf8(currentRegion.getRegionNameAsString());
    final TransactionalAggregateRequest requestArg = validateArgAndGetPB(regionName, transactionId, scan, ci,
            false);
    final NavigableMap<byte[], List<S>> map = new TreeMap<byte[], List<S>>(Bytes.BYTES_COMPARATOR);
    class StdCallback implements Batch.Callback<List<S>> {
        S sumVal = null, sumWeights = null;

        public Pair<NavigableMap<byte[], List<S>>, List<S>> getMedianParams() {
            List<S> l = new ArrayList<S>();
            l.add(sumVal);
            l.add(sumWeights);
            Pair<NavigableMap<byte[], List<S>>, List<S>> p = new Pair<NavigableMap<byte[], List<S>>, List<S>>(
                    map, l);
            return p;
        }

        @Override
        public synchronized void update(byte[] region, byte[] row, List<S> result) {
            map.put(row, result);
            sumVal = ci.add(sumVal, result.get(0));
            sumWeights = ci.add(sumWeights, result.get(1));
        }
    }
    StdCallback stdCallback = new StdCallback();
    table.coprocessorService(TrxRegionService.class, scan.getStartRow(), scan.getStopRow(),
            new Batch.Call<TrxRegionService, List<S>>() {
                @Override
                public List<S> call(TrxRegionService instance) throws IOException {
                    ServerRpcController controller = new ServerRpcController();
                    BlockingRpcCallback<TransactionalAggregateResponse> rpcCallback = new BlockingRpcCallback<TransactionalAggregateResponse>();
                    instance.getMedian(controller, requestArg, rpcCallback);
                    TransactionalAggregateResponse response = rpcCallback.get();
                    if (controller.failedOnException()) {
                        throw controller.getFailedOn();
                    }

                    List<S> list = new ArrayList<S>();
                    for (int i = 0; i < response.getFirstPartCount(); i++) {
                        ByteString b = response.getFirstPart(i);
                        T t = ProtobufUtil.getParsedGenericInstance(ci.getClass(), 4, b);
                        S s = ci.getPromotedValueFromProto(t);
                        list.add(s);
                    }
                    return list;
                }

            }, stdCallback);
    return stdCallback.getMedianParams();
}