fixed stats of articles per category
[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 pnews.Article;
13 import pnews.Category;
14
15 public class JSON {
16         private static final Logger LOG = Logger.getLogger(JSON.class.getName());
17         
18         public static String getStats(ArticleProvider provider, Config config) {
19                 JsonObject jstats, jreadcounts, jcategories, jmemory;
20                 Runtime runtime;
21                 List<Article> articles;
22                 Article[] allArticles;
23                 
24                 jstats = new JsonObject();
25                                 
26                 jstats.addProperty("articles-count", ArticleStore.singleton.size());
27                 
28                 jreadcounts = new JsonObject();
29                 jstats.add("read-counts", jreadcounts);
30                 
31                 allArticles = ArticleStore.singleton.getArticles();
32                 for (Article a: allArticles)
33                         if (a.readCount.get() > 0)
34                                 jreadcounts.addProperty(a.link, a.readCount);         
35                 
36                 jcategories = new JsonObject();
37                 jstats.add("categories", jcategories);
38                 
39                 for (Category cat: config.getCategories())
40                         try {
41                                 articles = provider.getArticles(cat);
42                                 jcategories.addProperty(cat.getLabel(),
43                                                         articles.size());
44                         } catch (IllegalArgumentException | FeedException | IOException e) {
45                                 LOG.log(Level.SEVERE, "Fail to retrieve articles", e);
46                         }
47                 
48                 jmemory = new JsonObject();
49                 jstats.add("memory", jmemory);
50                 
51                 runtime = Runtime.getRuntime();
52                 jmemory.addProperty("total", runtime.totalMemory());
53                 jmemory.addProperty("max", runtime.maxMemory());
54                 jmemory.addProperty("free", runtime.freeMemory());
55                 
56                 return new Gson().toJson(jstats);                
57         }
58 }