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:net.sourceforge.pmd.docs.RuleDocGenerator.java

private Map<Language, List<RuleSet>> sortRulesets(Iterator<RuleSet> rulesets) throws RuleSetNotFoundException {
    SortedMap<Language, List<RuleSet>> rulesetsByLanguage = new TreeMap<>();

    while (rulesets.hasNext()) {
        RuleSet ruleset = rulesets.next();
        Language language = getRuleSetLanguage(ruleset);

        if (!rulesetsByLanguage.containsKey(language)) {
            rulesetsByLanguage.put(language, new ArrayList<RuleSet>());
        }//from w ww . j  a v a2  s . co  m
        rulesetsByLanguage.get(language).add(ruleset);
    }

    for (List<RuleSet> rulesetsOfOneLanguage : rulesetsByLanguage.values()) {
        Collections.sort(rulesetsOfOneLanguage, new Comparator<RuleSet>() {
            @Override
            public int compare(RuleSet o1, RuleSet o2) {
                return o1.getName().compareToIgnoreCase(o2.getName());
            }
        });
    }
    return rulesetsByLanguage;
}

From source file:eu.stratosphere.pact.runtime.hash.MultiLevelHashITCase.java

private void printStatistics() {
    for (int level = 0; level < maxLevel; level++) {
        int bucketCountInLevel = 0;

        SortedMap<Integer, Integer> levelMap = bucketSizesPerLevel.get(level);
        Iterator<Integer> bucketSizeIterator = levelMap.keySet().iterator();

        LOG.debug("Statistics for level: " + level);
        LOG.debug("----------------------------------------------");
        LOG.debug("");
        LOG.debug("Bucket Size |      Count");
        LOG.debug("------------------------");

        int i = 0;
        while (bucketSizeIterator.hasNext()) {
            int bucketSize = bucketSizeIterator.next();
            if (bucketSize != 0) {
                int countForBucketSize = levelMap.get(bucketSize);
                bucketCountInLevel += countForBucketSize;
                Formatter formatter = new Formatter();
                formatter.format(" %10d | %10d", bucketSize, countForBucketSize);

                if (levelMap.size() < 20 || i < 3 || i >= (levelMap.size() - 3)) {
                    LOG.debug(formatter.out());
                } else if (levelMap.size() / 2 == i) {
                    LOG.debug("         .. |         ..");
                    LOG.debug(formatter.out());
                    LOG.debug("         .. |         ..");
                }/*from  w ww  .ja  v a 2  s  . co m*/
                i++;
            }
        }

        LOG.debug("");
        LOG.debug("Number of non-empty buckets in level: " + bucketCountInLevel);
        LOG.debug("Number of empty buckets in level    : " + levelMap.get(0));
        LOG.debug("Number of different bucket sizes    : " + (levelMap.size() - 1));
        LOG.debug("");
        LOG.debug("");
        LOG.debug("");
    }
}

From source file:openlr.mapviewer.coding.ui.AbstractCodingOptionsDialog.java

/**
 * Builds a configuration map from the given {@link FileConfiguration}. It is
 * assumed that the configuration contains of key with maximum nesting of
 * two levels. Each "topic" of parameters, i.e. parameters with the same
 * prefix, is stored in a map entry. The sub-keys configurations below the
 * topic parent represent the value to the key in form of a list of
 * key-value elements ({@link ConfigEntry}). If there is no nesting for a
 * configuration key the map key will be the original configuration key, the
 * value will be a {@link ConfigEntry} with again the property key as key
 * and the single value./*from  w w  w. java 2 s.  co  m*/
 * 
 * @param config
 *            The configuration to process
 * @return The configuration map
 */
private SortedMap<String, List<ConfigEntry>> buildConfigurationMap(final FileConfiguration config) {

    SortedMap<String, List<ConfigEntry>> map = new TreeMap<String, List<ConfigEntry>>();

    Iterator<?> iter = config.getKeys();
    while (iter.hasNext()) {

        String key = iter.next().toString();
        // skip all attributes in our case these are the XML attributes
        if (!key.startsWith("[@")) {

            String[] parts = key.split("\\.");
            String value = config.getString(key);

            if (parts.length == 2) {

                String topic = parts[0];
                String subKey = parts[1];

                List<ConfigEntry> subKeysAndValues = map.get(topic);
                if (subKeysAndValues == null) {
                    subKeysAndValues = new ArrayList<ConfigEntry>();
                    map.put(topic, subKeysAndValues);
                }

                subKeysAndValues.add(new ConfigEntry(key, subKey, value));
            } else if (parts.length == 1) {

                map.put(key, Arrays.asList(new ConfigEntry(key, key, value)));
            } else {
                throw new IllegalStateException(
                        "Unexpected format of OpenLR properties. Nesting level was assumed to be at most 2 but was "
                                + parts.length);
            }
        }
    }
    return map;
}

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

/**
 * Checks to see if the interval defined as [s,e)
 * is entirely contained within this Range object.
 * //from w ww .j  a  v a2 s.c  om
 * @param s
 * @param e
 * @return boolean
 */
public boolean withinRange(Comparable s, Comparable e) {
    SortedMap m = spans.headMap(e);
    if (!m.isEmpty()) {
        // thankfully Range keeps contiguous spans merged,
        // so this is easy
        Comparable start = (Comparable) m.lastKey();
        Comparable end = (Comparable) m.get(start);
        if (end.compareTo(s) >= 0) {
            return start.compareTo(s) <= 0 && end.compareTo(e) >= 0;
        }
    }
    m = spans.tailMap(s);
    if (!m.isEmpty()) {
        Comparable sPrime = (Comparable) m.firstKey();
        if (sPrime.compareTo(s) == 0) {
            return e.compareTo((Comparable) m.get(sPrime)) <= 0;
        }
    }
    return false;
}

From source file:com.aurel.track.fieldType.runtime.matchers.converter.CompositSelectMatcherConverter.java

/**
 * Convert the object value to xml string for save
 * @param value/*from ww w. ja va  2s  . c  o m*/
 * @param matcherRelation
 * @return
 */
@Override
public String toXMLString(Object value, Integer matcherRelation) {
    if (value == null || matcherRelation == null) {
        return null;
    }
    switch (matcherRelation.intValue()) {
    case MatchRelations.EQUAL:
    case MatchRelations.NOT_EQUAL:
    case MatchRelations.PARTIAL_MATCH:
    case MatchRelations.PARTIAL_NOTMATCH:
        SortedMap<Integer, Integer[]> actualValuesMap = null;
        try {
            actualValuesMap = (SortedMap<Integer, Integer[]>) value;
        } catch (Exception e) {
            LOGGER.warn("Converting the " + value
                    + " to SortedMap<Integer, Integer[]> for display string failed with " + e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
        if (actualValuesMap != null) {
            StringBuffer stringBuffer = new StringBuffer();
            Iterator<Integer> iterator = actualValuesMap.keySet().iterator();
            while (iterator.hasNext()) {
                Integer partNo = iterator.next();
                Integer[] partValueArr = null;
                try {
                    partValueArr = actualValuesMap.get(partNo);
                } catch (Exception e) {
                    LOGGER.warn("Converting the part " + partNo
                            + " to Integer[] for XML string string failed with " + e.getMessage());
                    LOGGER.debug(ExceptionUtils.getStackTrace(e));
                }
                String partValue = "";
                if (partValueArr != null && partValueArr.length > 0) {
                    //partValue is probably an integer array
                    //if there is a possibility that the composite contains also other
                    //datatypes for example date which should be formatted then 
                    //we would need to extend the API with further method parameters
                    partValue = partValueArr[0].toString();
                }
                stringBuffer.append(partValue);
                if (iterator.hasNext()) {
                    stringBuffer.append(PART_SPLITTER_STRING);
                }
            }
            return stringBuffer.toString().trim();
        }
    }
    return null;
}

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

public ActionForward listEmployees(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 Employee employee : rootDomainObject.getEmployeesSet()) {
        final Person person = employee.getPerson();
        if (person != null) {
            final Teacher teacher = person.getTeacher();
            if (teacher == 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  w w  .  j  av a  2  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-employees");
}

From source file:org.formix.dsx.serialization.XmlSerializer.java

@SuppressWarnings("unchecked")
private Collection<Object> getCollectionValue(XmlElement elem, Class<?> paramType,
        SortedMap<String, Method> parentMethods, Object parent) throws XmlException {

    Collection<Object> col = null;
    if ((parentMethods != null) && (parent != null)) {

        String methodName = "get" + this.capitalize(elem.getName());
        String signature = parentMethods.tailMap(methodName).firstKey();
        Method colGetterMethod = parentMethods.get(signature);

        try {/*from  ww w . j  av a2 s.c  o m*/
            col = (Collection<Object>) colGetterMethod.invoke(parent, (Object[]) null);

        } catch (Exception e) {
            throw new XmlException("Unable to invoke collection getter: " + colGetterMethod.getName(), e);
        }
    }

    try {
        if (col == null)
            col = this.createCollection(paramType);
    } catch (Exception e) {
        throw new XmlException("Unable to create collection type: " + paramType.getName(), e);
    }

    for (XmlContent colContent : elem.getChilds()) {
        if (colContent instanceof XmlElement) {
            XmlElement colElem = (XmlElement) colContent;

            Object objToAdd = null;
            Class<?> colElemType = null;
            String colElemTypeName = this.capitalize(colElem.getName());
            try {
                colElemType = this.getType(colElemTypeName);
            } catch (ClassNotFoundException e) {
                throw new XmlException(
                        "Unable to find the collection's internal element type: " + colElemTypeName, e);
            }

            objToAdd = this.deserialize(colElem, colElemType);

            col.add(objToAdd);
        }
    }

    return col;
}

From source file:org.web4thejob.web.util.ToolbarRenderer.java

private SortedMap<CommandEnum, List<Command>> mergeCommands() {
    SortedMap<CommandEnum, List<Command>> map = new TreeMap<CommandEnum, List<Command>>(COMMANDS_SORTER);

    for (CommandAware owner : commandOwners) {
        if (owner instanceof PlaceholderPanel && !owner.equals(getPrimaryOwner())) {
            continue;
        }/*from  ww  w.ja  va  2 s.c  om*/

        SortedSet<Command> commands;
        if (owner instanceof CommandMerger) {
            commands = ((CommandMerger) owner).getMergedCommands();
        } else {
            commands = owner.getCommands();
        }
        for (final Command command : commands) {
            if (isMergable(command)) {
                if (map.containsKey(command.getId())) {
                    if (!map.get(command.getId()).contains(command)) {
                        map.get(command.getId()).add(command);
                    }
                } else {
                    List<Command> list = new ArrayList<Command>();
                    list.add(command);
                    map.put(command.getId(), list);
                }
            }
        }

    }

    return map;
}

From source file:com.aurel.track.item.history.HistoryLoaderBL.java

/**
 * Get the raw history (only the values, no show values, field names) for a workItemID
 * @param workItemID/*  www  .  j a va  2 s .  c o  m*/
 * @param filterFieldIDs
 * @param personID
 * @param fromDate
 * @param toDate
 * @return
 */
public static SortedMap<Integer, Map<Integer, HistoryValues>> getWorkItemRawHistory(Integer workItemID,
        Integer[] filterFieldIDs, List<Integer> personIDs, Date fromDate, Date toDate) {

    int[] workItemIDs = new int[] { workItemID };
    List<THistoryTransactionBean> historyTransactionBeanList = HistoryTransactionBL
            .getByWorkItemsAndFields(workItemIDs, filterFieldIDs, true, personIDs, fromDate, toDate);
    addPersonNamesToHistoryTransactionBeans(historyTransactionBeanList);
    Map<Integer, THistoryTransactionBean> historyTransactionBeanMap = GeneralUtils
            .createMapFromList(historyTransactionBeanList);
    List<TFieldChangeBean> fieldChangeBeanList = FieldChangeBL.getByWorkItemsAndFields(workItemIDs,
            filterFieldIDs, true, personIDs, fromDate, toDate);
    Map<Integer, Map<Integer, Map<String, Object>>> workItemsFieldChangeBeansMap = getFieldChangeBeansByWorkItemAndTransactionAndMergedField(
            historyTransactionBeanMap, fieldChangeBeanList);
    Map<Integer, SortedMap<Integer, Map<Integer, HistoryValues>>> workItemsHistoryValuesMap = new HashMap<Integer, SortedMap<Integer, Map<Integer, HistoryValues>>>();
    Iterator<Integer> workItemIDsIterator = workItemsFieldChangeBeansMap.keySet().iterator();
    while (workItemIDsIterator.hasNext()) {
        workItemID = workItemIDsIterator.next();
        Map<Integer, Map<String, Object>> workItemFieldChangeBeansMap = workItemsFieldChangeBeansMap
                .get(workItemID);
        Iterator<Integer> transactionIDsIterator = workItemFieldChangeBeansMap.keySet().iterator();
        while (transactionIDsIterator.hasNext()) {
            Integer historyTransactionID = transactionIDsIterator.next();
            Map<String, Object> transactionFieldChangeBeansMap = workItemFieldChangeBeansMap
                    .get(historyTransactionID);
            Iterator<String> mergeKeysIterator = transactionFieldChangeBeansMap.keySet().iterator();
            Map<String, Object> newValuesHistoryMap = new HashMap<String, Object>();
            Map<String, Object> oldValuesHistoryMap = new HashMap<String, Object>();
            while (mergeKeysIterator.hasNext()) {
                String mergeKey = mergeKeysIterator.next();
                Integer[] parts = MergeUtil.getParts(mergeKey);
                Integer fieldID = parts[0];
                Integer parameterCode = parts[1];
                if (parameterCode == null || parameterCode.intValue() == 1) {
                    IFieldTypeRT fieldTypeRT = null;
                    if (TFieldChangeBean.COMPOUND_HISTORY_FIELD.equals(fieldID)) {
                        //load the Compound field is loaded similar like Description (longText)  
                        fieldTypeRT = FieldTypeManager.getFieldTypeRT(SystemFields.INTEGER_DESCRIPTION);
                    } else {
                        fieldTypeRT = FieldTypeManager.getFieldTypeRT(fieldID);
                    }
                    if (fieldTypeRT == null) {
                        LOGGER.info("Fieldtype unknown for field " + fieldID);
                        continue;
                    }
                    fieldTypeRT.processHistoryLoad(fieldID, null, transactionFieldChangeBeansMap,
                            newValuesHistoryMap, oldValuesHistoryMap);
                    SortedMap<Integer, Map<Integer, HistoryValues>> workItemHistoryValuesMap = workItemsHistoryValuesMap
                            .get(workItemID);
                    if (workItemHistoryValuesMap == null) {
                        workItemHistoryValuesMap = new TreeMap<Integer, Map<Integer, HistoryValues>>();
                        workItemsHistoryValuesMap.put(workItemID, workItemHistoryValuesMap);
                    }
                    Map<Integer, HistoryValues> historyTransactionMap = workItemHistoryValuesMap
                            .get(historyTransactionID);
                    if (historyTransactionMap == null) {
                        historyTransactionMap = new TreeMap<Integer, HistoryValues>();
                        workItemHistoryValuesMap.put(historyTransactionID, historyTransactionMap);
                    }
                    HistoryValues historyValues = initHistoryValues(
                            historyTransactionBeanMap.get(historyTransactionID));
                    historyValues.setDate(fieldTypeRT.getValueType() == ValueType.DATE
                            || fieldTypeRT.getValueType() == ValueType.DATETIME);
                    historyValues.setObjectID(getFirstFieldChangeID(fieldID, parameterCode,
                            transactionFieldChangeBeansMap.get(mergeKey)));
                    historyValues.setTimesEdited(
                            getTimesEdited(fieldID, transactionFieldChangeBeansMap.get(mergeKey)));
                    historyValues.setTransactionID(historyTransactionID);
                    historyValues.setFieldID(fieldID);
                    historyValues.setLongField(fieldTypeRT.isLong());
                    Object newValue = getAttribute(newValuesHistoryMap, fieldID, fieldTypeRT);
                    Object oldValue = getAttribute(oldValuesHistoryMap, fieldID, fieldTypeRT);
                    historyValues.setNewValue(newValue);
                    historyValues.setOldValue(oldValue);
                    historyTransactionMap.put(fieldID, historyValues);
                }
            }
        }
    }
    return workItemsHistoryValuesMap.get(workItemID);
}

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

/**
 * this can be very large - avoid loading the entire jdbc ResultSet into
 * memory/*from www.  j a  va  2s.com*/
 */
@Override
public InstanceData loadInstances(String strQuery) {
    final InstanceData instanceLabel = new InstanceData();
    PreparedStatement s = null;
    Connection conn = null;
    ResultSet rs = null;
    try {
        // jdbcTemplate.query(strQuery, new RowCallbackHandler() {
        RowCallbackHandler ch = new RowCallbackHandler() {

            @Override
            public void processRow(ResultSet rs) throws SQLException {
                String label = "";
                int run = 0;
                int fold = 0;
                boolean train = true;
                long instanceId = rs.getLong(1);
                String className = rs.getString(2);
                if (rs.getMetaData().getColumnCount() >= 3)
                    train = rs.getBoolean(3);
                if (rs.getMetaData().getColumnCount() >= 4) {
                    label = rs.getString(4);
                    if (label == null)
                        label = "";
                }
                if (rs.getMetaData().getColumnCount() >= 5)
                    fold = rs.getInt(5);
                if (rs.getMetaData().getColumnCount() >= 6)
                    run = rs.getInt(6);
                // get runs for label
                SortedMap<Integer, SortedMap<Integer, SortedMap<Boolean, SortedMap<Long, String>>>> runToInstanceMap = instanceLabel
                        .getLabelToInstanceMap().get(label);
                if (runToInstanceMap == null) {
                    runToInstanceMap = new TreeMap<Integer, SortedMap<Integer, SortedMap<Boolean, SortedMap<Long, String>>>>();
                    instanceLabel.getLabelToInstanceMap().put(label, runToInstanceMap);
                }
                // get folds for run
                SortedMap<Integer, SortedMap<Boolean, SortedMap<Long, String>>> foldToInstanceMap = runToInstanceMap
                        .get(run);
                if (foldToInstanceMap == null) {
                    foldToInstanceMap = new TreeMap<Integer, SortedMap<Boolean, SortedMap<Long, String>>>();
                    runToInstanceMap.put(run, foldToInstanceMap);
                }
                // get train/test set for fold
                SortedMap<Boolean, SortedMap<Long, String>> ttToClassMap = foldToInstanceMap.get(fold);
                if (ttToClassMap == null) {
                    ttToClassMap = new TreeMap<Boolean, SortedMap<Long, String>>();
                    foldToInstanceMap.put(fold, ttToClassMap);
                }
                // get instances for train/test set
                SortedMap<Long, String> instanceToClassMap = ttToClassMap.get(train);
                if (instanceToClassMap == null) {
                    instanceToClassMap = new TreeMap<Long, String>();
                    ttToClassMap.put(train, instanceToClassMap);
                }
                // set the instance class
                instanceToClassMap.put(instanceId, className);
                // add the class to the labelToClassMap
                SortedSet<String> labelClasses = instanceLabel.getLabelToClassMap().get(label);
                if (labelClasses == null) {
                    labelClasses = new TreeSet<String>();
                    instanceLabel.getLabelToClassMap().put(label, labelClasses);
                }
                if (!labelClasses.contains(className))
                    labelClasses.add(className);
            }
        };
        conn = this.jdbcTemplate.getDataSource().getConnection();
        s = conn.prepareStatement(strQuery, java.sql.ResultSet.TYPE_FORWARD_ONLY,
                java.sql.ResultSet.CONCUR_READ_ONLY);
        if ("MySQL".equals(conn.getMetaData().getDatabaseProductName())) {
            s.setFetchSize(Integer.MIN_VALUE);
        } else if (s.getClass().getName().equals("com.microsoft.sqlserver.jdbc.SQLServerStatement")) {
            try {
                BeanUtils.setProperty(s, "responseBuffering", "adaptive");
            } catch (IllegalAccessException e) {
                log.warn("error setting responseBuffering", e);
            } catch (InvocationTargetException e) {
                log.warn("error setting responseBuffering", e);
            }
        }
        rs = s.executeQuery();
        while (rs.next()) {
            ch.processRow(rs);
        }
    } catch (SQLException j) {
        log.error("loadInstances failed", j);
        throw new RuntimeException(j);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
            }
        }
        if (s != null) {
            try {
                s.close();
            } catch (SQLException e) {
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
            }
        }
    }
    return instanceLabel;
}