Example usage for java.util SortedMap get

List of usage examples for java.util SortedMap get

Introduction

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

Prototype

V get(Object key);

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:hudson.plugins.jobConfigHistory.FileHistoryDaoTest.java

private void testGetRevisions(SortedMap<String, HistoryDescr> result) {
    assertEquals(5, result.size());// w ww  .java2 s . co  m
    assertEquals("2012-11-21_11-29-12", result.firstKey());
    assertEquals("2012-11-21_11-42-05", result.lastKey());
    final HistoryDescr firstValue = result.get(result.firstKey());
    final HistoryDescr lastValue = result.get(result.lastKey());
    assertEquals("Created", firstValue.getOperation());
    assertEquals("anonymous", firstValue.getUserID());
    assertEquals("Changed", lastValue.getOperation());
}

From source file:com.restfb.util.InsightUtilsTest.java

@Test
public void executeInsightQueriesByMetricByDate2() throws IOException, ParseException {
    // note that the query that is passed to the FacebookClient WebRequestor is
    // ignored,/*from www .j a va  2s  .c  om*/
    // so arguments of executeInsightQueriesByDate:
    // (String pageObjectId, Set<String> metrics, Period period)
    // are effectively ignored. In this test we are validating the
    // WebRequestor's json
    // is properly processed
    Date d20030629_0000pst = sdfPST.parse("20030629_0000");
    Date d20030630_0000pst = sdfPST.parse("20030630_0000");
    Date d20030701_0000pst = sdfPST.parse("20030701_0000");
    Date d20030702_0000pst = sdfPST.parse("20030702_0000");
    // intentionally using (chaotic) HashSet to ensure implementation is
    // tolerant of that collection
    Set<Date> periodEndDates = new HashSet<Date>();
    periodEndDates.add(d20030629_0000pst);
    periodEndDates.add(d20030630_0000pst);
    periodEndDates.add(d20030701_0000pst);
    periodEndDates.add(d20030702_0000pst);

    SortedMap<String, SortedMap<Date, Object>> results = executeInsightQueriesByMetricByDate(
            createFixedResponseFacebookClient("multiResponse_2metrics_4dates.json"), TEST_PAGE_OBJECT,
            toStringSet("page_active_users", "page_tab_views_login_top_unique"), Period.DAY, periodEndDates);
    Assert.assertNotNull(results);
    assertEquals(2, results.size());

    SortedMap<Date, Object> metricResult = results.get("page_active_users");
    assertEquals(4, metricResult.size());
    // {"name":0,"fql_result_set":[{"metric":"page_active_users","value":761},{"metric":"page_tab_views_login_top_unique","value":{"wall":30,"app_4949752878":3,"photos":2}}]},
    // here we validate the date map is sorted, so the results will come out in
    // a predictable order
    Iterator<Object> itValues = metricResult.values().iterator();
    assertEquals(761, itValues.next());
    assertEquals(705, itValues.next());
    assertEquals(582, itValues.next());
    assertEquals(125, itValues.next());

    metricResult = results.get("page_tab_views_login_top_unique");
    assertEquals(4, metricResult.size());
    JsonObject o = (JsonObject) metricResult.get(d20030629_0000pst);
    assertEquals(3, o.length());
    assertEquals(2, o.getInt("photos"));
    assertEquals(3, o.getInt("app_4949752878"));
    assertEquals(30, o.getInt("wall"));

    o = (JsonObject) metricResult.get(d20030630_0000pst);
    assertEquals(4, o.length());
    assertEquals(1, o.getInt("photos"));
    assertEquals(1, o.getInt("app_4949752878"));
    assertEquals(2, o.getInt("app_2373072738"));
    assertEquals(23, o.getInt("wall"));

    o = (JsonObject) metricResult.get(d20030701_0000pst);
    assertEquals(2, o.length());
    assertEquals(1, o.getInt("app_4949752878"));
    assertEquals(12, o.getInt("wall"));

    o = (JsonObject) metricResult.get(d20030702_0000pst);
    assertEquals(2, o.length());
    assertEquals(1, o.getInt("photos"));
    assertEquals(11, o.getInt("wall"));
}

From source file:org.eclipse.jubula.client.ui.rcp.handlers.project.OpenProjectHandler.java

/**
 * Checks all available projects/*from   w  ww .j ava 2  s.c o  m*/
 * 
 * @return list of all projects
 */
private List<IProjectPO> checkAllAvailableProjects() {
    List<IProjectPO> projList = null;
    try {
        projList = ProjectPM.findAllProjects();
        if (projList.isEmpty()) {
            Display.getDefault().asyncExec(new Runnable() {
                public void run() {
                    ErrorHandlingUtil.createMessageDialog(MessageIDs.I_NO_PROJECT_IN_DB);
                }
            });
            Plugin.stopLongRunning();
        } else {
            SortedMap<String, List<String>> projNameToVersionMap = new TreeMap<String, List<String>>();
            for (IProjectPO proj : projList) {
                String projName = proj.getName();
                String projVersion = proj.getVersionString();
                if (!StringUtils.isBlank(projName) && !projNameToVersionMap.containsKey(projName)) {
                    projNameToVersionMap.put(projName, new ArrayList<String>());
                }
                projNameToVersionMap.get(projName).add(projVersion);
            }
        }
    } catch (final JBException e) {
        Display.getDefault().asyncExec(new Runnable() {
            public void run() {
                ErrorHandlingUtil.createMessageDialog(e, null, null);
            }
        });
    }
    return projList;
}

From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step6GraphTransitivityCleaner.java

public static SortedMap<String, DescriptiveStatistics> collectStatisticsOverGraphCleaningResults(
        Collection<GraphCleaningResults> results) throws IllegalAccessException {

    SortedMap<String, DescriptiveStatistics> result = new TreeMap<>();

    for (GraphCleaningResults r : results) {
        Field[] declaredFields = GraphCleaningResults.class.getDeclaredFields();
        //            System.out.println(Arrays.toString(declaredFields));
        for (Field field : declaredFields) {
            String fieldName = field.getName();

            if (!result.containsKey(fieldName)) {
                result.put(fieldName, new DescriptiveStatistics());
            }// w ww  . j ava 2s .c  o m

            Object value = field.get(r);

            double doubleVal;

            if (value instanceof Integer) {
                doubleVal = ((Integer) value).doubleValue();
            } else if (value instanceof Double) {
                doubleVal = (Double) value;
            } else {
                throw new IllegalStateException("Unkown type " + value.getClass());
            }

            //                System.out.println(doubleVal);

            result.get(fieldName).addValue(doubleVal);
        }

    }

    return result;
}

From source file:org.apache.cassandra.db.index.sasi.disk.TokenTreeTest.java

@Test
public void buildWithMultipleMapsAndIterate() throws Exception {
    final SortedMap<Long, LongSet> merged = new TreeMap<>();
    final TokenTreeBuilder builder = new TokenTreeBuilder(simpleTokenMap).finish();
    builder.add(collidingTokensMap);/*from   w  ww.jav  a 2s .c  om*/

    merged.putAll(collidingTokensMap);
    for (Map.Entry<Long, LongSet> entry : simpleTokenMap.entrySet()) {
        if (merged.containsKey(entry.getKey())) {
            LongSet mergingOffsets = entry.getValue();
            LongSet existingOffsets = merged.get(entry.getKey());

            if (mergingOffsets.equals(existingOffsets))
                continue;

            Set<Long> mergeSet = new HashSet<>();
            for (LongCursor merging : mergingOffsets)
                mergeSet.add(merging.value);

            for (LongCursor existing : existingOffsets)
                mergeSet.add(existing.value);

            LongSet mergedResults = new LongOpenHashSet();
            for (Long result : mergeSet)
                mergedResults.add(result);

            merged.put(entry.getKey(), mergedResults);
        } else {
            merged.put(entry.getKey(), entry.getValue());
        }
    }

    final Iterator<Pair<Long, LongSet>> tokenIterator = builder.iterator();
    final Iterator<Map.Entry<Long, LongSet>> listIterator = merged.entrySet().iterator();
    while (tokenIterator.hasNext() && listIterator.hasNext()) {
        Pair<Long, LongSet> tokenNext = tokenIterator.next();
        Map.Entry<Long, LongSet> listNext = listIterator.next();

        Assert.assertEquals(listNext.getKey(), tokenNext.left);
        Assert.assertEquals(listNext.getValue(), tokenNext.right);
    }

    Assert.assertFalse("token iterator not finished", tokenIterator.hasNext());
    Assert.assertFalse("list iterator not finished", listIterator.hasNext());

}

From source file:de.pixida.logtest.designer.logreader.LogReaderEditor.java

private List<Triple<String, Node, String>> createConfigurationForm() {
    final List<Triple<String, Node, String>> formItems = new ArrayList<>();

    // Headline pattern
    final TextField textInput = new TextField(this.logReader.getHeadlinePattern());
    textInput.textProperty().addListener((ChangeListener<String>) (observable, oldValue, newValue) -> {
        this.logReader.setHeadlinePattern(newValue);
        this.setChanged(true);
    });/*from  w w  w  .j  a  va  2  s .co m*/
    textInput.setStyle("-fx-font-family: monospace");
    formItems.add(Triple.of("Headline Pattern", textInput,
            "The perl style regular expression is used to spot the beginning of"
                    + " log entries in the log file. If a log entry consists of multiple lines, this pattern must only match the first"
                    + " line, called \"head line\". Groups can intentionally be matched to spot values like timestamp or channel name."
                    + " All matching groups are removed from the payload before they are processed by an automaton."));

    // Index of timestamp
    Supplier<Integer> getter = () -> this.logReader.getHeadlinePatternIndexOfTimestamp();
    Consumer<Integer> setter = value -> this.logReader.setHeadlinePatternIndexOfTimestamp(value);
    final TextField indexOfTimestampInput = this.createIntegerInputField(textInput, getter, setter);
    formItems.add(Triple.of("Timestamp Group", indexOfTimestampInput,
            "Denotes which matching group in the headline pattern contains"
                    + " the timestamp. Index 0 references the whole pattern match, index 1 is the first matching group etc. The timestamp must"
                    + " always be a valid integer. Currently, this integer is always interpreted as milliseconds. If no value is set, no"
                    + " timestamp will be extracted and timing conditions cannot be used. If the referenced matching group is optional"
                    + " and does not match for a specific head line, the last recent timestamp will be used for the extracted log entry."));

    // Index of channel
    getter = () -> this.logReader.getHeadlinePatternIndexOfChannel();
    setter = value -> this.logReader.setHeadlinePatternIndexOfChannel(value);
    final TextField indexOfChannelInput = this.createIntegerInputField(textInput, getter, setter);
    formItems.add(Triple.of("Channel Group", indexOfChannelInput,
            "Denotes which matching group in the headline pattern contains"
                    + " the channel. If the value is empty or the matching group is optional and it did not match, the default channel is used"
                    + " for the extracted log entry."));

    // Trim payload
    CheckBox cb = new CheckBox();
    cb.setSelected(this.logReader.getTrimPayload());
    cb.selectedProperty().addListener((ChangeListener<Boolean>) (observable, oldValue, newValue) -> {
        this.logReader.setTrimPayload(BooleanUtils.toBoolean(newValue));
        this.setChanged(true);
    });
    formItems.add(Triple.of("Trim Payload", cb, "Only has effect on multiline payloads."
            + " If enabled, all leading and trailing whitespaces are removed from the payload"
            + " after the matching groups are removed. This allows for regular expressions in the automaton that match the beginning"
            + " and the end of the payload, without having to take care too much for whitespaces in the source log file."));

    // Handling of non headline lines
    this.createInputForHandlingOfNonHeadlineLines(formItems);

    // Trim payload
    cb = new CheckBox();
    cb.setSelected(this.logReader.getRemoveEmptyPayloadLinesFromMultilineEntry());
    cb.selectedProperty().addListener((ChangeListener<Boolean>) (observable, oldValue, newValue) -> {
        this.logReader.setRemoveEmptyPayloadLinesFromMultilineEntry(BooleanUtils.toBoolean(newValue));
        this.setChanged(true);
    });
    formItems.add(Triple.of("Remove Empty Lines", cb,
            "If enabled, empty lines will be removed from multiline payload entries."));

    // Charset
    final SortedMap<String, Charset> charsets = Charset.availableCharsets();
    final ChoiceBox<String> encodingInput = new ChoiceBox<>(
            FXCollections.observableArrayList(charsets.keySet()));
    encodingInput.getSelectionModel().select(this.logReader.getLogFileCharset().name());
    encodingInput.getSelectionModel().selectedItemProperty()
            .addListener((ChangeListener<String>) (observable, oldValue, newValue) -> {
                this.logReader.setLogFileCharset(charsets.get(newValue));
                this.setChanged(true);
            });
    formItems.add(Triple.of("Log File Encoding", encodingInput,
            "Encoding of the log file. Note that some of the encodings are"
                    + " platform specific such that reading the log on a different platform might fail. Usually, log files are written"
                    + " using UTF-8, UTF-16, ISO-8859-1 or ASCII."));

    return formItems;
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.ViewHomepageDA.java

public ActionForward listTeachers(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    final SortedMap<Unit, SortedSet<Homepage>> homepages = new TreeMap<Unit, SortedSet<Homepage>>(
            Unit.COMPARATOR_BY_NAME_AND_ID);
    for (final Teacher teacher : rootDomainObject.getTeachersSet()) {
        final Person person = teacher.getPerson();
        final Employee employee = person.getEmployee();
        if (employee != null) {
            final Contract contract = employee.getCurrentWorkingContract();
            if (contract != null) {
                final Unit unit = contract.getWorkingUnit();
                final SortedSet<Homepage> unitHomepages;
                if (homepages.containsKey(unit)) {
                    unitHomepages = homepages.get(unit);
                } else {
                    unitHomepages = new TreeSet<Homepage>(Homepage.HOMEPAGE_COMPARATOR_BY_NAME);
                    homepages.put(unit, unitHomepages);
                }/*from w  ww  .j a va2 s .  c  o m*/
                final Homepage homepage = person.getHomepage();
                if (homepage != null && homepage.getActivated().booleanValue()) {
                    unitHomepages.add(homepage);
                }
            }
        }
    }
    request.setAttribute("homepages", homepages);

    final String selectedPage = request.getParameter("selectedPage");
    if (selectedPage != null) {
        request.setAttribute("selectedPage", selectedPage);
    }

    return mapping.findForward("list-homepages-teachers");
}

From source file:edu.umd.cfar.lamp.viper.util.Range.java

/**
 * Subsumes the Instants in the Span into this Range. 
 * @param start the first instant to add
 * @param stop the stop instant, exclusive
 * @return <code>true</code> iff the operation modified this Range
 *//*from  ww w .  j a  va2s  .co  m*/
public boolean add(Comparable start, Comparable stop) {
    Comparable old = (Comparable) spans.get(start);
    if (old != null && old.compareTo(stop) >= 0) {
        return false;
    }
    SortedMap head = spans.headMap(start);
    if (!head.isEmpty()) {
        Comparable oldStart = (Comparable) head.lastKey();
        Comparable oldEnd = (Comparable) head.get(oldStart);
        if (oldEnd.compareTo(stop) >= 0) {
            return false;
        } else {
            if (oldEnd.compareTo(start) >= 0) {
                start = oldStart;
                spans.remove(oldStart);
            }
        }
    }
    SortedMap sub = spans.subMap(start, stop);
    if (!sub.isEmpty()) {
        Comparable oldStart = (Comparable) sub.lastKey();
        Comparable oldEnd = (Comparable) sub.get(oldStart);
        if (oldStart.compareTo(start) == 0 && oldEnd.compareTo(stop) >= 0) {
            return false;
        } else if (oldEnd.compareTo(stop) > 0) {
            stop = oldEnd;
        }
        sub.clear();
    }
    if (spans.containsKey(stop)) {
        stop = (Comparable) spans.remove(stop);
    }
    spans.put(start, stop);
    return true;
}

From source file:org.opencms.workplace.CmsWidgetDialogParameter.java

/**
 * Create a new Widget parameter.<p>
 * /*from  w  ww .  ja  v a2  s.  c  o  m*/
 * @param base the base of the parameter
 * @param index the index of this parameter in the list
 * @param originalIndex the original index in the previous version of the list
 */
public CmsWidgetDialogParameter(CmsWidgetDialogParameter base, int index, int originalIndex) {

    this(null, base.m_defaultValue, base.getName(), base.getWidget(), base.getDialogPage(), base.getMinOccurs(),
            base.getMaxOccurs(), index);

    m_baseObject = base.m_baseObject;
    m_baseObjectProperty = base.m_baseObjectProperty;
    m_baseCollection = base.m_baseCollection;

    if (m_baseCollection != null) {
        if (m_baseCollection instanceof List) {
            // base object is a list - make sure to set possible old value 
            List<?> baseList = (List<?>) m_baseCollection;
            if (originalIndex < baseList.size()) {
                Object o = baseList.get(originalIndex);
                if (o != null) {
                    m_value = o.toString();
                }
            }
        } else if (m_baseCollection instanceof SortedMap) {
            // base object is a sorted map - make sure to set possible old value 
            SortedMap<?, ?> baseMap = (SortedMap<?, ?>) m_baseCollection;
            @SuppressWarnings({ "unchecked", "rawtypes" })
            List<?> keyList = new ArrayList(baseMap.keySet());
            if (originalIndex < keyList.size()) {
                Object key = keyList.get(originalIndex);
                Object value = baseMap.get(key);
                StringBuffer val = new StringBuffer();
                val.append(key != null ? key.toString() : "");
                val.append('=');
                val.append(value != null ? value.toString() : "");
                m_value = val.toString();
            }
        }
    }
}

From source file:edu.umd.cfar.lamp.viper.util.Range.java

/**
 * @see edu.umd.cfar.lamp.viper.util.IntervalIndexList#remove(java.lang.Comparable, java.lang.Comparable)
 *///from  w ww.  j  a  va  2  s.co  m
public boolean remove(Comparable start, Comparable end) {
    boolean someFound = false;
    SortedMap head = spans.headMap(start);
    if (!head.isEmpty()) {
        Comparable oldStart = (Comparable) head.lastKey();
        Comparable oldEnd = (Comparable) head.get(oldStart);
        if (oldEnd.compareTo(start) > 0) {
            // if there is a span that goes into the span to
            // be removed, replace it.
            head.put(oldStart, start);
            someFound = true;
            double toCheck = oldEnd.compareTo(end);
            if (toCheck > 0) {
                // if the span to be removed is a strict subset 
                // of some existing span, you also have
                // to add back the end.
                spans.put(end, oldEnd);
                return true;
            } else if (toCheck == 0) {
                return true;
            }
        }
    }
    SortedMap sub = spans.subMap(start, end);
    if (!sub.isEmpty()) {
        someFound = true;
        Comparable oldStart = (Comparable) sub.lastKey();
        Comparable oldEnd = (Comparable) sub.get(oldStart);
        if (oldEnd.compareTo(end) > 0) {
            // if there is a span that starts during the
            // span to removed that goes past the end,
            // have to add back the difference.
            spans.put(end, oldEnd);
        }
        sub.clear();
    }
    return someFound;
}