X-Git-Url: https://git.wpitchoune.net/gitweb/?p=pnews.git;a=blobdiff_plain;f=war%2Fsrc%2Fmain%2Fjava%2Fnet%2Fwpitchoune%2Fpnews%2Fservlet%2FJSON.java;fp=war%2Fsrc%2Fmain%2Fjava%2Fnet%2Fwpitchoune%2Fpnews%2Fservlet%2FJSON.java;h=70b1c242bb4292a77606c2fcdbfa6681e5f766c1;hp=0000000000000000000000000000000000000000;hb=a0c6addfd9ac6ac45f37b4202e787602c40e6bf7;hpb=aff83c8798602b535d13edeaffdb8f4238e2bbf5 diff --git a/war/src/main/java/net/wpitchoune/pnews/servlet/JSON.java b/war/src/main/java/net/wpitchoune/pnews/servlet/JSON.java new file mode 100644 index 0000000..70b1c24 --- /dev/null +++ b/war/src/main/java/net/wpitchoune/pnews/servlet/JSON.java @@ -0,0 +1,60 @@ +package net.wpitchoune.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 net.wpitchoune.pnews.Article; +import net.wpitchoune.pnews.ArticleStore; +import net.wpitchoune.pnews.Category; +import net.wpitchoune.pnews.Config; + +public class JSON { + 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
articles; + Article[] allArticles; + + jstats = new JsonObject(); + + jstats.addProperty("articles-count", ArticleStore.singleton.size()); + + jreadcounts = new JsonObject(); + 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); + } + + 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); + } +}