package pnews.servlet;
+import java.io.IOException;
+import java.util.List;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
import com.google.gson.Gson;
import com.google.gson.JsonObject;
+import com.rometools.rome.io.FeedException;
-import pnews.Article;
+import net.wpitchoune.pnews.Article;
+import net.wpitchoune.pnews.ArticleStore;
+import net.wpitchoune.pnews.Category;
+import net.wpitchoune.pnews.Config;
public class JSON {
- public static String getStats() {
- JsonObject jarticles, jreadcounts;
- Article[] articles;
+ private static final Logger LOG = Logger.getLogger(JSON.class.getName());
+
+ public static String getStats(ArticleProvider provider, Config config) {
+ JsonObject jstats, jreadcounts, jcategories, jmemory;
+ Runtime runtime;
+ List<Article> articles;
+ Article[] allArticles;
- 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);
+
+ allArticles = ArticleStore.singleton.getArticles();
+ for (Article a: allArticles)
+ if (a.getReadCount() > 0)
+ jreadcounts.addProperty(a.getLink(), a.getReadCount());
+
+ jcategories = new JsonObject();
+ jstats.add("categories", jcategories);
+
+ for (Category cat: config.getCategories())
+ try {
+ articles = provider.getArticles(cat, null);
+ jcategories.addProperty(cat.getLabel(),
+ articles.size());
+ } catch (IllegalArgumentException | FeedException | IOException e) {
+ LOG.log(Level.SEVERE, "Fail to retrieve articles", e);
+ }
- articles = ArticleStore.singleton.getArticles();
- for (Article a: articles)
- if (a.readCount.get() > 0)
- jreadcounts.addProperty(a.link, a.readCount);
+ jmemory = new JsonObject();
+ jstats.add("memory", jmemory);
- return new Gson().toJson(jarticles);
+ runtime = Runtime.getRuntime();
+ jmemory.addProperty("total", runtime.totalMemory());
+ jmemory.addProperty("max", runtime.maxMemory());
+ jmemory.addProperty("free", runtime.freeMemory());
+ return new Gson().toJson(jstats);
}
}