read config from json. Many refactoring to prepare multi language support
[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(Category[] cats) {
18                 JsonObject jstats, jreadcounts, jcategories, jmemory;
19                 Runtime runtime;
20                 Article[] articles;
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: cats)
38                         try {
39                                 jcategories.addProperty(cat.getName(),
40                                                         articles.length);
41                         } catch (IllegalArgumentException e) {
42                                 LOG.log(Level.SEVERE, "Fail to retrieve articles", e);
43                         }
44                 
45                 jmemory = new JsonObject();
46                 jstats.add("memory", jmemory);
47                 
48                 runtime = Runtime.getRuntime();
49                 jmemory.addProperty("total", runtime.totalMemory());
50                 jmemory.addProperty("max", runtime.maxMemory());
51                 jmemory.addProperty("free", runtime.freeMemory());
52                 
53                 return new Gson().toJson(jstats);                
54         }
55 }