Example usage for java.util TreeMap entrySet

List of usage examples for java.util TreeMap entrySet

Introduction

In this page you can find the example usage for java.util TreeMap entrySet.

Prototype

EntrySet entrySet

To view the source code for java.util TreeMap entrySet.

Click Source Link

Document

Fields initialized to contain an instance of the entry set view the first time this view is requested.

Usage

From source file:org.sakaiproject.memory.impl.HazelcastMemoryService.java

@Override
public String getStatus() {
    // MIRRORS the OLD status report
    final StringBuilder buf = new StringBuilder();
    buf.append("** Memory report\n");
    buf.append("freeMemory: ").append(Runtime.getRuntime().freeMemory());
    buf.append(" totalMemory: ");
    buf.append(Runtime.getRuntime().totalMemory());
    buf.append(" maxMemory: ");
    buf.append(Runtime.getRuntime().maxMemory());
    buf.append("\n\n");

    Collection<DistributedObject> distributedObjects = hcInstance.getDistributedObjects();
    TreeMap<String, IMap> caches = new TreeMap<String, IMap>();
    for (DistributedObject distributedObject : distributedObjects) {
        if (distributedObject instanceof IMap) {
            caches.put(distributedObject.getName(), (IMap) distributedObject);
        }//  w  w  w.ja  v  a 2 s .  com
    }

    // summary (cache descriptions)
    for (Map.Entry<String, IMap> entry : caches.entrySet()) {
        Cache c = new HazelcastCache(entry.getValue());
        buf.append(c.getDescription()).append("\n");
    }

    /* TODO figure out how to get the configs from the IMap
    // config report
    buf.append("\n** Current Cache Configurations\n");
    // determine whether to use old or new form keys
    boolean legacyKeys = true; // set true for a 2.9/BasicMemoryService compatible set of keys
    String maxKey = "maxEntries";
    String ttlKey = "timeToLive";
    String ttiKey = "timeToIdle";
    String eteKey = "eternal";
    //noinspection ConstantConditions
    if (legacyKeys) {
    maxKey = "maxElementsInMemory";
    ttlKey = "timeToLiveSeconds";
    ttiKey = "timeToIdleSeconds";
    }
    // DEFAULT cache config
    CacheConfiguration defaults = cacheManager.getConfiguration().getDefaultCacheConfiguration();
    long maxEntriesDefault = defaults.getMaxEntriesLocalHeap();
    long ttlSecsDefault = defaults.getTimeToLiveSeconds();
    long ttiSecsDefault = defaults.getTimeToIdleSeconds();
    boolean eternalDefault = defaults.isEternal();
    buf.append("# DEFAULTS: ").append(maxKey).append("=").append(maxEntriesDefault).append(",").append(ttlKey).append("=").append(ttlSecsDefault).append(",").append(ttiKey).append("=").append(ttiSecsDefault).append(",").append(eteKey).append("=").append(eternalDefault).append("\n");
    // new: timeToLive=600,timeToIdle=360,maxEntries=5000,eternal=false
    // old: timeToLiveSeconds=3600,timeToIdleSeconds=900,maxElementsInMemory=20000,eternal=false
    for (Ehcache cache : caches) {
    long maxEntries = cache.getCacheConfiguration().getMaxEntriesLocalHeap();
    long ttlSecs = cache.getCacheConfiguration().getTimeToLiveSeconds();
    long ttiSecs = cache.getCacheConfiguration().getTimeToIdleSeconds();
    boolean eternal = cache.getCacheConfiguration().isEternal();
    if (maxEntries == maxEntriesDefault && ttlSecs == ttlSecsDefault && ttiSecs == ttiSecsDefault && eternal == eternalDefault) {
        // Cache ONLY uses the defaults
        buf.append("# memory.").append(cache.getName()).append(" *ALL DEFAULTS*\n");
    } else {
        // NOT only defaults cache, show the settings that differ from the defaults
        buf.append("memory.").append(cache.getName()).append("=");
        boolean first = true;
        if (maxEntries != maxEntriesDefault) {
            //noinspection ConstantConditions
            first = addKeyValueToConfig(buf, maxKey, maxEntries, first);
        }
        if (ttlSecs != ttlSecsDefault) {
            first = addKeyValueToConfig(buf, ttlKey, ttlSecs, first);
        }
        if (ttiSecs != ttiSecsDefault) {
            first = addKeyValueToConfig(buf, ttiKey, ttiSecs, first);
        }
        if (eternal != eternalDefault) {
            addKeyValueToConfig(buf, eteKey, eternal, first);
        }
        buf.append("\n");
        // TODO remove the overflow to disk check
        //noinspection deprecation
        if (cache.getCacheConfiguration().isOverflowToDisk()) {
            // overflowToDisk. maxEntriesLocalDisk
            buf.append("# NOTE: ").append(cache.getName()).append(" is configured for Overflow(disk), ").append(cache.getCacheConfiguration().getMaxEntriesLocalDisk()).append(" entries\n");
        }
    }
    }
    */

    final String rv = buf.toString();
    log.info(rv);

    return rv;
}

From source file:io.fabric8.mq.autoscaler.MQAutoScaler.java

private String getOrderedProperties(Hashtable<String, String> properties) {
    TreeMap<String, String> map = new TreeMap<>(properties);
    String result = "";
    String separator = "";
    for (Map.Entry<String, String> entry : map.entrySet()) {
        result += separator;//from   w w  w  .  j  a v a  2s . c om
        result += entry.getKey() + "=" + entry.getValue();
        separator = ",";
    }
    return result;
}

From source file:com.google.android.apps.authenticator.dataimport.Importer.java

private int importAccountDbFromJson(JSONObject json, AccountDb accountDb) {
    Iterator<String> it = json.keys();
    int importedAccountCount = 0;
    TreeMap<String, JSONObject> map = new TreeMap<String, JSONObject>();
    // iterate over the JSON objects and put them in a sorted map
    while (it.hasNext()) {
        try {//  w  w w . ja v a 2 s.co m
            String key = it.next();
            JSONObject value = json.getJSONObject(key);
            map.put(key, value);
        } catch (Exception e) {
            Log.e(LOG_TAG, "Unable to deserialize JSON string");
            Log.e(LOG_TAG, e.getMessage());
            return -1;
        }
    }

    for (Map.Entry<String, JSONObject> entry : map.entrySet()) {
        String key = entry.getKey();
        JSONObject accountJson = entry.getValue();
        String name = null;
        String secret = null;
        Integer counter = null;
        String typeString = null;
        AccountDb.OtpType type = null;

        try {
            name = accountJson.getString(KEY_NAME);
            if (accountDb.nameExists(name)) {
                Log.w(LOG_TAG, "Skipping account #" + key + ": already configured");
                continue;
            }
        } catch (JSONException e1) {
            Log.w(LOG_TAG, "Skipping account #" + key + ": name missing");
            continue;
        }

        try {
            secret = accountJson.getString(KEY_ENCODED_SECRET);
        } catch (JSONException e2) {
            Log.w(LOG_TAG, "Skipping account #" + key + ": secret missing");
            continue;
        }

        try {
            typeString = accountJson.getString(KEY_TYPE);
            type = AccountDb.OtpType.valueOf(typeString);
        } catch (JSONException e3) {
            Log.w(LOG_TAG, "Skipping account #" + key + ": type missing");
            continue;
        }

        try {
            counter = accountJson.getInt(KEY_COUNTER);
        } catch (JSONException e4) {
            if (type == AccountDb.OtpType.HOTP) {
                Log.w(LOG_TAG, "Skipping account #" + key + ": counter missing");
                continue;
            } else {
                counter = AccountDb.DEFAULT_HOTP_COUNTER;
            }
        }

        if (name != null && secret != null && counter != null && type != null) {
            accountDb.update(name, secret, name, type, counter);
            importedAccountCount++;
        }
    }

    Log.i(LOG_TAG, "Imported " + importedAccountCount + " accounts");
    return importedAccountCount;
}

From source file:de.mpg.mpdl.inge.syndication.feed.Feed.java

/**
 * Populate parameters with the values taken from the certain <code>uri</code> and populate
 * <code>paramHash</code> with the parameter/value paars.
 * /*from  www . j  a va2s  .  co  m*/
 * @param uri
 * @throws SyndicationException
 */
private void populateParamsFromUri(String uri) throws SyndicationException {
    Utils.checkName(uri, "Uri is empty");

    String um = getUriMatcher();

    Utils.checkName(um, "Uri matcher is empty");

    Matcher m = Pattern.compile(um, Pattern.CASE_INSENSITIVE | Pattern.DOTALL).matcher(uri);
    if (m.find()) {
        for (int i = 0; i < m.groupCount(); i++)
            paramHash.put((String) paramList.get(i), m.group(i + 1));
    }

    // special handling of Organizational Unit Feed
    // TODO: should be resolved other way!
    if (getUriMatcher().equals("(.+)?/syndication/feed/(.+)?/publications/organization/(.+)?")) {
        TreeMap<String, String> outm = Utils.getOrganizationUnitTree();
        String oid = (String) paramHash.get("${organizationId}");
        for (Map.Entry<String, String> entry : outm.entrySet()) {
            if (entry.getValue().equals(oid)) {
                paramHash.put("${organizationName}", entry.getKey());
            }
        }
    }

    logger.info("parameters: " + paramHash);

}

From source file:playground.pieter.singapore.demand.InputDataCollection.java

private void createLocationSamplers() {
    inputLog.info(/*w  w w .  ja v  a 2  s. com*/
            "Creating weighted samplers for each activity type,\n indexing the relevant facility ids and their capacity for the particular activity.");
    for (String activityType : this.mainActivityTypes) {
        TreeMap<Id<ActivityFacility>, ActivityFacility> facilities = this.scenario.getActivityFacilities()
                .getFacilitiesForActivityType(activityType);
        Iterator<Entry<Id<ActivityFacility>, ActivityFacility>> fi = facilities.entrySet().iterator();
        String[] ids = new String[facilities.entrySet().size()];
        double[] caps = new double[facilities.entrySet().size()];
        int i = 0;
        while (fi.hasNext()) {
            Entry<Id<ActivityFacility>, ActivityFacility> e = fi.next();
            ids[i] = e.getKey().toString();
            caps[i] = e.getValue().getActivityOptions().get(activityType).getCapacity();

            i++;
        }
        this.locationSamplers.put(activityType, new LocationSampler(activityType, ids, caps));
    }
    inputLog.info("DONE: Creating weighted samplers for each activity type.");
}

From source file:net.tradelib.core.Series.java

public Series toDaily(double identity, BinaryOperator<Double> accumulator) {
    TreeMap<LocalDateTime, Integer> newIndex = buildDailyIndex();
    Series result = new Series();
    int numUnique = newIndex.size();
    result.index = new ArrayList<LocalDateTime>(numUnique);
    result.data = new ArrayList<List<Double>>(data.size());
    for (int ii = 0; ii < data.size(); ++ii) {
        result.data.add(new ArrayList<Double>(newIndex.size()));
    }//  w w w.j  a  v a 2 s.  co  m

    int currentIndex = 0;
    Iterator<Map.Entry<LocalDateTime, Integer>> iter = newIndex.entrySet().iterator();
    while (iter.hasNext()) {
        Map.Entry<LocalDateTime, Integer> entry = iter.next();
        result.append(entry.getKey(), 0.0);
        int lastIndex = result.size() - 1;
        for (int jj = 0; jj < data.size(); ++jj) {
            result.set(lastIndex, data.get(jj).subList(currentIndex, currentIndex + entry.getValue()).stream()
                    .reduce(identity, accumulator));
        }
        currentIndex += entry.getValue();
        //         result.append(entry.getKey(), 0.0);
        //         int lastIndex = result.size() - 1;
        //         for(int ii = 0; ii < entry.getValue(); ++ii, ++currentIndex) {
        //            for(int jj = 0; jj < data.size(); ++jj) {
        //               result.set(lastIndex, jj, result.get(lastIndex, jj) + get(currentIndex, jj));
        //            }
        //         }
    }

    if (columnNames != null) {
        result.columnNames = new HashMap<String, Integer>(columnNames);
    }

    return result;
}

From source file:net.massbank.validator.RecordValidator.java

/**
 * ???// w  w w  .  ja v a2 s  . c  o m
 * 
 * @param op
 *            PrintWriter?
 * @param resultMap
 *            ??
 * @return ?
 * @throws IOException
 */
private static boolean dispResult(PrintStream op, TreeMap<String, String> resultMap) throws IOException {

    // ----------------------------------------------------
    // 
    // ----------------------------------------------------
    NumberFormat nf = NumberFormat.getNumberInstance();
    int okCnt = 0;
    int warnCnt = 0;
    int errCnt = 0;
    for (Map.Entry<String, String> e : resultMap.entrySet()) {
        String statusStr = e.getValue().split("\t")[0];
        if (statusStr.equals(STATUS_OK)) {
            okCnt++;
        } else if (statusStr.equals(STATUS_WARN)) {
            warnCnt++;
        } else if (statusStr.equals(STATUS_ERR)) {
            errCnt++;
        }
    }
    op.println(nf.format(okCnt) + " ok");
    op.println(nf.format(warnCnt) + " warn");
    op.println(nf.format(errCnt) + " error / " + nf.format(resultMap.size()) + " files");
    op.println("Status");
    op.println("Details");

    // ----------------------------------------------------
    // 
    // ----------------------------------------------------
    for (Map.Entry<String, String> e : resultMap.entrySet()) {
        String nameStr = e.getKey();
        String statusStr = e.getValue().split("\t")[0];
        String detailsStr = e.getValue().split("\t")[1].trim();
        op.println(nameStr + " ");
        op.println(statusStr + "");
        op.println(detailsStr + "");
    }

    return true;
}

From source file:com.gsma.rcs.ri.sharing.SharingListView.java

/**
 * Sets the providers/* ww  w.j ava  2  s .  co m*/
 *
 * @param providers ordered map of providers IDs associated with their name
 */
private void setProviders(TreeMap<Integer, String> providers) {
    mProviderIds = new ArrayList<>();
    mFilterMenuItems = new ArrayList<>();
    for (Entry<Integer, String> entry : providers.entrySet()) {
        mFilterMenuItems.add(entry.getValue());
        mProviderIds.add(entry.getKey());
    }
    /* Upon setting, all providers are checked True */
    mCheckedProviders = new boolean[providers.size()];
    for (int i = 0; i < mCheckedProviders.length; i++) {
        mCheckedProviders[i] = true;
    }
}

From source file:io.smartspaces.activity.impl.BaseActivity.java

/**
 * Log the activity configuration information to an activity config log file.
 *
 * @param logFile//from   ww w. j  a  v  a  2  s.c  o m
 *          file to write the log into
 */
private void logConfiguration(String logFile) {
    try {
        StringBuilder logBuilder = new StringBuilder();
        getLog().info("Logging activity configuration to " + logFile);
        Configuration configuration = getConfiguration();
        Map<String, String> configMap = configuration.getCollapsedMap();
        TreeMap<String, String> sortedMap = new TreeMap<>(configMap);
        for (Map.Entry<String, String> entry : sortedMap.entrySet()) {
            String value;
            try {
                value = configuration.evaluate(entry.getValue());
            } catch (Throwable e) {
                value = e.toString();
            }
            logBuilder.append(String.format("%s=%s\n", entry.getKey(), value));
        }
        File configLog = new File(getActivityFilesystem().getLogDirectory(), logFile);
        fileSupport.writeFile(configLog, logBuilder.toString());
    } catch (Throwable e) {
        logException("While logging activity configuration", e);
    }
}

From source file:org.apache.hama.bsp.sync.ZooKeeperSyncClientImpl.java

@Override
public String[] getAllPeerNames(BSPJobID jobID) {
    if (allPeers == null) {
        TreeMap<Integer, String> sortedMap = new TreeMap<Integer, String>();
        try {/*from   w w w .ja  v a  2s .c  o  m*/
            List<String> var = zk.getChildren(constructKey(jobID, "peers"), this);
            allPeers = var.toArray(new String[var.size()]);

            TreeMap<TaskAttemptID, String> taskAttemptSortedMap = new TreeMap<TaskAttemptID, String>();
            for (String s : allPeers) {
                byte[] data = zk.getData(constructKey(jobID, "peers", s), this, null);
                TaskAttemptID thatTask = new TaskAttemptID();
                boolean result = getValueFromBytes(data, thatTask);

                if (result) {
                    taskAttemptSortedMap.put(thatTask, s);
                }
            }
            for (Map.Entry<TaskAttemptID, String> entry : taskAttemptSortedMap.entrySet()) {
                TaskAttemptID thatTask = entry.getKey();
                String s = entry.getValue();
                LOG.debug("TASK mapping from zookeeper: " + thatTask + " ID:" + thatTask.getTaskID().getId()
                        + " : " + s);
                sortedMap.put(thatTask.getTaskID().getId(), s);
            }
        } catch (Exception e) {
            LOG.error(e);
            throw new RuntimeException("All peer names could not be retrieved!");
        }

        allPeers = new String[sortedMap.size()];
        int count = 0;
        for (Entry<Integer, String> entry : sortedMap.entrySet()) {
            allPeers[count++] = entry.getValue();
            LOG.debug("TASK mapping from zookeeper: " + entry.getKey() + " : " + entry.getValue() + " at index "
                    + (count - 1));
        }

    }
    return allPeers;
}