Example usage for java.util SortedMap entrySet

List of usage examples for java.util SortedMap entrySet

Introduction

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

Prototype

Set<Map.Entry<K, V>> entrySet();

Source Link

Document

Returns a Set view of the mappings contained in this map.

Usage

From source file:se.jguru.nazgul.tools.codestyle.enforcer.rules.CorrectPackagingRule.java

/**
 * Delegate method, implemented by concrete subclasses.
 *
 * @param project The active MavenProject.
 * @param helper  The EnforcerRuleHelper instance, from which the MavenProject has been retrieved.
 * @throws RuleFailureException If the enforcer rule was not satisfied.
 */// ww w. j  a  v a2  s .  co  m
@Override
@SuppressWarnings("unchecked")
protected void performValidation(final MavenProject project, final EnforcerRuleHelper helper)
        throws RuleFailureException {

    // Find all java source files, and map their packages to their names.
    final List<String> compileSourceRoots = (List<String>) project.getCompileSourceRoots();
    if (compileSourceRoots.size() == 0) {
        return;
    }

    final SortedMap<String, SortedSet<String>> packageName2SourceFileNameMap = new TreeMap<String, SortedSet<String>>();

    for (String current : compileSourceRoots) {
        addPackages(new File(current), packageName2SourceFileNameMap);
    }

    // Retrieve the groupId of this project
    final String groupId = project.getGroupId();
    if (groupId == null || groupId.equals("")) {

        // Don't accept empty groupIds
        throw new RuleFailureException("Maven groupId cannot be null or empty.", project.getArtifact());

    } else {

        // Correct packaging everywhere?
        final SortedSet<String> incorrectPackages = new TreeSet<String>();
        for (Map.Entry<String, SortedSet<String>> currentPackage : packageName2SourceFileNameMap.entrySet()) {

            final String candidate = currentPackage.getKey();
            if (!candidate.startsWith(groupId)) {
                incorrectPackages.add(candidate);
            }
        }

        if (incorrectPackages.size() > 0) {

            final SortedMap<String, SortedSet<String>> result = new TreeMap<String, SortedSet<String>>();
            for (String current : incorrectPackages) {
                result.put(current, packageName2SourceFileNameMap.get(current));
            }

            throw new RuleFailureException("Incorrect packaging detected; required [" + groupId
                    + "] but found package to file names: " + result, project.getArtifact());
        }
    }
}

From source file:com.jlhood.metrics.CloudWatchReporter.java

/**
 * Reports the given metrics to CloudWatch.
 *
 * @param gauges     gauge metrics.//  w  w  w.jav  a 2s  .c  o m
 * @param counters   counter metrics.
 * @param histograms histogram metrics.
 * @param meters     meter metrics.
 * @param timers     timer metrics.
 */
void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters,
        SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters,
        SortedMap<String, Timer> timers) {

    // Just an estimate to reduce resizing.
    List<MetricDatum> data = new ArrayList<MetricDatum>(
            gauges.size() + counters.size() + meters.size() + 2 * histograms.size() + 2 * timers.size());

    // Translate various metric classes to MetricDatum
    for (Map.Entry<String, Gauge> gaugeEntry : gauges.entrySet()) {
        reportGauge(gaugeEntry, typeDimValGauge, data);
    }
    for (Map.Entry<String, Counter> counterEntry : counters.entrySet()) {
        reportCounter(counterEntry, typeDimValCounterCount, data);
    }
    for (Map.Entry<String, Meter> meterEntry : meters.entrySet()) {
        reportCounter(meterEntry, typeDimValMeterCount, data);
    }
    for (Map.Entry<String, Histogram> histogramEntry : histograms.entrySet()) {
        reportCounter(histogramEntry, typeDimValHistoSamples, data);
        reportSampling(histogramEntry, typeDimValHistoStats, 1.0, data);
    }
    for (Map.Entry<String, Timer> timerEntry : timers.entrySet()) {
        reportCounter(timerEntry, typeDimValTimerSamples, data);
        reportSampling(timerEntry, typeDimValTimerStats, 0.000001, data); // nanos -> millis
    }

    // Filter out unreportable entries.
    Collection<MetricDatum> nonEmptyData = Collections2.filter(data, new Predicate<MetricDatum>() {
        @Override
        public boolean apply(MetricDatum input) {
            if (input == null) {
                return false;
            } else if (input.getStatisticValues() != null) {
                // CloudWatch rejects any Statistic Sets with sample count == 0, which it probably should reject.
                return input.getStatisticValues().getSampleCount() > 0;
            }
            return true;
        }
    });

    // Whether to use local "now" (true, new Date()) or cloudwatch service "now" (false, leave null).
    if (timestampLocal) {
        Date now = new Date();
        for (MetricDatum datum : nonEmptyData) {
            datum.withTimestamp(now);
        }
    }

    // Finally, apply any user-level filter.
    Collection<MetricDatum> filtered = Collections2.filter(nonEmptyData, reporterFilter);

    // Each CloudWatch API request may contain at maximum 20 datums. Break into partitions of 20.
    Iterable<List<MetricDatum>> dataPartitions = Iterables.partition(filtered, 20);
    List<Future<?>> cloudWatchFutures = Lists.newArrayListWithExpectedSize(filtered.size());

    // Submit asynchronously with threads.
    for (List<MetricDatum> dataSubset : dataPartitions) {
        cloudWatchFutures.add(cloudWatch.putMetricDataAsync(
                new PutMetricDataRequest().withNamespace(metricNamespace).withMetricData(dataSubset)));
    }

    // Wait for CloudWatch putMetricData futures to be fulfilled.
    for (Future<?> cloudWatchFuture : cloudWatchFutures) {
        try {
            cloudWatchFuture.get();
        } catch (Exception e) {
            LOG.error(
                    "Exception reporting metrics to CloudWatch. Some or all of the data in this CloudWatch API request "
                            + "may have been discarded, did not make it to CloudWatch.",
                    e);
        }
    }

    LOG.debug("Sent {} metric data to CloudWatch. namespace: {}", filtered.size(), metricNamespace);
}

From source file:org.directwebremoting.servlet.MonitorHandler.java

public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {
    if (!debug) {
        log.warn(//w w w  .j  a  va2  s  .c o m
                "Failed attempt to access test pages outside of debug mode. Set the debug init-parameter to true to enable.");
        throw new SecurityException("Access to debug pages is denied.");
    }

    response.setContentType(MimeConstants.MIME_HTML);
    PrintWriter out = response.getWriter();
    out.print("<html><head><title>DWR - System Monitor</title></head><body>");

    WebContext webContext = WebContextFactory.get();

    out.print("<h1>DWR - System Monitor</h1>");
    out.print("<h2>Global Settings:</h2>");

    String contextPath = webContext.getContextPath();
    out.print("<p>ContextPath: " + contextPath + "</p>");
    out.print("<p>Current Page: " + webContext.getCurrentPage() + "</p>");

    //ScriptSession scriptSession = webContext.getScriptSession();

    Container container = webContext.getContainer();
    SortedMap<String, Object> beans = new TreeMap<String, Object>();
    SortedMap<String, String> settings = new TreeMap<String, String>();
    SortedMap<String, String> urls = new TreeMap<String, String>();
    for (String name : container.getBeanNames()) {
        Object bean = container.getBean(name);
        if (name.startsWith("url:")) {
            urls.put(name.substring(4), bean.getClass().getName());
        } else if (bean instanceof String) {
            settings.put(name, bean.toString());
        } else {
            beans.put(name, bean);
        }
    }

    // Add all the beans to an ID map for <a name=ID>
    IdManager ids = new IdManager();

    // Remove the URL re-writers from the Settings map
    for (Map.Entry<String, String> urlEntry : urls.entrySet()) {
        for (Iterator<Map.Entry<String, String>> it = settings.entrySet().iterator(); it.hasNext();) {
            Map.Entry<String, String> settingEntry = it.next();
            if (urlEntry.getKey().equals(settingEntry.getValue())) {
                it.remove();
                urls.put(urlEntry.getKey(), urlEntry.getValue() + " (" + settingEntry.getKey() + ")");
            }
        }
    }

    out.print("<h2>Beans:</h2>");
    for (Map.Entry<String, Object> entry : beans.entrySet()) {
        String name = entry.getKey();
        Object object = entry.getValue();

        digWhatever(out, ids, name, object);
    }

    out.print("<h2>Settings:</h2>");
    for (Map.Entry<String, String> entry : settings.entrySet()) {
        out.print("<p>" + entry.getKey() + ": \"" + entry.getValue() + "\"</p>");
    }

    out.print("<h2>URLs:</h2>");
    String prefix = contextPath + webContext.getHttpServletRequest().getServletPath();
    for (Map.Entry<String, String> entry : urls.entrySet()) {
        out.print("<p><a href='" + prefix + entry.getKey() + "'>" + entry.getKey() + "</a>: " + entry.getValue()
                + "</p>");
    }

    webContext.getContextPath();
    out.print("</body></html>");
}

From source file:org.jasig.schedassist.model.VisibleScheduleBuilderTest.java

/**
 * Verify that start and end times of blocks stay consistent for calculateVisibleSchedule.
 * //from w  ww .  j  av a 2  s .c  om
 * @throws Exception
 */
@Test
public void testOffsetStart() throws Exception {
    Set<AvailableBlock> blocks = AvailableBlockBuilder.createBlocks("9:00 AM", "1:00 PM", "MWF",
            makeDateTime("20090720-0000"), makeDateTime("20090725-0000"), 1, null);

    TreeSet<AvailableBlock> expanded = new TreeSet<AvailableBlock>(AvailableBlockBuilder.expand(blocks, 30));
    Assert.assertEquals(makeDateTime("20090720-0900"), expanded.first().getStartTime());
    Assert.assertEquals(makeDateTime("20090720-0930"), expanded.first().getEndTime());
    Assert.assertEquals(makeDateTime("20090724-1230"), expanded.last().getStartTime());
    Assert.assertEquals(makeDateTime("20090724-1300"), expanded.last().getEndTime());
    AvailableSchedule schedule = new AvailableSchedule(expanded);

    Calendar emptyCalendar = new Calendar();

    MockScheduleOwner owner = new MockScheduleOwner(new MockCalendarAccount(), 1);
    owner.setPreference(Preferences.DURATIONS, MeetingDurations.THIRTY.getKey());
    VisibleSchedule control = this.builder.calculateVisibleSchedule(makeDateTime("20090719-0000"),
            makeDateTime("20090726-0000"), emptyCalendar, schedule, owner);
    Assert.assertEquals(24, control.getFreeCount());
    // verify that all the free blocks start on the half hour
    SortedMap<AvailableBlock, AvailableStatus> blockMap = control.getBlockMap();
    for (Entry<AvailableBlock, AvailableStatus> entry : blockMap.entrySet()) {
        if (AvailableStatus.FREE.equals(entry.getValue())) {
            AvailableBlock freeBlock = entry.getKey();
            java.util.Calendar startTimeCal = java.util.Calendar.getInstance();
            startTimeCal.setTime(freeBlock.getStartTime());
            Assert.assertTrue(startTimeCal.get(java.util.Calendar.MINUTE) % 30 == 0);
            java.util.Calendar endTimeCal = java.util.Calendar.getInstance();
            endTimeCal.setTime(freeBlock.getEndTime());
            Assert.assertTrue(endTimeCal.get(java.util.Calendar.MINUTE) % 30 == 0);
        }
    }

    // now start the offset in between a block
    VisibleSchedule startsInBlock = this.builder.calculateVisibleSchedule(makeDateTime("20090720-1005"),
            makeDateTime("20090727-1005"), emptyCalendar, schedule, owner);
    Assert.assertEquals(21, startsInBlock.getFreeCount());
    // verify that all the free blocks start on the half hour
    SortedMap<AvailableBlock, AvailableStatus> blockMap2 = startsInBlock.getBlockMap();
    for (Entry<AvailableBlock, AvailableStatus> entry : blockMap2.entrySet()) {
        if (AvailableStatus.FREE.equals(entry.getValue())) {
            AvailableBlock freeBlock = entry.getKey();
            java.util.Calendar startTimeCal = java.util.Calendar.getInstance();
            startTimeCal.setTime(freeBlock.getStartTime());
            Assert.assertTrue(startTimeCal.get(java.util.Calendar.MINUTE) % 30 == 0);
            java.util.Calendar endTimeCal = java.util.Calendar.getInstance();
            endTimeCal.setTime(freeBlock.getEndTime());
            Assert.assertTrue(endTimeCal.get(java.util.Calendar.MINUTE) % 30 == 0);
        }
    }
}

From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step11GoldDataStatistics.java

/**
 * (1) Plain text with 4 columns: (1) the rank of the document in the list
 * (2) average agreement rate over queries (3) standard deviation of
 * agreement rate over queries. (4) average length of the document in the
 * rank./*from ww  w .  j  av  a2 s  .  c o m*/
 */
public static void statistics1(File inputDir, File outputDir) throws Exception {
    SortedMap<Integer, DescriptiveStatistics> mapDocumentRankObservedAgreement = new TreeMap<>();
    SortedMap<Integer, DescriptiveStatistics> mapDocumentRankDocLength = new TreeMap<>();

    // iterate over query containers
    for (File f : FileUtils.listFiles(inputDir, new String[] { "xml" }, false)) {
        QueryResultContainer queryResultContainer = QueryResultContainer
                .fromXML(FileUtils.readFileToString(f, "utf-8"));

        for (QueryResultContainer.SingleRankedResult rankedResult : queryResultContainer.rankedResults) {
            // add new entries
            if (!mapDocumentRankObservedAgreement.containsKey(rankedResult.rank)) {
                mapDocumentRankObservedAgreement.put(rankedResult.rank, new DescriptiveStatistics());
            }
            if (!mapDocumentRankDocLength.containsKey(rankedResult.rank)) {
                mapDocumentRankDocLength.put(rankedResult.rank, new DescriptiveStatistics());
            }

            Double observedAgreement = rankedResult.observedAgreement;

            if (observedAgreement == null) {
                System.err
                        .println("Observed agreement is null; " + f.getName() + ", " + rankedResult.clueWebID);
            } else {
                // update value
                mapDocumentRankObservedAgreement.get(rankedResult.rank).addValue(observedAgreement);
                mapDocumentRankDocLength.get(rankedResult.rank).addValue(rankedResult.plainText.length());
            }
        }
    }

    PrintWriter pw = new PrintWriter(new FileWriter(new File(outputDir, "stats1.csv")));
    for (Map.Entry<Integer, DescriptiveStatistics> entry : mapDocumentRankObservedAgreement.entrySet()) {
        pw.printf(Locale.ENGLISH, "%d\t%.4f\t%.4f\t%.4f\t%.4f%n", entry.getKey(), entry.getValue().getMean(),
                entry.getValue().getStandardDeviation(), mapDocumentRankDocLength.get(entry.getKey()).getMean(),
                mapDocumentRankDocLength.get(entry.getKey()).getStandardDeviation());
    }
    pw.close();
}

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

/**
 * @see java.util.Set#equals(java.lang.Object)
 *///from  ww w . jav a  2s.c o m
public boolean equals(Object o) {
    if (this == o) {
        return true;
    } else if (o instanceof Range) {
        SortedMap oSpans = ((Range) o).spans;
        if (oSpans.size() != spans.size()) {
            return false;
        } else {
            Iterator myIter = spans.entrySet().iterator();
            Iterator oIter = oSpans.entrySet().iterator();
            while (myIter.hasNext()) {
                if (!myIter.next().equals(oIter.next())) {
                    return false;
                }
            }
            return true;
        }
    } else {
        return false;
    }
}

From source file:io.anserini.search.SearchCollection.java

@SuppressWarnings("unchecked")
public <K> int runTopics() throws IOException {
    IndexSearcher searcher = new IndexSearcher(reader);
    searcher.setSimilarity(similarity);//from   w ww.j  av a 2 s  . co m

    Path topicsFile = Paths.get(args.topics);

    if (!Files.exists(topicsFile) || !Files.isRegularFile(topicsFile) || !Files.isReadable(topicsFile)) {
        throw new IllegalArgumentException(
                "Topics file : " + topicsFile + " does not exist or is not a (readable) file.");
    }

    TopicReader<K> tr;
    SortedMap<K, Map<String, String>> topics;
    try {
        tr = (TopicReader<K>) Class.forName("io.anserini.search.query." + args.topicReader + "TopicReader")
                .getConstructor(Path.class).newInstance(topicsFile);
        topics = tr.read();
    } catch (Exception e) {
        throw new IllegalArgumentException("Unable to load topic reader: " + args.topicReader);
    }

    final String runTag = "Anserini_" + args.topicfield + "_" + (args.keepstop ? "KeepStopwords_" : "")
            + FIELD_BODY + "_" + (args.searchtweets ? "SearchTweets_" : "") + similarity.toString();

    PrintWriter out = new PrintWriter(
            Files.newBufferedWriter(Paths.get(args.output), StandardCharsets.US_ASCII));

    for (Map.Entry<K, Map<String, String>> entry : topics.entrySet()) {
        K qid = entry.getKey();
        String queryString = entry.getValue().get(args.topicfield);

        ScoredDocuments docs;
        if (args.searchtweets) {
            docs = searchTweets(searcher, qid, queryString, Long.parseLong(entry.getValue().get("time")));
        } else {
            docs = search(searcher, qid, queryString);
        }

        /**
         * the first column is the topic number.
         * the second column is currently unused and should always be "Q0".
         * the third column is the official document identifier of the retrieved document.
         * the fourth column is the rank the document is retrieved.
         * the fifth column shows the score (integer or floating point) that generated the ranking.
         * the sixth column is called the "run tag" and should be a unique identifier for your
         */
        for (int i = 0; i < docs.documents.length; i++) {
            out.println(String.format(Locale.US, "%s Q0 %s %d %f %s", qid,
                    docs.documents[i].getField(FIELD_ID).stringValue(), (i + 1), docs.scores[i],
                    ((i == 0 || i == docs.documents.length - 1) ? runTag : "See_Line1")));
        }
    }
    out.flush();
    out.close();

    return topics.size();
}

From source file:com.aurel.track.report.dashboard.AverageTimeToCloseItem.java

private String convertResultMapToJSONData(SortedMap<Date, EarnedValueTimeSlice> earnedValueTimeSliceMap,
        Double maxValPlanned, Double maxEarned, int reportingInterval, int effortType) {
    StringBuilder local = new StringBuilder();
    local.append("[");
    for (Map.Entry<Date, EarnedValueTimeSlice> entry : earnedValueTimeSliceMap.entrySet()) {
        local.append("{");
        JSONUtility.appendStringValue(local, "date",
                getDateBasedOnReportInterval(entry.getKey(), reportingInterval));
        Double plannedVal = entry.getValue().getPlannedValue();
        if (effortType == EFFORT_TYPE.TIME) {
            plannedVal = maxValPlanned - entry.getValue().getPlannedValue();
        }// w w w . j av a 2  s. co m
        JSONUtility.appendDoubleValue(local, "plannedValue", plannedVal);
        Double earnValue = 0.0;
        if (entry.getValue().getEarnedvalue() != null) {
            earnValue = entry.getValue().getEarnedvalue();

        }
        if (effortType == EFFORT_TYPE.TIME) {
            earnValue = maxEarned - earnValue;
        }
        JSONUtility.appendDoubleValue(local, "earnedValue", earnValue, true);
        local.append("},");
    }
    if (local != null && local.length() > 0) {
        if (local.toString().endsWith(",")) {
            local = new StringBuilder(local.substring(0, local.length() - 1));
        }
    }
    local.append("]");
    return local.toString();
}

From source file:nz.net.catalyst.MaharaDroid.upload.http.RestClient.java

public static JSONObject CallFunction(String url, String[] paramNames, String[] paramVals, Context context) {
    JSONObject json = new JSONObject();

    SchemeRegistry supportedSchemes = new SchemeRegistry();

    SSLSocketFactory sf = getSocketFactory(DEBUG);

    // TODO we make assumptions about ports.
    supportedSchemes.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    supportedSchemes.register(new Scheme("https", sf, 443));

    HttpParams http_params = new BasicHttpParams();
    ClientConnectionManager ccm = new ThreadSafeClientConnManager(http_params, supportedSchemes);

    // HttpParams http_params = httpclient.getParams();
    http_params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpConnectionParams.setConnectionTimeout(http_params, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(http_params, CONNECTION_TIMEOUT);

    DefaultHttpClient httpclient = new DefaultHttpClient(ccm, http_params);

    if (paramNames == null) {
        paramNames = new String[0];
    }//from w ww . j a  v  a2s .co  m
    if (paramVals == null) {
        paramVals = new String[0];
    }

    if (paramNames.length != paramVals.length) {
        Log.w(TAG, "Incompatible number of param names and values, bailing on upload!");
        return null;
    }

    SortedMap<String, String> sig_params = new TreeMap<String, String>();

    HttpResponse response = null;
    HttpPost httppost = null;
    Log.d(TAG, "HTTP POST URL: " + url);
    try {
        httppost = new HttpPost(url);
    } catch (IllegalArgumentException e) {
        try {
            json.put("fail", e.getMessage());
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        return json;
    }

    try {
        File file = null;
        // If this is a POST call, then it is a file upload. Check to see if
        // a
        // filename is given, and if so, open that file.
        // Get the title of the photo being uploaded so we can pass it into
        // the
        // MultipartEntityMonitored class to be broadcast for progress
        // updates.
        String title = "";
        for (int i = 0; i < paramNames.length; ++i) {
            if (paramNames[i].equals("title")) {
                title = paramVals[i];
            } else if (paramNames[i].equals("filename")) {
                file = new File(paramVals[i]);
                continue;
            }
            sig_params.put(paramNames[i], paramVals[i]);
        }

        MultipartEntityMonitored mp_entity = new MultipartEntityMonitored(context, title);
        if (file != null) {
            mp_entity.addPart("userfile", new FileBody(file));
        }
        for (Map.Entry<String, String> entry : sig_params.entrySet()) {
            mp_entity.addPart(entry.getKey(), new StringBody(entry.getValue()));
        }
        httppost.setEntity(mp_entity);

        response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();

        if (resEntity != null) {
            String content = convertStreamToString(resEntity.getContent());
            if (response.getStatusLine().getStatusCode() == 200) {
                try {
                    json = new JSONObject(content.toString());
                } catch (JSONException e1) {
                    Log.w(TAG, "Response 200 received but invalid JSON.");
                    json.put("fail", e1.getMessage());
                    if (DEBUG)
                        Log.d(TAG, "HTTP POST returned status code: " + response.getStatusLine());
                }
            } else {
                Log.w(TAG, "File upload failed with response code:" + response.getStatusLine().getStatusCode());
                json.put("fail", response.getStatusLine().getReasonPhrase());
                if (DEBUG)
                    Log.d(TAG, "HTTP POST returned status code: " + response.getStatusLine());
            }
        } else {
            Log.w(TAG, "Response does not contain a valid HTTP entity.");
            if (DEBUG)
                Log.d(TAG, "HTTP POST returned status code: " + response.getStatusLine());
        }

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        try {
            json.put("fail", e.getMessage());
        } catch (JSONException e1) {
        }
        e.printStackTrace();
    } catch (IllegalStateException e) {
        try {
            json.put("fail", e.getMessage());
        } catch (JSONException e1) {
        }
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        try {
            json.put("fail", e.getMessage());
        } catch (JSONException e1) {
        }
        e.printStackTrace();
    } catch (JSONException e) {
    }

    httpclient.getConnectionManager().shutdown();

    return json;

}

From source file:com.aurel.track.report.dashboard.AverageTimeToCloseItem.java

private String convertResultMapToJsonResponse(SortedMap<Date, Object> dateToAvgTime, int reportingInterval,
        int responseTimeLimitValue) {
    StringBuilder sb = new StringBuilder();
    boolean isEmpty = true;
    if (dateToAvgTime != null) {
        sb.append("[");
        for (Map.Entry<Date, Object> entry : dateToAvgTime.entrySet()) {
            if (isEmpty) {
                isEmpty = false;/*from  www.j  av a 2 s . c o  m*/
            }
            Date date = entry.getKey();
            Double avgValue = (Double) entry.getValue();
            sb.append("{");
            JSONUtility.appendStringValue(sb, "date", getDateBasedOnReportInterval(date, reportingInterval));
            JSONUtility.appendDoubleValue(sb, "avgTime", avgValue);
            JSONUtility.appendIntegerValue(sb, "respTimeLimitValue", responseTimeLimitValue, true);

            sb.append("},");
        }
        if (sb != null && sb.length() > 0) {
            if (sb.toString().endsWith(",")) {
                sb = new StringBuilder(sb.substring(0, sb.length() - 1));
            }
        }
        sb.append("]");
    }
    if (isEmpty) {
        sb = new StringBuilder();
        sb.append("[]");
    }
    return sb.toString();
}