Example usage for java.util TreeMap get

List of usage examples for java.util TreeMap get

Introduction

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

Prototype

public 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:com.facebook.tsdb.tsdash.server.model.Metric.java

/**
 * create a new metric with rows aggregated after dissolving the given tags.
 * The resulted metric will not be able to accept filters on this tag
 * anymore.//from w ww .  j  a v  a2 s.c o m
 *
 * @param tagName
 * @param aggregatorName
 *            'sum', 'max', 'min' or 'avg'
 * @return a new Metric object that contains the aggregated rows
 * @throws IDNotFoundException
 * @throws IOException
 */
public Metric dissolveTags(ArrayList<String> tagsName, String aggregatorName)
        throws IOException, IDNotFoundException {
    if (tagsName.size() == 0) {
        return this;
    }
    HashMap<String, HashSet<String>> tagsSet = getTagsSet();
    for (String tagName : tagsName) {
        if (!tagsSet.containsKey(tagName)) {
            // TODO: throw an exception here
            logger.error("Dissolve error: tag '" + tagName + "' is not part of the tag set");
            return null;
        }
        // we can only dissolve once a given tag
        if (dissolvedTags.contains(tagName)) {
            // TODO: throw an exception here
            logger.error("Metric already dissolved tag " + tagName);
            return null;
        }
    }
    // this aligns the time series in a perfect grid
    alignAllTimeSeries();

    Metric newData = new Metric(id, name, idMap);
    Tag[] toDissolve = new Tag[tagsName.size()];
    for (int i = 0; i < toDissolve.length; i++) {
        toDissolve[i] = new Tag(tagsName.get(i), idMap);
        newData.dissolvedTags.add(tagsName.get(i));
    }
    TreeMap<TagsArray, ArrayList<ArrayList<DataPoint>>> dissolved = new TreeMap<TagsArray, ArrayList<ArrayList<DataPoint>>>(
            Tag.arrayComparator());
    // sort the tags we will dissolve for calling disableTags()
    Arrays.sort(toDissolve, Tag.keyComparator());
    for (TagsArray header : timeSeries.keySet()) {
        TagsArray dissolvedRowTags = header.copy();
        if (toDissolve.length == 1) {
            dissolvedRowTags.disableTag(toDissolve[0]);
        } else {
            dissolvedRowTags.disableTags(toDissolve);
        }
        if (!dissolved.containsKey(dissolvedRowTags)) {
            dissolved.put(dissolvedRowTags, new ArrayList<ArrayList<DataPoint>>());
        }
        dissolved.get(dissolvedRowTags).add(timeSeries.get(header));
    }
    Aggregator aggregator = getAggregator(aggregatorName);
    newData.aggregatorName = aggregatorName;
    for (TagsArray header : dissolved.keySet()) {
        newData.timeSeries.put(header, TimeSeries.aggregate(dissolved.get(header), aggregator));
    }
    return newData;
}

From source file:com.sfs.whichdoctor.export.writer.ExportWriterBase.java

/**
 * Builds the export table./*  www  .j av  a2  s .  c o m*/
 *
 * @param headings the headings
 * @param values the values
 * @return the string
 */
protected final String buildExportTable(final Collection<String> headings,
        final TreeMap<Integer, Collection<String>> values) {

    final StringBuffer table = new StringBuffer();

    final StringBuffer header = new StringBuffer();

    for (String heading : headings) {
        if (header.length() > 0) {
            header.append(this.getKeys().getString("ITEM_DIVIDER"));
        }

        header.append(this.getKeys().getString("HEADERITEM_PREFIX"));
        header.append(heading);
        header.append(this.getKeys().getString("HEADERITEM_SUFFIX"));
    }
    if (StringUtils.isNotBlank(header.toString())) {
        table.append(this.getKeys().getString("LIST_BEGINNING"));
        table.append(this.getKeys().getString("ROW_BEGINNING"));
        table.append(header.toString());
        table.append(this.getKeys().getString("ROW_END"));
    }

    final StringBuffer content = new StringBuffer();

    for (Integer index : values.keySet()) {
        Collection<String> row = values.get(index);

        content.append(this.getKeys().getString("ROW_BEGINNING"));

        StringBuffer fieldValue = new StringBuffer();

        for (String field : row) {
            if (fieldValue.length() > 0) {
                fieldValue.append(this.getKeys().getString("ITEM_DIVIDER"));
            }
            fieldValue.append(this.getKeys().getString("ITEM_PREFIX"));
            fieldValue.append(field);
            fieldValue.append(this.getKeys().getString("ITEM_SUFFIX"));
        }
        content.append(fieldValue.toString());

        content.append(this.getKeys().getString("ROW_END"));
    }

    if (StringUtils.isNotBlank(content.toString())) {
        table.append(content.toString());
    }
    if (StringUtils.isNotBlank(header.toString())) {
        table.append(this.getKeys().getString("LIST_END"));
    }
    return table.toString();
}

From source file:com.cloud.upgrade.DatabaseUpgradeChecker.java

protected void upgrade(CloudStackVersion dbVersion, CloudStackVersion currentVersion) {
    s_logger.info("Database upgrade must be performed from " + dbVersion + " to " + currentVersion);

    final DbUpgrade[] upgrades = calculateUpgradePath(dbVersion, currentVersion);

    boolean supportsRollingUpgrade = true;
    for (DbUpgrade upgrade : upgrades) {
        if (!upgrade.supportsRollingUpgrade()) {
            supportsRollingUpgrade = false;
            break;
        }// w w  w  . j  ava2s  .  c  om
    }

    if (!supportsRollingUpgrade && false) { // FIXME: Needs to detect if there are management servers running
        // ClusterManagerImpl.arePeersRunning(null)) {
        String errorMessage = "Unable to run upgrade because the upgrade sequence does not support rolling update and there are other management server nodes running";
        s_logger.error(errorMessage);
        throw new CloudRuntimeException(errorMessage);
    }

    for (DbUpgrade upgrade : upgrades) {
        s_logger.debug("Running upgrade " + upgrade.getClass().getSimpleName() + " to upgrade from "
                + upgrade.getUpgradableVersionRange()[0] + "-" + upgrade.getUpgradableVersionRange()[1] + " to "
                + upgrade.getUpgradedVersion());
        TransactionLegacy txn = TransactionLegacy.open("Upgrade");
        txn.start();
        try {
            Connection conn;
            try {
                conn = txn.getConnection();
            } catch (SQLException e) {
                String errorMessage = "Unable to upgrade the database";
                s_logger.error(errorMessage, e);
                throw new CloudRuntimeException(errorMessage, e);
            }
            File[] scripts = upgrade.getPrepareScripts();
            if (scripts != null) {
                for (File script : scripts) {
                    runScript(conn, script);
                }
            }

            upgrade.performDataMigration(conn);
            boolean upgradeVersion = true;

            if (upgrade.getUpgradedVersion().equals("2.1.8")) {
                // we don't have VersionDao in 2.1.x
                upgradeVersion = false;
            } else if (upgrade.getUpgradedVersion().equals("2.2.4")) {
                try (PreparedStatement pstmt = conn
                        .prepareStatement("SELECT * FROM version WHERE version='2.2.4'");
                        ResultSet rs = pstmt.executeQuery();) {
                    // specifically for domain vlan update from 2.1.8 to 2.2.4
                    if (rs.next()) {
                        upgradeVersion = false;
                    }
                } catch (SQLException e) {
                    throw new CloudRuntimeException("Unable to update the version table", e);
                }
            }

            if (upgradeVersion) {
                VersionVO version = new VersionVO(upgrade.getUpgradedVersion());
                _dao.persist(version);
            }

            txn.commit();
        } catch (CloudRuntimeException e) {
            String errorMessage = "Unable to upgrade the database";
            s_logger.error(errorMessage, e);
            throw new CloudRuntimeException(errorMessage, e);
        } finally {
            txn.close();
        }
    }

    if (true) { // FIXME Needs to detect if management servers are running
        // !ClusterManagerImpl.arePeersRunning(trimmedCurrentVersion)) {
        s_logger.info("Cleaning upgrades because all management server are now at the same version");
        TreeMap<String, List<DbUpgrade>> upgradedVersions = new TreeMap<String, List<DbUpgrade>>();

        for (DbUpgrade upgrade : upgrades) {
            String upgradedVerson = upgrade.getUpgradedVersion();
            List<DbUpgrade> upgradeList = upgradedVersions.get(upgradedVerson);
            if (upgradeList == null) {
                upgradeList = new ArrayList<DbUpgrade>();
            }
            upgradeList.add(upgrade);
            upgradedVersions.put(upgradedVerson, upgradeList);
        }

        for (String upgradedVersion : upgradedVersions.keySet()) {
            List<DbUpgrade> versionUpgrades = upgradedVersions.get(upgradedVersion);
            VersionVO version = _dao.findByVersion(upgradedVersion, Step.Upgrade);
            s_logger.debug("Upgrading to version " + upgradedVersion + "...");

            TransactionLegacy txn = TransactionLegacy.open("Cleanup");
            try {
                if (version != null) {
                    for (DbUpgrade upgrade : versionUpgrades) {
                        s_logger.info("Cleanup upgrade " + upgrade.getClass().getSimpleName()
                                + " to upgrade from " + upgrade.getUpgradableVersionRange()[0] + "-"
                                + upgrade.getUpgradableVersionRange()[1] + " to "
                                + upgrade.getUpgradedVersion());

                        txn.start();

                        Connection conn;
                        try {
                            conn = txn.getConnection();
                        } catch (SQLException e) {
                            String errorMessage = "Unable to cleanup the database";
                            s_logger.error(errorMessage, e);
                            throw new CloudRuntimeException(errorMessage, e);
                        }

                        File[] scripts = upgrade.getCleanupScripts();
                        if (scripts != null) {
                            for (File script : scripts) {
                                runScript(conn, script);
                                s_logger.debug("Cleanup script " + script.getAbsolutePath()
                                        + " is executed successfully");
                            }
                        }
                        txn.commit();
                    }

                    txn.start();
                    version.setStep(Step.Complete);
                    s_logger.debug("Upgrade completed for version " + upgradedVersion);
                    version.setUpdated(new Date());
                    _dao.update(version.getId(), version);
                    txn.commit();
                }
            } finally {
                txn.close();
            }
        }
    }

}

From source file:it.polito.tellmefirst.web.rest.clients.ClientEpub.java

public ArrayList<ClassifyOutput> sortByRank(HashMap<ClassifyOutput, Integer> inputList) {

    LOG.debug("[sortByRank] - BEGIN");

    ArrayList<ClassifyOutput> result = new ArrayList<>();
    LinkedMap apacheMap = new LinkedMap(inputList);
    for (int i = 0; i < apacheMap.size() - 1; i++) {
        TreeMap<Float, ClassifyOutput> treeMap = new TreeMap<>(Collections.reverseOrder());
        do {/*w w  w  .j  av  a 2 s .c o  m*/
            i++;
            treeMap.put(Float.valueOf(((ClassifyOutput) apacheMap.get(i - 1)).getScore()),
                    (ClassifyOutput) apacheMap.get(i - 1));
        } while (i < apacheMap.size() && apacheMap.getValue(i) == apacheMap.getValue(i - 1));
        i--;
        for (Float score : treeMap.keySet()) {
            result.add(treeMap.get(score));
        }
    }

    LOG.debug("[sortByRank] - END");
    return result;
}

From source file:com.netflix.ice.processor.BillingFileProcessor.java

private void sendOndemandCostAlert() {

    if (ondemandThreshold == null || StringUtils.isEmpty(fromEmail) || StringUtils.isEmpty(alertEmails)
            || endMilli < lastAlertMillis() + AwsUtils.hourMillis * 24)
        return;/* ww w.  j  a  v a 2  s.  co  m*/

    Map<Long, Map<Ec2InstanceReservationPrice.Key, Double>> ondemandCosts = getOndemandCosts(
            lastAlertMillis() + AwsUtils.hourMillis);
    Long maxHour = null;
    double maxTotal = ondemandThreshold;

    for (Long hour : ondemandCosts.keySet()) {
        double total = 0;
        for (Double value : ondemandCosts.get(hour).values())
            total += value;

        if (total > maxTotal) {
            maxHour = hour;
            maxTotal = total;
        }
    }

    if (maxHour != null) {
        NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.US);
        String subject = String.format("Alert: Ondemand cost per hour reached $%s at %s",
                numberFormat.format(maxTotal), AwsUtils.dateFormatter.print(maxHour));
        StringBuilder body = new StringBuilder();
        body.append(String.format("Total ondemand cost $%s at %s:<br><br>", numberFormat.format(maxTotal),
                AwsUtils.dateFormatter.print(maxHour)));
        TreeMap<Double, String> costs = Maps.newTreeMap();
        for (Map.Entry<Ec2InstanceReservationPrice.Key, Double> entry : ondemandCosts.get(maxHour).entrySet()) {
            costs.put(entry.getValue(), entry.getKey().region + " " + entry.getKey().usageType + ": ");
        }
        for (Double cost : costs.descendingKeySet()) {
            if (cost > 0)
                body.append(costs.get(cost)).append("$" + numberFormat.format(cost)).append("<br>");
        }
        body.append("<br>Please go to <a href=\"" + urlPrefix
                + "dashboard/reservation#usage_cost=cost&groupBy=UsageType&product=ec2_instance&operation=OndemandInstances\">Ice</a> for details.");
        SendEmailRequest request = new SendEmailRequest();
        request.withSource(fromEmail);
        List<String> emails = Lists.newArrayList(alertEmails.split(","));
        request.withDestination(new Destination(emails));
        request.withMessage(
                new Message(new Content(subject), new Body().withHtml(new Content(body.toString()))));

        AmazonSimpleEmailServiceClient emailService = AwsUtils.getAmazonSimpleEmailServiceClient();
        try {
            emailService.sendEmail(request);
            updateLastAlertMillis(endMilli);
            logger.info("updateLastAlertMillis " + endMilli);
        } catch (Exception e) {
            logger.error("Error in sending alert emails", e);
        }
    }
}

From source file:org.alfresco.bm.report.AbstractEventReporter.java

protected TreeMap<String, ResultSummary> collateResults(boolean chartOnly) {
    ResultService resultService = getResultService();
    // Do a quick check to see if there are results
    EventRecord firstEvent = resultService.getFirstResult();
    if (firstEvent == null) {
        return new TreeMap<String, ResultSummary>();
    }/*from  w  w w  .  ja v a2s.  co m*/
    EventRecord lastEvent = resultService.getLastResult();

    long oneHour = TimeUnit.HOURS.toMillis(1L);
    long queryWindowStartTime = firstEvent.getStartTime();
    long queryWindowEndTime = queryWindowStartTime + oneHour;

    // Prepare recorded data
    TreeMap<String, ResultSummary> results = new TreeMap<String, ResultSummary>();
    int limit = 10000;
    int skip = 0;

    while (true) {
        List<EventRecord> data = resultService.getResults(queryWindowStartTime, queryWindowEndTime, chartOnly,
                skip, limit);
        if (data.size() == 0) {
            if (queryWindowEndTime > lastEvent.getStartTime()) {
                // The query window covered all known events, so we're done
                break;
            } else {
                // Push the window up
                queryWindowStartTime = queryWindowEndTime;
                queryWindowEndTime += oneHour;
                skip = 0;
                // Requery
                continue;
            }
        }
        for (EventRecord eventRecord : data) {
            skip++;
            // Add the data
            String eventName = eventRecord.getEvent().getName();
            ResultSummary resultSummary = results.get(eventName);
            if (resultSummary == null) {
                resultSummary = new ResultSummary(eventName);
                results.put(eventName, resultSummary);
            }
            boolean resultSuccess = eventRecord.isSuccess();
            long resultTime = eventRecord.getTime();
            resultSummary.addSample(resultSuccess, resultTime);
        }
    }
    // Done
    return results;
}

From source file:edu.mit.mobile.android.appupdater.AppUpdateChecker.java

@SuppressWarnings("unchecked")
private void triggerFromJson(JSONObject jo) throws JSONException {

    final ArrayList<String> changelog = new ArrayList<String>();

    // keep a sorted map of versionCode to the version information objects.
    // Most recent is at the top.
    final TreeMap<Integer, JSONObject> versionMap = new TreeMap<Integer, JSONObject>(new Comparator<Integer>() {
        public int compare(Integer object1, Integer object2) {
            return object2.compareTo(object1);
        };//  ww  w. ja  v a  2  s . co m
    });

    for (final Iterator<String> i = jo.keys(); i.hasNext();) {
        final String versionName = i.next();
        if (versionName.equals("package")) {
            pkgInfo = jo.getJSONObject(versionName);
            continue;
        }
        final JSONObject versionInfo = jo.getJSONObject(versionName);
        versionInfo.put("versionName", versionName);

        final int versionCode = versionInfo.getInt("versionCode");
        versionMap.put(versionCode, versionInfo);
    }
    final int latestVersionNumber = versionMap.firstKey();
    final String latestVersionName = versionMap.get(latestVersionNumber).getString("versionName");
    final Uri downloadUri = Uri.parse(pkgInfo.getString("downloadUrl"));

    if (currentAppVersion > latestVersionNumber) {
        Log.d(TAG, "We're newer than the latest published version (" + latestVersionName
                + "). Living in the future...");
        mUpdateListener.appUpdateStatus(true, latestVersionName, null, downloadUri);
        return;
    }

    if (currentAppVersion == latestVersionNumber) {
        Log.d(TAG, "We're at the latest version (" + currentAppVersion + ")");
        mUpdateListener.appUpdateStatus(true, latestVersionName, null, downloadUri);
        return;
    }

    // construct the changelog. Newest entries are at the top.
    for (final Entry<Integer, JSONObject> version : versionMap.headMap(currentAppVersion).entrySet()) {
        final JSONObject versionInfo = version.getValue();
        final JSONArray versionChangelog = versionInfo.optJSONArray("changelog");
        if (versionChangelog != null) {
            final int len = versionChangelog.length();
            for (int i = 0; i < len; i++) {
                changelog.add(versionChangelog.getString(i));
            }
        }
    }

    mUpdateListener.appUpdateStatus(false, latestVersionName, changelog, downloadUri);
}

From source file:hoot.services.command.CommandRunner.java

private void logExec(String pCmdString, Map<String, String> unsortedEnv) {

    if (_log.isInfoEnabled()) {

        TreeMap<String, String> env = new TreeMap<String, String>();
        env.putAll(unsortedEnv);/*w ww .j  av  a 2  s  . co  m*/

        _log.info("Executing '" + pCmdString + "'");
        _log.info("Enviroment:");
        FileWriter writer = null;
        try {
            if (_log.isDebugEnabled()) {
                File envvarFile = File.createTempFile("envvars", ".txt");
                writer = new FileWriter(envvarFile);
                _log.debug("ENVVARS will be written to " + envvarFile.getAbsolutePath());
            }
            for (String key : env.keySet()) {
                _log.info(String.format("  %s", new Object[] { key + "=" + env.get(key) }));
                if (_log.isDebugEnabled())
                    writer.write(String.format("  %s%n", new Object[] { key + "=" + env.get(key) }));
            }
            if (_log.isDebugEnabled())
                writer.close();
        } catch (Exception e) {
            _log.error("Unable to log exec call: " + ExceptionUtils.getStackTrace(e));
        }
    }
}

From source file:org.egov.ptis.web.controller.rest.AssessmentServiceController.java

/**
 * This method is used to get all list of floor numbers.
 * @return responseJson - server response in JSON format
 * @throws IOException/*www .  j a va 2  s .co  m*/
 */
@RequestMapping(value = "/property/floors", produces = APPLICATION_JSON_VALUE)
public String getFloors() throws IOException {
    List<MasterCodeNamePairDetails> mstrCodeNamePairDetailsList = new ArrayList<>();
    ErrorDetails errorDetails = null;
    String responseJson = null;
    //Boolean isAuthenticatedUser = propertyExternalService.authenticateUser(username, password);
    Boolean isAuthenticatedUser = true;
    if (isAuthenticatedUser) {
        TreeMap<Integer, String> floorMap = PropertyTaxConstants.FLOOR_MAP;

        Set<Integer> keys = floorMap.keySet();
        for (Integer key : keys) {
            MasterCodeNamePairDetails mstrCodeNamePairDetails = new MasterCodeNamePairDetails();
            mstrCodeNamePairDetails.setCode(key.toString());
            mstrCodeNamePairDetails.setName(floorMap.get(key));
            mstrCodeNamePairDetailsList.add(mstrCodeNamePairDetails);
        }
        responseJson = getJSONResponse(mstrCodeNamePairDetailsList);
    } else {
        errorDetails = getInvalidCredentialsErrorDetails();
        responseJson = getJSONResponse(errorDetails);
    }
    return responseJson;
}

From source file:ca.sqlpower.architect.ddl.TypeMap.java

/**
 * /*  w w w.ja  v  a 2s .  c om*/
 * only create new database and native type entries when createNew is true.
 * this prevents bogus map entries from being created when doing lookups.
 *
 * notice that a SQLColumn is not passed in, so the rules list is not
 * cut down to size.  
 * 
 * @see getRules for the method which determines which rules are in effect
 *  
 * @param database
 * @param nativeType
 * @param createNew
 * @return
 */
protected List getRulesForNativeType(String database, String nativeType, boolean createNew) {
    TreeMap nativeTypes = null;
    String tDatabase = translateDatabaseName(database);
    if (!databases.containsKey(tDatabase)) {
        if (createNew) {
            nativeTypes = new TreeMap();
            databases.put(tDatabase, nativeTypes);
        } else {
            return EMPTY_LIST; // empty list
        }
    } else {
        nativeTypes = (TreeMap) databases.get(tDatabase);
    }

    ArrayList mappingRules = null;
    if (!nativeTypes.containsKey(nativeType)) {
        if (createNew) {
            mappingRules = new ArrayList();
            nativeTypes.put(nativeType, mappingRules);
        } else {
            return EMPTY_LIST; // empty list
        }
    } else {
        mappingRules = (ArrayList) nativeTypes.get(nativeType);
    }
    return mappingRules;
}