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