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