package pnews.servlet;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import pnews.Article;
+import pnews.Category;
public class JSON {
- public static String getStats() {
- JsonObject jarticles, jreadcounts;
+ private static final Logger LOG = Logger.getLogger(JSON.class.getName());
+
+ public static String getStats(Category[] cats) {
+ JsonObject jstats, jreadcounts, jcategories, jmemory;
+ Runtime runtime;
Article[] articles;
- jarticles = new JsonObject();
+ jstats = new JsonObject();
- jarticles.addProperty("articles-count", ArticleStore.singleton.size());
+ jstats.addProperty("articles-count", ArticleStore.singleton.size());
jreadcounts = new JsonObject();
- jarticles.add("read-counts", jreadcounts);
+ jstats.add("read-counts", jreadcounts);
articles = ArticleStore.singleton.getArticles();
for (Article a: articles)
if (a.readCount.get() > 0)
jreadcounts.addProperty(a.link, a.readCount);
- return new Gson().toJson(jarticles);
+ jcategories = new JsonObject();
+ jstats.add("categories", jcategories);
+
+ for (Category cat: cats)
+ try {
+ jcategories.addProperty(cat.getLabel(),
+ articles.length);
+ } catch (IllegalArgumentException e) {
+ LOG.log(Level.SEVERE, "Fail to retrieve articles", e);
+ }
+
+ jmemory = new JsonObject();
+ jstats.add("memory", jmemory);
+
+ runtime = Runtime.getRuntime();
+ jmemory.addProperty("total", runtime.totalMemory());
+ jmemory.addProperty("max", runtime.maxMemory());
+ jmemory.addProperty("free", runtime.freeMemory());
+ return new Gson().toJson(jstats);
}
}