69ad1bc338eddbc1a49ddb4226c7b3efa92a7d7d
[pnews.git] / war / src / main / java / pnews / servlet / Pnews.java
1 package pnews.servlet;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.io.InputStreamReader;
6 import java.io.Reader;
7 import java.io.UnsupportedEncodingException;
8 import java.io.Writer;
9 import java.net.URLDecoder;
10 import java.util.ArrayList;
11 import java.util.List;
12 import java.util.logging.Level;
13 import java.util.logging.Logger;
14
15 import javax.servlet.ServletConfig;
16 import javax.servlet.ServletException;
17 import javax.servlet.http.HttpServlet;
18 import javax.servlet.http.HttpServletRequest;
19 import javax.servlet.http.HttpServletResponse;
20
21 import com.rometools.rome.io.FeedException;
22
23 import pnews.Article;
24 import pnews.Category;
25 import pnews.Language;
26
27 public class Pnews extends HttpServlet {
28         private static final String CLASS_NAME = Pnews.class.getName();
29         private static final Logger LOG = Logger.getLogger(Pnews.class.getName());
30         private static final long serialVersionUID = 1L;
31         private ArticleProvider provider;
32         private Config config;
33
34         private static String getQueryParameter(HttpServletRequest rq, String key)
35                         throws UnsupportedEncodingException {
36                 final String METHOD_NAME="getQueryParameter";                
37                 String[] params;
38                 int idx;
39                 String q;
40                 
41                 
42                 LOG.entering(CLASS_NAME, METHOD_NAME, new Object[] { rq, key} );
43
44                 q = rq.getQueryString();
45
46                 if (q == null)
47                         return null;
48
49                 params = q.split("&");
50
51                 for (String p: params) {
52                         idx = p.indexOf('=');
53
54                         if (idx > 1 && p.substring(0, idx).equals(key))
55                                 return URLDecoder.decode(p.substring(idx + 1), "UTF-8");
56                 }
57
58                 return null;
59         }
60
61         private static void redirect(HttpServletRequest rq, HttpServletResponse rp) {
62                 String redirectURL;
63                 Article a;
64
65                 LOG.entering(Pnews.class.getName(), "redirect", new Object[] { rq, rp });
66
67                 try {
68                         redirectURL = getQueryParameter(rq, "url");
69
70                         LOG.info("Request redirection to " + redirectURL);
71
72                         if (redirectURL != null) {
73                                 a = ArticleStore.singleton.get(redirectURL);
74                                 if (a != null)
75                                         a.readCount.incrementAndGet();
76                                 else
77                                         LOG.severe("Cannot find the article " + redirectURL);
78                                 
79                                 rp.setHeader("Location", redirectURL);
80                                 rp.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
81                         } else {
82                                 LOG.severe("No redirection URL");
83                                 rp.setStatus(HttpServletResponse.SC_NOT_FOUND);
84                         }
85
86                 } catch (UnsupportedEncodingException e) {
87                         e.printStackTrace();
88                         LOG.log(Level.SEVERE, "redirect failure", e);
89                         rp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
90                 }
91
92                 LOG.exiting(Pnews.class.getName(), "redirect");
93         }
94         
95         private static void doTemporaryRedirect(String newURL, HttpServletResponse rp) {
96                 rp.setHeader("Location", newURL);
97                 rp.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);             
98         }
99
100         private void writeStats(HttpServletResponse rp) throws IOException {
101                 rp.setContentType("application/json;charset=utf-8");
102                 rp.setCharacterEncoding("utf-8");
103
104                 rp.getWriter().write(JSON.getStats(provider, config));
105         }
106
107         
108         private void writeArticles(Category cat, String entity, HttpServletResponse rp) {
109                 String html;
110                 List<Article> articles;
111
112                 try {
113                         articles = provider.getArticles(cat, entity);
114                         if (articles != null) {
115                                 html = HTML.toHTML(articles, cat, entity, config, provider);
116                                 rp.setContentType("text/html;charset=utf-8");
117                                 rp.getWriter().write(html);
118                                 rp.setCharacterEncoding("utf-8");
119                         } else {
120                                 LOG.severe("writeArticles cannot retrieve any articles");
121                                 html = HTML.toHTML(new ArrayList<Article>(), cat, entity, config, provider);
122                                 rp.setContentType("text/html");
123                                 rp.getWriter().write(html);
124                         }
125                 } catch (IOException | IllegalArgumentException | FeedException e) {
126                         LOG.log(Level.SEVERE, "writeArticles failure", e);
127                         rp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
128                 }
129         }
130
131         private void copy(InputStream in, Writer writer) throws IOException {
132                 Reader r;
133                 char[] buf;
134                 int n;
135
136                 buf = new char[1024];
137                 r = new InputStreamReader(in);
138                 while ( (n = r.read(buf, 0, buf.length)) != -1)
139                         writer.write(buf, 0, n);
140         }
141
142         @Override
143         protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
144                 final String METHOD_NAME = "doGet";
145                 String path;
146                 InputStream in;
147
148                 RequesterLog.singleton.writeRequest(req);
149               
150                 LOG.info("doGet " + req.getRemoteAddr().toString() + " " + req.getRequestURI() + " " + req.getQueryString());
151                                 
152                 LOG.info(METHOD_NAME + " queryString=" + req.getQueryString());
153                 
154                 path = req.getPathInfo();
155
156                 if (path.equals("/redirect")) {
157                         redirect(req, resp);
158                         return ;
159                 }
160
161                 if (path.equals("/style.css")) {
162                         try {
163                                 in = HTML.class.getClassLoader().getResourceAsStream("style.css");
164                                 copy(in, resp.getWriter());
165                                 resp.setContentType("text/css");
166
167                                 return ;
168                         } catch (IOException e) {
169                                 LOG.log(Level.SEVERE, "doGet failure", e);
170                                 resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
171
172                                 return ;
173                         }
174                 }
175
176                 if (path.equals("/")) {
177                         doTemporaryRedirect(config.getDefaultLanguage().toURL(), resp);
178                         return ;
179                 }
180
181                 try {
182                         if (path.equals("/stats")) {
183                                 writeStats(resp);
184                                 return ;
185                         }
186                 
187                         for (Category cat: config.getCategories()) {
188                                 if (path.equals(cat.getURL())) {
189                                         writeArticles(cat, getQueryParameter(req, "entity"), resp);
190                                         return ;
191                                 }
192                         }
193                         
194                         for (Language l: config.getLanguages()) {
195                                 if (path.equals(l.toURL())) {
196                                         doTemporaryRedirect(config.getDefaultCategory(l).getURL(), resp);
197                                         return ;
198                                 }
199                         }
200                 
201                         resp.getWriter().write("Not found " + req.getPathInfo());
202                         resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
203                 } catch (IOException | RuntimeException e) {
204                         LOG.log(Level.SEVERE, "doGet failure", e);
205                         resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
206                 }
207         }
208
209         @Override
210         public void init(ServletConfig cfg) throws ServletException {
211                 LOG.info("Pnews servlet init " + cfg.getServletContext().getContextPath());
212                 
213                 config = new Config();
214                 try {
215                         config.loadConfig();
216                 } catch (UnsupportedEncodingException e) {
217                         throw new ServletException(e);
218                 }
219                 
220                 provider = new ArticleProvider(config);
221         }
222 }