removed useless vars
[pnews.git] / war / src / main / java / pnews / servlet / ArticleProvider.java
1 package pnews.servlet;
2
3 import java.io.IOException;
4 import java.net.MalformedURLException;
5 import java.net.URL;
6 import java.util.ArrayList;
7 import java.util.Collections;
8 import java.util.Comparator;
9 import java.util.Date;
10 import java.util.HashMap;
11 import java.util.List;
12 import java.util.Map;
13 import java.util.concurrent.Executors;
14 import java.util.concurrent.ScheduledExecutorService;
15 import java.util.concurrent.TimeUnit;
16 import java.util.logging.Level;
17 import java.util.logging.Logger;
18
19 import org.jsoup.Jsoup;
20
21 import com.rometools.rome.feed.synd.SyndEnclosure;
22 import com.rometools.rome.feed.synd.SyndEntry;
23 import com.rometools.rome.feed.synd.SyndFeed;
24 import com.rometools.rome.io.FeedException;
25 import com.rometools.rome.io.SyndFeedInput;
26 import com.rometools.rome.io.XmlReader;
27
28 import pnews.Article;
29 import pnews.Category;
30
31 public class ArticleProvider {
32         public final static ArticleProvider singleton = new ArticleProvider();
33         private static final Logger LOG = Logger.getLogger(ArticleProvider.class.getName());
34         private final Map<Category, List<Article>> articlesByCategory = new HashMap<>();
35         private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
36         
37         private ArticleProvider() {      
38                 for (Category cat:Category.values())
39                         scheduler.scheduleAtFixedRate(new Refresher(cat), 2, 600, TimeUnit.SECONDS);
40         }
41         
42         private static SyndFeed getSyndFeed(String u) throws IllegalArgumentException, FeedException, MalformedURLException, IOException {
43                 XmlReader r;
44                 
45                 r = new XmlReader(new URL(u));
46                 XmlReader.setDefaultEncoding("UTF-8");
47                 
48                 return new SyndFeedInput().build(r);                
49         }
50         
51         private static Map<Category, String[]> getFeeds() {
52                 Map<Category, String[]> result;
53                 
54                 result = new HashMap<>();
55                 
56                 result.put(Category.TOP,
57                            new String[] {
58                                            "http://www.francetvinfo.fr/titres.rss",
59                                            "http://www.rfi.fr/general/rss",
60                                            "http://www.cnews.fr/rss/une",
61                                            "http://www.ladepeche.fr/rss/a-la-une.rss",
62                                            "https://www.franceinter.fr/rss/a-la-une.xml",
63                                            "https://www.francebleu.fr/rss/a-la-une.xml",
64                                            "http://www.bfmtv.com/rss/info/flux-rss/flux-toutes-les-actualites/"
65                            });
66                 
67                 result.put(Category.SPORT,
68                                 new String[] { "http://www.france24.com/fr/sports/rss" });
69                 
70                 result.put(Category.FRANCE,
71                                 new String[] { "http://www.france24.com/fr/france/rss",
72                                                "http://www.rfi.fr/france/rss"});
73                 
74                 result.put(Category.EUROPE,
75                                 new String[] { "http://www.france24.com/fr/europe/rss" });
76
77                 result.put(Category.MONDE, 
78                            new String[] { "http://www.france24.com/fr/actualites/rss" });                                           
79
80                 
81                 result.put(Category.ECO,
82                                 new String[] { "http://www.france24.com/fr/economie/rss",
83                                                "http://www.rfi.fr/economie/rss" });
84                 
85                 result.put(Category.ESSONNE,
86                                 new String[] { "http://www.tourisme-essonne.com/rss/actus/",
87                                                "http://www.ville-palaiseau.fr/rss/actualites.htm" });
88                 
89                 result.put(Category.PEOPLE,
90                                 new String[] { "http://www.premiere.fr/rss/actu-live",
91                                                "http://www.purepeople.com/rss/news_t0.xml"                                               
92                 });
93                 
94                 result.put(Category.TECHNOLOGIE,
95                                 new String[] { "http://feeds.feedburner.com/lesnumeriques/news",
96                                                "http://www.zdnet.fr/feeds/rss/actualites/"});
97                 
98                 return result;
99         }
100         
101         private List<Article> getArticlesForUpdate(Category cat) {
102                 List<Article> result;
103                 
104                 synchronized (articlesByCategory) {
105                         result = articlesByCategory.get(cat);
106                         if (result == null) {
107                                 result = new ArrayList<>();
108                                 articlesByCategory.put(cat, result);
109                         }
110                         return result;
111                 }                
112         }
113         
114         private boolean exists(String articleLink, List<Article> articles) {
115                 synchronized (articles) {
116                         for (Article a: articles)
117                                 if (a.link.equals(articleLink))
118                                         return true;
119                 }
120                 return false;
121         }
122         
123         private Article toArticle(String link, Category cat, SyndEntry entry, SyndFeed feed) {
124                 String desc, title, thumbnail;
125                 Date date;
126
127                 thumbnail = null;
128                 for (SyndEnclosure e: entry.getEnclosures()) {
129                         if (e.getType().startsWith("image/"))
130                                 thumbnail = e.getUrl();    
131                         break;
132                 }
133                 
134                 if (thumbnail == null && feed.getImage() != null)
135                         thumbnail = feed.getImage().getUrl();
136                                                 
137                 title = entry.getTitle().trim();
138                 
139                 if (entry.getDescription() != null) {                                      
140                         desc = Jsoup.parse(entry.getDescription().getValue()).text();
141                 } else {       
142                         desc = null;
143                         LOG.severe("No description for " + feed.getTitle() + " - " + title);
144                 }
145                 
146                 date = entry.getPublishedDate();
147                 if (date == null)
148                         date = entry.getUpdatedDate();
149                 if (date == null)
150                         LOG.severe("The article " + feed.getTitle() + " - " + title + " does not have a date");
151                                      
152                 return new Article(link, cat, title, desc, thumbnail, date, title);
153         }
154         
155         
156         
157         private void addArticles(Category cat, SyndFeed feed) {
158                 String link, feedTitle;
159                 List<Article> articles;
160                 Article a;
161                 
162                 feedTitle = feed.getTitle().trim();
163                 
164                 LOG.info("addArticles " + cat.getId() + " " + feedTitle + " number of articles: " + feed.getEntries().size());
165                 
166                 for (SyndEntry entry: feed.getEntries()) {
167                         link = entry.getLink().trim();
168                         articles = getArticlesForUpdate(cat);
169                         if (exists(link, articles)) {
170                                 LOG.fine("addArticles " + link + " is already present");
171                                 continue ;
172                         }
173                         
174                         a = toArticle(link, cat, entry, feed);
175                         
176                         synchronized (articles) {
177                                 articles.add(a);
178
179                                 Collections.sort(articles, new Comparator<Article>() {
180                                         @Override
181                                         public int compare(Article o1, Article o2) {
182                                                 if (o1.publicationDate == o2.publicationDate)
183                                                         return 0;
184                                                 if (o1.publicationDate == null)
185                                                         return 1;
186                                                 if (o2.publicationDate == null)
187                                                         return -1;
188                                                 return o2.publicationDate.compareTo(o1.publicationDate);
189                                         }
190
191                                 });
192                         }
193                 }          
194                 
195                 LOG.info("addArticles done " + cat.getId());
196         }
197         
198         private void retrieveArticles(Category cat) throws IllegalArgumentException, MalformedURLException, FeedException, IOException {
199                 String[] feeds;
200                 
201                 feeds = getFeeds().get(cat);
202                 
203                 if (feeds != null)
204                         for (String str: feeds)
205                                 try {
206                                         addArticles(cat, getSyndFeed(str));
207                                 } catch (Throwable e) {
208                                         LOG.log(Level.SEVERE,
209                                                 "retrieveArticles failure " + cat.getId() + " " + str,
210                                                 e);
211                                 }
212                 else
213                         LOG.severe("No feed for category " + cat);
214         }
215         
216         /**
217          * Returns a copy.
218          */
219         public List<Article> getArticles(Category cat)
220                         throws IllegalArgumentException, MalformedURLException, FeedException, IOException {
221                 List<Article> articles;
222                 
223                 synchronized (articlesByCategory) {
224                         articles = getArticlesForUpdate(cat);
225                 }
226                 
227                 synchronized (articles) {
228                         return new ArrayList<>(articles);
229                 }
230         }
231         
232         private class Refresher implements Runnable {
233                 private final Category category;
234                 
235                 public Refresher(Category category) {
236                         this.category = category;
237                 }
238                 
239                 @Override
240                 public void run() {
241                         List<Article> articles;
242                         
243                         LOG.info("refresher "+ category.getId());
244                         
245                         try {
246                                 retrieveArticles(category);
247                                 
248                                 synchronized (articlesByCategory) {
249                                         articles = articlesByCategory.get(category);
250                                         if (articles != null && articles.size() > 100) {
251                                                 articlesByCategory.put(category,
252                                                                        articles.subList(0, 100));
253                                                                 
254                                         }
255                                         LOG.info("refresher " + category.getId() + " number of articles: " + articles.size());
256                                 }
257                         } catch (IllegalArgumentException | FeedException | IOException e) {
258                                 LOG.log(Level.SEVERE, "refresher failure", e);
259                         }                        
260                         
261                         LOG.info("refresher "+ category.getId() + " done");
262                 }                
263         }
264 }