Example usage for java.util NavigableMap putAll

List of usage examples for java.util NavigableMap putAll

Introduction

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

Prototype

void putAll(Map<? extends K, ? extends V> m);

Source Link

Document

Copies all of the mappings from the specified map to this map (optional operation).

Usage

From source file:com.mirth.connect.server.controllers.DonkeyMessageController.java

private List<MessageSearchResult> searchMessages(MessageFilter filter, String channelId, int offset,
        int limit) {
    long startTime = System.currentTimeMillis();

    FilterOptions filterOptions = new FilterOptions(filter, channelId);
    long maxMessageId = filterOptions.getMaxMessageId();
    long minMessageId = filterOptions.getMinMessageId();

    Long localChannelId = ChannelController.getInstance().getLocalChannelId(channelId);
    Map<String, Object> params = getBasicParameters(filter, localChannelId);

    try {/*  www  . j a v  a 2  s.c  om*/
        NavigableMap<Long, MessageSearchResult> messages = new TreeMap<Long, MessageSearchResult>();
        SqlSession session = SqlConfig.getSqlSessionManager();

        int offsetRemaining = offset;
        /*
         * If the limit is greater than the default batch size, use the limit, but cap it at
         * 50000.
         */
        long batchSize = Math.min(Math.max(limit, 500), 50000);
        long totalSearched = 0;

        while (messages.size() < limit && maxMessageId >= minMessageId) {
            /*
             * Slowly increase the batch size in case all the necessary results are found early
             * on.
             */
            if (totalSearched >= 100000 && batchSize < 50000) {
                batchSize = 50000;
            } else if (totalSearched >= 10000 && batchSize < 10000) {
                batchSize = 10000;
            } else if (totalSearched >= 1000 && batchSize < 1000) {
                batchSize = 1000;
            }

            /*
             * Search in descending order so that messages will be found from the greatest to
             * lowest message id
             */
            long currentMinMessageId = Math.max(maxMessageId - batchSize + 1, minMessageId);
            params.put("maxMessageId", maxMessageId);
            params.put("minMessageId", currentMinMessageId);
            maxMessageId -= batchSize;
            totalSearched += batchSize;

            Map<Long, MessageSearchResult> foundMessages = searchAll(session, params, filter, localChannelId,
                    false, filterOptions);

            if (!foundMessages.isEmpty()) {
                /*
                 * Skip results until there is no offset remaining. This is required when
                 * viewing results beyond the first page
                 */
                if (offsetRemaining >= foundMessages.size()) {
                    offsetRemaining -= foundMessages.size();
                } else if (offsetRemaining == 0) {
                    messages.putAll(foundMessages);
                } else {
                    NavigableMap<Long, MessageSearchResult> orderedMessages = new TreeMap<Long, MessageSearchResult>(
                            foundMessages);

                    while (offsetRemaining-- > 0) {
                        orderedMessages.pollLastEntry();
                    }

                    messages.putAll(orderedMessages);
                }
            }
        }

        // Remove results beyond the limit requested
        while (messages.size() > limit) {
            messages.pollFirstEntry();
        }

        List<MessageSearchResult> results = new ArrayList<MessageSearchResult>(messages.size());

        /*
         * Now that we have the message and metadata ids that should be returned as the result,
         * we need to retrieve the message data for those.
         */
        if (!messages.isEmpty()) {
            Iterator<Long> iterator = messages.descendingKeySet().iterator();

            while (iterator.hasNext()) {
                Map<String, Object> messageParams = new HashMap<String, Object>();
                messageParams.put("localChannelId", localChannelId);

                ListRangeIterator listRangeIterator = new ListRangeIterator(iterator,
                        ListRangeIterator.DEFAULT_LIST_LIMIT, false, null);

                while (listRangeIterator.hasNext()) {
                    ListRangeItem item = listRangeIterator.next();
                    List<Long> list = item.getList();
                    Long startRange = item.getStartRange();
                    Long endRange = item.getEndRange();

                    if (list != null || (startRange != null && endRange != null)) {
                        if (list != null) {
                            messageParams.remove("minMessageId");
                            messageParams.remove("maxMessageId");
                            messageParams.put("includeMessageList", StringUtils.join(list, ","));
                        } else {
                            messageParams.remove("includeMessageList");
                            messageParams.put("minMessageId", endRange);
                            messageParams.put("maxMessageId", startRange);
                        }

                        // Get the current batch of results
                        List<MessageSearchResult> currentResults = session
                                .selectList("Message.selectMessagesById", messageParams);

                        // Add the metadata ids to each result
                        for (MessageSearchResult currentResult : currentResults) {
                            currentResult.setMetaDataIdSet(
                                    messages.get(currentResult.getMessageId()).getMetaDataIdSet());
                        }

                        // Add the current batch to the final list of results
                        results.addAll(currentResults);
                    }
                }
            }
        }

        return results;
    } finally {
        long endTime = System.currentTimeMillis();
        logger.debug("Search executed in " + (endTime - startTime) + "ms");
    }
}

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

public void testPutAllLjava_util_Map() {
    K[] keys = getSortedKeys();/*from  w w  w . j ava2  s .  c  o  m*/
    V[] values = getSortedValues();
    NavigableMap<K, V> map = createNavigableMap();
    for (int i = 0; i < keys.length; i++) {
        map.put(keys[i], values[i]);
    }

    NavigableMap<K, V> newMap = createNavigableMap();
    newMap.putAll(map);
    assertEquals(map.size(), newMap.size());
    for (int i = 0; i < keys.length; i++) {
        V value = values[i];
        assertEquals(value, newMap.get(keys[i]));
    }
}

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

@SuppressWarnings("unchecked")
public void testNavigableKeySet_iterator() {
    NavigableMap<K, V> map = createNavigableMap();
    map.putAll(makeFullMap());
    resetFull();/*from  w ww .j ava2s.c  o m*/
    ArrayList<K> keys = new ArrayList<K>();
    for (Object key : getSampleKeys()) {
        keys.add((K) key);
    }
    Comparator<? super K> cmp = ((TreeMap<K, V>) map).comparator();
    Collections.sort(keys, cmp);
    Iterator<K> it = map.navigableKeySet().iterator();
    for (K key : keys) {
        assertTrue(it.hasNext());
        K rem = it.next();
        it.remove();
        assertEquals(key, rem);
    }
    try {
        it.next();
        fail("should throw NoSuchElementException");
    } catch (NoSuchElementException expected) {
    }
    _assertEmpty(map);
}

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

@SuppressWarnings("unchecked")
public void testDescendingKeySet_iterator() {
    NavigableMap<K, V> map = createNavigableMap();
    map.putAll(makeFullMap());
    resetFull();/*from ww w . jav a 2 s .c o  m*/
    ArrayList<K> keys = new ArrayList<K>();
    for (Object key : getSampleKeys()) {
        keys.add((K) key);
    }

    // JDK < 7 does not handle null keys correctly.
    if (useNullKey() && TestUtils.isJvm() && TestUtils.getJdkVersion() < 7) {
        map.remove(null);
        keys.remove(null);
    }

    Comparator<? super K> cmp = ((TreeMap<K, V>) map).comparator();
    Collections.sort(keys, Collections.reverseOrder(cmp));
    Iterator<K> it = map.descendingKeySet().iterator();
    for (K key : keys) {
        assertTrue(it.hasNext());
        K rem = it.next();
        it.remove();
        assertEquals(key, rem);
    }
    try {
        it.next();
        fail("should throw NoSuchElementException");
    } catch (NoSuchElementException expected) {
    }
    _assertEmpty(map);
}

From source file:org.apache.hadoop.hbase.client.crosssite.CrossSiteHTable.java

public NavigableMap<HRegionInfo, ServerName> getRegionLocations() throws IOException {
    List<ClusterInfo> cis = getClusterInfos(null, null);
    List<Future<NavigableMap<HRegionInfo, ServerName>>> futures = new ArrayList<Future<NavigableMap<HRegionInfo, ServerName>>>();
    for (final ClusterInfo ci : cis) {
        futures.add(pool.submit(new Callable<NavigableMap<HRegionInfo, ServerName>>() {
            @Override// w ww  . j a  va  2  s. c  o m
            public NavigableMap<HRegionInfo, ServerName> call() throws Exception {
                boolean closeTable = false;
                HTableInterface table = tablesCache.get(ci.getName());
                if (table == null) {
                    // Not cached.Let us create one. Do not cache this created one and make sure to close
                    // this when the operation is done
                    table = createHTable(ci.getName(), ci.getAddress());
                    closeTable = true;
                }
                try {
                    if (table instanceof HTable) {
                        return ((HTable) table).getRegionLocations();
                    }
                    throw new UnsupportedOperationException();
                } finally {
                    if (closeTable) {
                        try {
                            table.close();
                        } catch (IOException e) {
                            LOG.warn("Fail to close the HBaseAdmin", e);
                        }
                    }
                }
            }
        }));
    }
    try {
        NavigableMap<HRegionInfo, ServerName> regionLocations = new TreeMap<HRegionInfo, ServerName>();
        for (Future<NavigableMap<HRegionInfo, ServerName>> result : futures) {
            if (result != null) {
                NavigableMap<HRegionInfo, ServerName> regions = result.get();
                if (regions != null) {
                    regionLocations.putAll(regions);
                }
            }
        }
        return regionLocations;
    } catch (Exception e) {
        // do nothing. Even the exception occurs, we regard the cross site
        // HTable has been deleted
        LOG.error("Fail to get region locations of the cross site table " + tableName, e);
        throw new IOException(e);
    }
}

From source file:org.apache.hadoop.hbase.master.RegionManager.java

/**
 * Composes a map of .META. region locations for both online .META. regions and regions that
 * we know are assigned to regionservers, but have not been scanned yet. This is used on master
 * startup to write pending region location changes from the ZK unassigned directory to .META.
 */// w  ww .  jav  a  2s.  co m
NavigableMap<byte[], MetaRegion> getAllMetaRegionLocations() {
    NavigableMap<byte[], MetaRegion> m = new TreeMap<byte[], MetaRegion>(Bytes.BYTES_COMPARATOR);
    m.putAll(metaRegionLocationsBeforeScan);
    m.putAll(onlineMetaRegions);
    return m;
}

From source file:org.webcurator.ui.target.controller.QaIndicatorReportController.java

@Override
protected ModelAndView showForm(HttpServletRequest request, HttpServletResponse response, BindException errors)
        throws Exception {

    ModelAndView mav = new ModelAndView();

    // fetch the indicator oid from the request (hyperlinked from QA Summary Page)
    String iOid = request.getParameter("indicatorOid");

    if (iOid != null) {

        // prepare the indicator oid
        Long indicatorOid = Long.parseLong(iOid);

        // get the indicator
        Indicator indicator = indicatorDAO.getIndicatorByOid(indicatorOid);

        // add it to the ModelAndView so that we can access it within the jsp
        mav.addObject("indicator", indicator);

        // add the target instance
        TargetInstance instance = targetInstanceManager.getTargetInstance(indicator.getTargetInstanceOid());
        mav.addObject(TargetInstanceCommand.MDL_INSTANCE, instance);

        // ensure that the user belongs to the agency that created the indicator
        if (agencyUserManager.getAgenciesForLoggedInUser().contains(indicator.getAgency())) {
            // summarise the indicator values in the reportLines
            HashMap<String, Integer> summary = new HashMap<String, Integer>();
            NavigableMap<String, Integer> sortedSummary = null;
            int total = 0;
            // if the indicator is not in the exclusion list ...
            if (!excludedIndicators.containsKey(indicator.getName())) {
                // fetch the report lines for this indicator
                List<IndicatorReportLine> reportLines = indicator.getIndicatorReportLines();
                // add them ti the model
                mav.addObject("reportLines", reportLines);

                Comparator comparitor = null;

                Iterator<IndicatorReportLine> lines = reportLines.iterator();

                if (sortOrder.equals("countdesc")) {
                    comparitor = new DescendingValueComparator(summary);
                    sortedSummary = new TreeMap<String, Integer>(comparitor);
                } else if (sortOrder.equals("countasc")) {
                    comparitor = new AscendingValueComparator(summary);
                    sortedSummary = new TreeMap<String, Integer>(comparitor);
                } else if (sortOrder.equals("indicatorvaluedesc")) {
                    sortedSummary = new TreeMap<String, Integer>().descendingMap();
                } else if (sortOrder.equals("indicatorvalueasc")) {
                    sortedSummary = new TreeMap<String, Integer>();
                }/*ww w .j ava2s .c  o m*/

                while (lines.hasNext()) {
                    IndicatorReportLine line = lines.next();
                    if (summary.containsKey(line.getLine())) {
                        // increment the current entry value
                        summary.put(line.getLine(), summary.get(line.getLine()) + 1);
                    } else {
                        // initialise the value for the entry
                        summary.put(line.getLine(), 1);
                    }
                    total++;
                }
                sortedSummary.putAll(summary);
                mav.addObject("sortedSummary", sortedSummary);
                mav.addObject("total", total);
                mav.addObject("sortorder", sortOrder);

                mav.setViewName("QaIndicatorReport");
            } else {
                // otherwise redirect to the configured view
                StringBuilder queryString = new StringBuilder("redirect:");
                queryString.append(excludedIndicators.get(indicator.getName()));
                queryString.append("?");
                queryString.append("indicatorOid=");
                queryString.append(indicatorOid);

                return new ModelAndView(queryString.toString());
            }

        }
    }
    return mav;

}