Example usage for java.util SortedMap firstKey

List of usage examples for java.util SortedMap firstKey

Introduction

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

Prototype

K firstKey();

Source Link

Document

Returns the first (lowest) key currently in this map.

Usage

From source file:org.orekit.time.UTCTAIBulletinAFilesLoader.java

/** {@inheritDoc} */
@Override//from ww  w. jav a2  s.c o m
public List<OffsetModel> loadOffsets() throws OrekitException {

    final Parser parser = new Parser();
    DataProvidersManager.getInstance().feed(supportedNames, parser);
    final SortedMap<Integer, Integer> taiUtc = parser.getTaiUtc();
    final SortedMap<Integer, Double> ut1Utc = parser.getUt1Utc();

    // identify UT1-UTC discontinuities
    final List<Integer> leapDays = new ArrayList<Integer>();
    Map.Entry<Integer, Double> previous = null;
    for (final Map.Entry<Integer, Double> entry : ut1Utc.entrySet()) {
        if (previous != null) {
            final double delta = entry.getValue() - previous.getValue();
            if (FastMath.abs(delta) > 0.5) {
                // discontinuity found between previous and current entry, a leap second has occurred
                leapDays.add(entry.getKey());
            }
        }
        previous = entry;
    }

    final List<OffsetModel> offsets = new ArrayList<OffsetModel>();

    if (!taiUtc.isEmpty()) {

        // find the start offset, before the first UT1-UTC entry
        final Map.Entry<Integer, Integer> firstTaiMUtc = taiUtc.entrySet().iterator().next();
        int offset = firstTaiMUtc.getValue();
        final int refMJD = firstTaiMUtc.getKey();
        for (final int leapMJD : leapDays) {
            if (leapMJD > refMJD) {
                break;
            }
            --offset;
        }

        // set all known time steps
        for (final int leapMJD : leapDays) {
            offsets.add(new OffsetModel(new DateComponents(DateComponents.MODIFIED_JULIAN_EPOCH, leapMJD),
                    ++offset));
        }

        // check for missing time steps
        for (final Map.Entry<Integer, Integer> refTaiMUtc : taiUtc.entrySet()) {
            final DateComponents refDC = new DateComponents(DateComponents.MODIFIED_JULIAN_EPOCH,
                    refTaiMUtc.getKey() + 1);
            OffsetModel before = null;
            for (final OffsetModel o : offsets) {
                if (o.getStart().compareTo(refDC) < 0) {
                    before = o;
                }
            }
            if (before != null) {
                if (refTaiMUtc.getValue() != (int) FastMath.rint(before.getOffset())) {
                    throw new OrekitException(OrekitMessages.MISSING_EARTH_ORIENTATION_PARAMETERS_BETWEEN_DATES,
                            before.getStart(), refDC);
                }
            }
        }

        // make sure we stop the linear drift that was used before 1972
        if (offsets.isEmpty()) {
            offsets.add(0, new OffsetModel(new DateComponents(1972, 1, 1), taiUtc.get(taiUtc.firstKey())));
        } else {
            if (offsets.get(0).getStart().getYear() > 1972) {
                offsets.add(0, new OffsetModel(new DateComponents(1972, 1, 1),
                        ((int) FastMath.rint(offsets.get(0).getOffset())) - 1));
            }
        }

    }

    return offsets;

}

From source file:org.jahia.admin.sites.ManageSites.java

private Locale determineDefaultLocale(ProcessingContext jParams, Map<Object, Object> infos) {
    Locale defaultLocale = jParams.getLocale();
    SortedMap<Integer, String> activeLanguageCodesByRank = new TreeMap<Integer, String>();
    for (Map.Entry<Object, Object> info : infos.entrySet()) {
        if (info.getKey() instanceof String) {
            Matcher m = LANGUAGE_RANK_PATTERN.matcher((String) info.getKey());
            if (m.find()) {
                String languageCode = m.group(1);
                boolean activated = Boolean
                        .parseBoolean((String) infos.get("language." + languageCode + ".activated"));

                if (activated) {
                    if ("1".equals(info.getValue())) {
                        return LanguageCodeConverters.languageCodeToLocale(languageCode);
                    } else {
                        activeLanguageCodesByRank.put(new Integer((String) info.getValue()), languageCode);
                    }/*from   w  w w. ja  v  a 2 s  .co m*/
                }
            }
        }
    }
    if (!activeLanguageCodesByRank.isEmpty()) {
        defaultLocale = LanguageCodeConverters
                .languageCodeToLocale(activeLanguageCodesByRank.get(activeLanguageCodesByRank.firstKey()));
    }
    return defaultLocale;
}

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

public void testLastKey_after_subMap() {
    K[] keys = getSortedKeys();//from w ww.j a v  a  2 s . c om
    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.firstKey()'.
 *
 * @see java.util.SortedMap#firstKey()/*from w  ww .ja  va 2 s . c  om*/
 */
public void testFirstKey_throwsNoSuchElementException() {
    SortedMap<K, V> sortedMap = createNavigableMap();
    // test with no entries
    try {
        sortedMap.firstKey();
        fail("expected exception");
    } catch (NoSuchElementException e) {
        // expected outcome
    }
}

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

/**
 * Test method for 'java.util.SortedMap.firstKey()'.
 *
 * @see java.util.SortedMap#firstKey()//  w  w  w . ja v  a 2s .c  o  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:com.google.gwt.emultest.java.util.TreeMapTest.java

/**
 * Test method for 'java.util.SortedMap.lastKey()'.
 *
 * @see java.util.SortedMap#lastKey()/*  w  ww . j  a  va  2s .co 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

public void testHeadMapLjava_lang_Object() {
    K[] keys = getSortedKeys();// w  w w  .  ja  v a  2  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]);
    }

    Map<K, V> head = map.headMap(keys[3]);
    assertEquals(3, head.size());
    assertTrue(head.containsKey(keys[0]));
    assertTrue(head.containsValue(values[1]));
    assertTrue(head.containsKey(keys[2]));

    if (useNullKey() && useNullValue()) {
        map.put(null, null);

        SortedMap<K, V> submap = map.headMap(null);
        assertEquals(0, submap.size());

        Set<K> keySet = submap.keySet();
        assertEquals(0, keySet.size());

        Set<Map.Entry<K, V>> entrySet = submap.entrySet();
        assertEquals(0, entrySet.size());

        Collection<V> valueCollection = submap.values();
        assertEquals(0, valueCollection.size());

        map.remove(null);
    }

    SortedMap<K, V> submap = map.headMap(getLessThanMinimumKey());
    assertEquals(submap.size(), 0);
    assertTrue(submap.isEmpty());
    try {
        submap.firstKey();
        fail("NoSuchElementException should be thrown");
    } catch (NoSuchElementException expected) {
    }

    try {
        submap.lastKey();
        fail("NoSuchElementException should be thrown");
    } catch (NoSuchElementException expected) {
    }

    try {
        submap.headMap(null);
        assertTrue("expected exception", useNullKey());
    } catch (NullPointerException e) {
        assertFalse("unexpected NPE", useNullKey());
    }
}

From source file:org.apache.accumulo.tserver.tablet.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 = tableConfiguration.getMemoryInBytes(Property.TABLE_SPLIT_THRESHOLD);
    long maxEndRow = tableConfiguration.getMemoryInBytes(Property.TABLE_MAX_END_ROW_SIZE);

    if (extent.isRootTablet() || estimateTabletSize() <= splitThreshold) {
        return null;
    }/*  w  ww  .ja v a 2 s .c o  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(getTabletServer().getFileSystem(), getTabletServer().getConfiguration(),
                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(getTabletServer().getFileSystem(),
                    getTabletServer().getConfiguration(), files);
            lastRow = lastKey.getRow();
        } else {
            lastRow = extent.getEndRow();
        }

        // We expect to get a midPoint for this set of files. If we don't get one, we have a problem.
        final Key mid = keys.get(.5);
        if (null == mid) {
            throw new IllegalStateException("Could not determine midpoint for files");
        }

        // check to see that the midPoint is not equal to the end key
        if (mid.compareRow(lastRow) == 0) {
            if (keys.firstKey() < .5) {
                Key candidate = keys.get(keys.firstKey());
                if (candidate.getLength() > maxEndRow) {
                    log.warn("Cannot split tablet " + extent + ", selected split point too long.  Length :  "
                            + candidate.getLength());

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

                    return null;
                }
                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;
        }

        Text text = 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;
        }

        if (text.getLength() > maxEndRow) {
            log.warn("Cannot split tablet " + extent + ", selected split point too long.  Length :  "
                    + text.getLength());

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

            return null;
        }

        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: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./* www.  ja  va 2 s  .  co  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
        }
    }
}