78379a4ca0fccb1a674fb8f35346d1d18e4e1940
[pnews.git] / war / src / main / java / pnews / servlet / JSON.java
1 package pnews.servlet;
2
3 import java.io.IOException;
4 import java.util.List;
5 import java.util.logging.Level;
6 import java.util.logging.Logger;
7
8 import com.google.gson.Gson;
9 import com.google.gson.JsonObject;
10 import com.rometools.rome.io.FeedException;
11
12 import net.wpitchoune.pnews.Article;
13 import net.wpitchoune.pnews.ArticleStore;
14 import net.wpitchoune.pnews.Category;
15 import net.wpitchoune.pnews.Config;
16
17 public class JSON {
18         private static final Logger LOG = Logger.getLogger(JSON.class.getName());
19         
20         public static String getStats(ArticleProvider provider, Config config) {
21                 JsonObject jstats, jreadcounts, jcategories, jmemory;
22                 Runtime runtime;
23                 List<Article> articles;
24                 Article[] allArticles;
25                 
26                 jstats = new JsonObject();
27                                 
28                 jstats.addProperty("articles-count", ArticleStore.singleton.size());
29                 
30                 jreadcounts = new JsonObject();
31                 jstats.add("read-counts", jreadcounts);
32                 
33                 allArticles = ArticleStore.singleton.getArticles();
34                 for (Article a: allArticles)
35                         if (a.getReadCount() > 0)
36                                 jreadcounts.addProperty(a.getLink(), a.getReadCount());         
37                 
38                 jcategories = new JsonObject();
39                 jstats.add("categories", jcategories);
40                 
41                 for (Category cat: config.getCategories())
42                         try {
43                                 articles = provider.getArticles(cat, null);
44                                 jcategories.addProperty(cat.getLabel(),
45                                                         articles.size());
46                         } catch (IllegalArgumentException | FeedException | IOException e) {
47                                 LOG.log(Level.SEVERE, "Fail to retrieve articles", e);
48                         }
49                 
50                 jmemory = new JsonObject();
51                 jstats.add("memory", jmemory);
52                 
53                 runtime = Runtime.getRuntime();
54                 jmemory.addProperty("total", runtime.totalMemory());
55                 jmemory.addProperty("max", runtime.maxMemory());
56                 jmemory.addProperty("free", runtime.freeMemory());
57                 
58                 return new Gson().toJson(jstats);                
59         }
60 }