Example usage for java.util SortedMap lastKey

List of usage examples for java.util SortedMap lastKey

Introduction

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

Prototype

K lastKey();

Source Link

Document

Returns the last (highest) key currently in this map.

Usage

From source file:org.opencms.workplace.commons.CmsPreferences.java

/**
 * Builds the html for the preferred editors select boxes of the editor settings.<p>
 * /*from  ww w . j a va  2  s . c  o m*/
 * @param htmlAttributes optional html attributes for the &lgt;select&gt; tag
 * @return the html for the preferred editors select boxes
 */
public String buildSelectPreferredEditors(String htmlAttributes) {

    StringBuffer result = new StringBuffer(1024);
    HttpServletRequest request = getJsp().getRequest();
    if (htmlAttributes != null) {
        htmlAttributes += " name=\"" + PARAM_PREFERREDEDITOR_PREFIX;
    }
    Map resourceEditors = OpenCms.getWorkplaceManager().getWorkplaceEditorManager().getConfigurableEditors();
    if (resourceEditors != null) {
        // first: iterate over the resource types and consider order from configuration
        Iterator i = resourceEditors.keySet().iterator();

        SortedMap rankResources = new TreeMap();
        while (i.hasNext()) {
            String currentResourceType = (String) i.next();
            CmsExplorerTypeSettings settings = OpenCms.getWorkplaceManager()
                    .getExplorerTypeSetting(currentResourceType);
            rankResources.put(new Float(settings.getNewResourceOrder()), currentResourceType);
        }

        while (rankResources.size() > 0) {
            // get editor configuration with lowest order
            Float keyVal = (Float) rankResources.firstKey();
            String currentResourceType = (String) rankResources.get(keyVal);

            SortedMap availableEditors = (TreeMap) resourceEditors.get(currentResourceType);
            if ((availableEditors != null) && (availableEditors.size() > 0)) {
                String preSelection = computeEditorPreselection(request, currentResourceType);
                List options = new ArrayList(availableEditors.size() + 1);
                List values = new ArrayList(availableEditors.size() + 1);
                options.add(key(Messages.GUI_PREF_EDITOR_BEST_0));
                values.add(INPUT_DEFAULT);
                // second: iteration over the available editors for the resource type
                int selectedIndex = 0;
                int counter = 1;
                while (availableEditors.size() > 0) {
                    Float key = (Float) availableEditors.lastKey();
                    CmsWorkplaceEditorConfiguration conf = (CmsWorkplaceEditorConfiguration) availableEditors
                            .get(key);
                    options.add(keyDefault(conf.getEditorLabel(), conf.getEditorLabel()));
                    values.add(conf.getEditorUri());
                    if (conf.getEditorUri().equals(preSelection)) {
                        selectedIndex = counter;
                    }
                    counter++;
                    availableEditors.remove(key);
                }

                // create the table row for the current resource type
                result.append("<tr>\n\t<td style=\"white-space: nowrap;\">");
                String localizedName = keyDefault("label.editor.preferred." + currentResourceType, "");
                if (CmsStringUtil.isEmpty(localizedName)) {
                    localizedName = CmsWorkplaceMessages.getResourceTypeName(this, currentResourceType);
                }
                result.append(localizedName);
                result.append("</td>\n\t<td>");
                result.append(buildSelect(htmlAttributes + currentResourceType + "\"", options, values,
                        selectedIndex));
                result.append("</td>\n</tr>\n");
            }
            rankResources.remove(keyVal);
        }
    }
    return result.toString();
}

From source file:org.opencms.setup.CmsSetupBean.java

/** 
 * Returns a sorted list with they keys (e.g. "mysql", "generic" or "oracle") of all available
 * database server setups found in "/setup/database/" sorted by their ranking property.<p>
 *
 * @return a sorted list with they keys (e.g. "mysql", "generic" or "oracle") of all available database server setups
 *//*from   w w w .j  a v  a  2  s.  c  o  m*/
public List<String> getSortedDatabases() {

    if (m_sortedDatabaseKeys == null) {
        List<String> databases = m_databaseKeys;
        List<String> sortedDatabases = new ArrayList<String>(databases.size());
        SortedMap<Integer, String> mappedDatabases = new TreeMap<Integer, String>();
        for (int i = 0; i < databases.size(); i++) {
            String key = databases.get(i);
            Integer ranking = new Integer(0);
            try {
                ranking = Integer.valueOf(getDbProperty(key + ".ranking"));
            } catch (Exception e) {
                // ignore
            }
            mappedDatabases.put(ranking, key);
        }

        while (mappedDatabases.size() > 0) {
            // get database with highest ranking 
            Integer key = mappedDatabases.lastKey();
            String database = mappedDatabases.get(key);
            sortedDatabases.add(database);
            mappedDatabases.remove(key);
        }
        m_sortedDatabaseKeys = sortedDatabases;
    }
    return m_sortedDatabaseKeys;
}

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

/**
 * Test method for 'java.util.SortedMap.lastKey()'.
 *
 * @see java.util.SortedMap#lastKey()/*www. j  a  v  a  2 s.  c  o m*/
 */
public void testLastKey_throwsNoSuchElementException() {
    SortedMap<K, V> sortedMap = createNavigableMap();
    // test with no entries
    try {
        sortedMap.lastKey();
        fail("expected exception");
    } catch (NoSuchElementException e) {
        // expected outcome
    }
}

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

public void testLastKey_after_subMap() {
    K[] keys = getSortedKeys();/*from  w  w w .jav  a2  s  .  c  o  m*/
    V[] values = getSortedValues();
    NavigableMap<K, V> map = createNavigableMap();
    map.put(keys[0], values[0]);
    map.put(keys[1], values[1]);
    map.put(keys[2], values[2]);

    SortedMap<K, V> subMap = map;
    K firstKey = subMap.firstKey();
    for (int i = 0; i < map.size(); i++) {
        K lastKey = subMap.lastKey();
        subMap = subMap.subMap(firstKey, lastKey);
    }
}

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 .j  a  v a 2s  . com
 */
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.SortedMap.firstKey()'.
 *
 * @see java.util.SortedMap#firstKey()//from  www .j a va  2 s. co m
 */
public void testFirstKey() {
    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.firstKey());
    // is it consistent with other methods
    assertEquals(map.keySet().toArray()[0], map.firstKey());
    assertEquals(keys[0], map.lastKey());
    assertEquals(map.lastKey(), map.firstKey());

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

    map.put(keys[2], values[2]);
    map.put(keys[3], values[3]);
    assertEquals(keys[0], map.firstKey());
}

From source file:rrlFramework.RRLExperiment.java

/**
 * Compiles the performance files together into a single file, detailing the
 * average, min and max performances./*from  ww  w  .jav  a2  s .  c o m*/
 * 
 * @param runEnd
 *            The last run.
 * @param byEpisode
 *            If the performances are being combined by episode (in
 *            intervals) or by regular CE interval.
 */
private long combineTempFiles(File performanceFile, int runEnd, long experimentStart) throws Exception {
    List<List<Float[]>> performances = new ArrayList<List<Float[]>>();
    float min = Float.MAX_VALUE;
    int minRun = -1;
    float max = -Float.MAX_VALUE;
    int maxRun = -1;
    double[] episodeLengths = new double[runEnd];
    double[] numSlots = new double[runEnd];
    long averageRunTime = 0;

    File combinedPerfFile = performanceFile;
    if (Config.getInstance().getGeneratorFile() != null) {
        combinedPerfFile = new File(performanceFile.getAbsolutePath() + "greedy");
        ProgramArgument.PERFORMANCE_EPISODE_GAP
                .setDoubleValue(ProgramArgument.PERFORMANCE_TESTING_SIZE.intValue()
                        * ProgramArgument.POLICY_REPEATS.intValue());
    }
    if (!combinedPerfFile.exists())
        combinedPerfFile.createNewFile();
    // For every performance file
    for (int i = 0; i < runEnd; i++) {
        File tempPerf = new File(Config.TEMP_FOLDER + "/" + performanceFile + i);
        if (!Performance.readRawPerformanceFile(tempPerf, true)) {
            System.err.println("Error reading performance file.");
            return 0;
        }

        List<Float[]> thisRunPerformances = new ArrayList<Float[]>();
        performances.add(thisRunPerformances);

        // Run through the performances and place them in the matrix
        SortedMap<Integer, Float[]> runPerformances = Performance.getPerformanceArray();
        averageRunTime += Performance.getRunTime();
        Iterator<Integer> iter = runPerformances.keySet().iterator();
        Integer current = iter.next();
        Integer previous = null;
        int currentKeyframeEpisode = ProgramArgument.PERFORMANCE_EPISODE_GAP.intValue();
        // Run through the performances, using linear interpolation to
        // get estimates of the performance at a given interval.
        do {
            // If the current segment is further along than the current
            // value, advance to the next value.
            while (currentKeyframeEpisode > current) {
                previous = current;
                if (iter.hasNext())
                    current = iter.next();
                else
                    break;
            }

            // If the keyframe isn't up to the first episode, just use
            // the current value
            Float[] episodePerformance = runPerformances.get(current);
            if (previous == null) {
                // Add to the previous value.
                thisRunPerformances.add(episodePerformance);
            } else {
                // Interpolate from the previous value to the current
                // one.
                Float[] interpolatedPerformance = new Float[episodePerformance.length];
                if (previous == current) {
                    interpolatedPerformance = episodePerformance;
                } else {
                    Float[] prevPerformance = runPerformances.get(previous);

                    for (int j = 0; j < episodePerformance.length; j++) {
                        Float currPerf = episodePerformance[j];
                        Float prevPerf = prevPerformance[j];
                        // Adjust for null elites
                        if (j == PerformanceDetails.ELITEMAX.ordinal()
                                || j == PerformanceDetails.ELITEMEAN.ordinal()) {
                            if (currPerf == null)
                                currPerf = episodePerformance[PerformanceDetails.MEAN.ordinal()];
                            if (prevPerf == null)
                                prevPerf = prevPerformance[PerformanceDetails.MEAN.ordinal()];
                        }

                        if (currPerf == null || prevPerf == null)
                            interpolatedPerformance[j] = null;
                        else
                            interpolatedPerformance[j] = (currPerf - prevPerf)
                                    * (1f * (currentKeyframeEpisode - previous) / (current - previous))
                                    + prevPerf;
                    }
                }

                // Add to the performances
                thisRunPerformances.add(interpolatedPerformance);
            }

            // To the next increment
            currentKeyframeEpisode += ProgramArgument.PERFORMANCE_EPISODE_GAP.intValue();
        } while (currentKeyframeEpisode <= runPerformances.lastKey());
        Float[] lastPerf = runPerformances.get(runPerformances.lastKey());
        thisRunPerformances.add(lastPerf);
        System.out.println(runPerformances.get(runPerformances.lastKey())[PerformanceDetails.MEAN.ordinal()]);

        // Find min or max runs
        float runVal = runPerformances.get(runPerformances.lastKey())[PerformanceDetails.MEAN.ordinal()];
        if (runVal < min) {
            min = runVal;
            minRun = i;
        }
        if (runVal > max) {
            max = runVal;
            maxRun = i;
        }
        episodeLengths[i] = runPerformances.lastKey();
    }

    // Calculate the average and print out the stats
    FileWriter writer = new FileWriter(combinedPerfFile);
    BufferedWriter buf = new BufferedWriter(writer);
    Config.writeFileHeader(buf, Config.getInstance().getGoal());

    buf.write(
            "Episode\tAverage\tSD\tMin\tMax\tElite-Average\tElite-SD\tNumSlots\tSlots-SD\tNumRules\tRules-SD\n");
    boolean moreEpisodes = true;
    int index = 0;
    Mean mean = new Mean();
    StandardDeviation sd = new StandardDeviation();
    while (moreEpisodes) {
        moreEpisodes = false;
        // Compile the array of performances for the given index
        double[][] performanceArray = new double[PerformanceDetails.values().length][performances.size()];
        double maxVal = 0;
        double minVal = 0;
        for (int run = 0; run < performances.size(); run++) {
            List<Float[]> runPerformanceList = performances.get(run);
            int thisIndex = Math.min(index, runPerformanceList.size() - 1);
            if (index < runPerformanceList.size() - 1)
                moreEpisodes = true;
            Float[] performanceDetails = runPerformanceList.get(thisIndex);
            for (int j = 0; j < performanceDetails.length; j++) {
                if (performanceDetails[j] != null)
                    performanceArray[j][run] = performanceDetails[j];
            }

            // Max and min
            if (run == minRun)
                minVal = performanceArray[PerformanceDetails.MEAN.ordinal()][run];
            if (run == maxRun)
                maxVal = performanceArray[PerformanceDetails.MEAN.ordinal()][run];
        }

        // Find the statistics
        int episodeNum = (index + 1) * ProgramArgument.PERFORMANCE_EPISODE_GAP.intValue();
        buf.write(episodeNum + "\t" + mean.evaluate(performanceArray[PerformanceDetails.MEAN.ordinal()]) + "\t"
                + sd.evaluate(performanceArray[PerformanceDetails.MEAN.ordinal()]) + "\t" + minVal + "\t"
                + maxVal + "\t" + mean.evaluate(performanceArray[PerformanceDetails.ELITEMEAN.ordinal()]) + "\t"
                + sd.evaluate(performanceArray[PerformanceDetails.ELITEMEAN.ordinal()]) + "\t"
                + mean.evaluate(performanceArray[PerformanceDetails.NUMSLOTS.ordinal()]) + "\t"
                + sd.evaluate(performanceArray[PerformanceDetails.NUMSLOTS.ordinal()]) + "\t"
                + mean.evaluate(performanceArray[PerformanceDetails.NUMRULES.ordinal()]) + "\t"
                + sd.evaluate(performanceArray[PerformanceDetails.NUMRULES.ordinal()]) + "\n");
        index++;
    }

    averageRunTime /= runEnd;
    buf.write("Average Run Time: " + toTimeFormat(averageRunTime) + "\n");

    // Write the average episode length
    buf.write("\nAverage episode length: " + mean.evaluate(episodeLengths) + " +- "
            + sd.evaluate(episodeLengths) + "\n");
    buf.write("\nAverage num slots: " + mean.evaluate(numSlots) + " +- " + sd.evaluate(numSlots) + "\n");

    buf.close();
    writer.close();
    return averageRunTime;
}

From source file:org.apache.accumulo.server.tabletserver.Tablet.java

private SplitRowSpec findSplitRow(Collection<FileRef> files) {

    // never split the root tablet
    // check if we already decided that we can never split
    // check to see if we're big enough to split

    long splitThreshold = acuTableConf.getMemoryInBytes(Property.TABLE_SPLIT_THRESHOLD);
    if (extent.isRootTablet() || estimateTabletSize() <= splitThreshold) {
        return null;
    }/*from  ww w .  j a  va2 s.  co  m*/

    // have seen a big row before, do not bother checking unless a minor compaction or map file import has occurred.
    if (sawBigRow) {
        if (timeOfLastMinCWhenBigFreakinRowWasSeen != lastMinorCompactionFinishTime
                || timeOfLastImportWhenBigFreakinRowWasSeen != lastMapFileImportTime) {
            // a minor compaction or map file import has occurred... check again
            sawBigRow = false;
        } else {
            // nothing changed, do not split
            return null;
        }
    }

    SortedMap<Double, Key> keys = null;

    try {
        // we should make .25 below configurable
        keys = FileUtil.findMidPoint(fs, tabletServer.getSystemConfiguration(), extent.getPrevEndRow(),
                extent.getEndRow(), files, .25);
    } catch (IOException e) {
        log.error("Failed to find midpoint " + e.getMessage());
        return null;
    }

    // check to see if one row takes up most of the tablet, in which case we can not split
    try {

        Text lastRow;
        if (extent.getEndRow() == null) {
            Key lastKey = (Key) FileUtil.findLastKey(fs, tabletServer.getSystemConfiguration(), files);
            lastRow = lastKey.getRow();
        } else {
            lastRow = extent.getEndRow();
        }

        // check to see that the midPoint is not equal to the end key
        if (keys.get(.5).compareRow(lastRow) == 0) {
            if (keys.firstKey() < .5) {
                Key candidate = keys.get(keys.firstKey());
                if (candidate.compareRow(lastRow) != 0) {
                    // we should use this ratio in split size estimations
                    if (log.isTraceEnabled())
                        log.trace(String.format(
                                "Splitting at %6.2f instead of .5, row at .5 is same as end row%n",
                                keys.firstKey()));
                    return new SplitRowSpec(keys.firstKey(), candidate.getRow());
                }

            }

            log.warn("Cannot split tablet " + extent + " it contains a big row : " + lastRow);

            sawBigRow = true;
            timeOfLastMinCWhenBigFreakinRowWasSeen = lastMinorCompactionFinishTime;
            timeOfLastImportWhenBigFreakinRowWasSeen = lastMapFileImportTime;

            return null;
        }
        Key mid = keys.get(.5);
        Text text = (mid == null) ? null : mid.getRow();
        SortedMap<Double, Key> firstHalf = keys.headMap(.5);
        if (firstHalf.size() > 0) {
            Text beforeMid = firstHalf.get(firstHalf.lastKey()).getRow();
            Text shorter = new Text();
            int trunc = longestCommonLength(text, beforeMid);
            shorter.set(text.getBytes(), 0, Math.min(text.getLength(), trunc + 1));
            text = shorter;
        }
        return new SplitRowSpec(.5, text);
    } catch (IOException e) {
        // don't split now, but check again later
        log.error("Failed to find lastkey " + e.getMessage());
        return null;
    }
}

From source file:org.apache.accumulo.tserver.Tablet.java

private SplitRowSpec findSplitRow(Collection<FileRef> files) {

    // never split the root tablet
    // check if we already decided that we can never split
    // check to see if we're big enough to split

    long splitThreshold = acuTableConf.getMemoryInBytes(Property.TABLE_SPLIT_THRESHOLD);
    if (extent.isRootTablet() || estimateTabletSize() <= splitThreshold) {
        return null;
    }/* ww  w . j a  v a  2 s .  co m*/

    // have seen a big row before, do not bother checking unless a minor compaction or map file import has occurred.
    if (sawBigRow) {
        if (timeOfLastMinCWhenBigFreakinRowWasSeen != lastMinorCompactionFinishTime
                || timeOfLastImportWhenBigFreakinRowWasSeen != lastMapFileImportTime) {
            // a minor compaction or map file import has occurred... check again
            sawBigRow = false;
        } else {
            // nothing changed, do not split
            return null;
        }
    }

    SortedMap<Double, Key> keys = null;

    try {
        // we should make .25 below configurable
        keys = FileUtil.findMidPoint(fs, tabletServer.getSystemConfiguration(), extent.getPrevEndRow(),
                extent.getEndRow(), FileUtil.toPathStrings(files), .25);
    } catch (IOException e) {
        log.error("Failed to find midpoint " + e.getMessage());
        return null;
    }

    // check to see if one row takes up most of the tablet, in which case we can not split
    try {

        Text lastRow;
        if (extent.getEndRow() == null) {
            Key lastKey = (Key) FileUtil.findLastKey(fs, tabletServer.getSystemConfiguration(), files);
            lastRow = lastKey.getRow();
        } else {
            lastRow = extent.getEndRow();
        }

        // check to see that the midPoint is not equal to the end key
        if (keys.get(.5).compareRow(lastRow) == 0) {
            if (keys.firstKey() < .5) {
                Key candidate = keys.get(keys.firstKey());
                if (candidate.compareRow(lastRow) != 0) {
                    // we should use this ratio in split size estimations
                    if (log.isTraceEnabled())
                        log.trace(String.format(
                                "Splitting at %6.2f instead of .5, row at .5 is same as end row%n",
                                keys.firstKey()));
                    return new SplitRowSpec(keys.firstKey(), candidate.getRow());
                }

            }

            log.warn("Cannot split tablet " + extent + " it contains a big row : " + lastRow);

            sawBigRow = true;
            timeOfLastMinCWhenBigFreakinRowWasSeen = lastMinorCompactionFinishTime;
            timeOfLastImportWhenBigFreakinRowWasSeen = lastMapFileImportTime;

            return null;
        }
        Key mid = keys.get(.5);
        Text text = (mid == null) ? null : mid.getRow();
        SortedMap<Double, Key> firstHalf = keys.headMap(.5);
        if (firstHalf.size() > 0) {
            Text beforeMid = firstHalf.get(firstHalf.lastKey()).getRow();
            Text shorter = new Text();
            int trunc = longestCommonLength(text, beforeMid);
            shorter.set(text.getBytes(), 0, Math.min(text.getLength(), trunc + 1));
            text = shorter;
        }
        return new SplitRowSpec(.5, text);
    } catch (IOException e) {
        // don't split now, but check again later
        log.error("Failed to find lastkey " + e.getMessage());
        return null;
    }
}