610da29e7b6e0228ed5cf4d9baf7233c3af17076
[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                 
47                 return new SyndFeedInput().build(r);                
48         }
49         
50         private static Map<Category, String[]> getFeeds() {
51                 Map<Category, String[]> result;
52                 
53                 result = new HashMap<>();
54                 
55                 result.put(Category.TOP,
56                            new String[] {
57                                            "http://www.europe1.fr/var/export/rss/europe1/actus.xml",
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.europe1.fr/var/export/rss/europe1/sport.xml",
69                                                "http://www.france24.com/fr/sports/rss" });
70                 
71                 result.put(Category.FRANCE,
72                                 new String[] { "http://www.france24.com/fr/france/rss",
73                                                "http://www.francetvinfo.fr/france.rss",
74                                                "http://www.rfi.fr/france/rss"});
75                 
76                 result.put(Category.EUROPE,
77                                 new String[] { "http://www.france24.com/fr/europe/rss" });
78
79                 result.put(Category.MONDE, 
80                            new String[] { "http://www.europe1.fr/var/export/rss/europe1/international.xml",
81                                           "http://www.france24.com/fr/actualites/rss" });                                           
82
83                 
84                 result.put(Category.ECO,
85                                 new String[] { "http://www.france24.com/fr/economie/rss",
86                                                "http://www.europe1.fr/var/export/rss/europe1/economie.xml",
87                                                "http://www.rfi.fr/economie/rss" });
88                 
89                 result.put(Category.ESSONNE,
90                                 new String[] { "http://www.tourisme-essonne.com/rss/actus/",
91                                                "http://www.ville-palaiseau.fr/rss/actualites.htm" });
92                 
93                 result.put(Category.PEOPLE,
94                                 new String[] { "http://www.premiere.fr/rss/actu-live",
95                                                "http://www.purepeople.com/rss/news_t0.xml"                                               
96                 });
97                 
98                 result.put(Category.TECHNOLOGIE,
99                                 new String[] { "http://www.generation-nt.com/export/rss.xml",
100                                                "http://www.europe1.fr/var/export/rss/europe1/sciences.xml",
101                                                "http://feeds.feedburner.com/lesnumeriques/news",
102                                                "http://www.zdnet.fr/feeds/rss/actualites/",
103                                                "http://www.frandroid.com/feed",
104                                                "http://www.silicon.fr/feed",
105                                                "http://www.fredzone.org/feed",
106                                                "http://www.futura-sciences.com/rss/actualites.xml",
107                                                "https://www-03.ibm.com/press/fr/fr/rssfeed.wss?keyword=null&maxFeed=&feedType=RSS&topic=all"});
108                 
109                 return result;
110         }
111         
112         private List<Article> getArticlesForUpdate(Category cat) {
113                 List<Article> result;
114                 
115                 synchronized (articlesByCategory) {
116                         result = articlesByCategory.get(cat);
117                         if (result == null) {
118                                 result = new ArrayList<>();
119                                 articlesByCategory.put(cat, result);
120                         }
121                         return result;
122                 }                
123         }
124         
125         private boolean exists(String articleLink, List<Article> articles) {
126                 synchronized (articles) {
127                         for (Article a: articles)
128                                 if (a.link.equals(articleLink))
129                                         return true;
130                 }
131                 return false;
132         }
133         
134         private static Article toArticle(String link, SyndEntry entry, SyndFeed feed) {
135                 String desc, title, thumbnail, feedTitle, str;
136                 Date date;
137                 
138                 feedTitle = feed.getTitle();
139                 if (feedTitle != null) {
140                         feedTitle = feedTitle.trim();
141                 }
142                 
143                 thumbnail = null;
144                 for (SyndEnclosure e: entry.getEnclosures()) {
145                         if (e.getType().startsWith("image/"))
146                                 thumbnail = e.getUrl();    
147                         break;
148                 }
149                 
150                 if (thumbnail == null && feed.getImage() != null)
151                         thumbnail = feed.getImage().getUrl();
152                              
153                 
154                 title = entry.getTitle().trim();
155                 
156                 if (entry.getDescription() != null) {
157                         str = entry.getDescription().getValue();
158                         desc = Jsoup.parse(str).text();
159                 } else {       
160                         desc = null;
161                         LOG.severe("No description for " + feedTitle + " - " + title);
162                 }
163                 
164                 date = entry.getPublishedDate();
165                 if (date == null)
166                         date = entry.getUpdatedDate();
167                 if (date == null)
168                         LOG.severe("The article " + feedTitle + " - " + title + " does not have a date");
169                                      
170                 return new Article(link, title, desc, thumbnail, date, feedTitle);
171         }
172         
173         private void addArticles(Category cat, SyndFeed feed) {
174                 String feedTitle;
175                 List<Article> articles;
176                 Article a;
177                 
178                 feedTitle = feed.getTitle().trim();
179                 
180                 LOG.info("addArticles " + cat.getId() + " " + feedTitle + " number of articles: " + feed.getEntries().size());
181                 
182                 for (SyndEntry entry: feed.getEntries()) {
183                         String link = entry.getLink().trim();
184                         articles = getArticlesForUpdate(cat);
185                         if (exists(link, articles)) {
186                                 LOG.fine("addArticles " + link + " is already present");
187                                 continue ;
188                         }
189                         
190                         a = ArticleStore.singleton.getArticle(link, ()->toArticle(link, entry, feed));
191                         
192                         synchronized (articles) {
193                                 articles.add(a);
194
195                                 Collections.sort(articles, new Comparator<Article>() {
196                                         @Override
197                                         public int compare(Article o1, Article o2) {
198                                                 if (o1.publicationDate == o2.publicationDate)
199                                                         return 0;
200                                                 if (o1.publicationDate == null)
201                                                         return 1;
202                                                 if (o2.publicationDate == null)
203                                                         return -1;
204                                                 return o2.publicationDate.compareTo(o1.publicationDate);
205                                         }
206                                 });
207                         }
208                 }          
209                 
210                 LOG.info("addArticles done " + cat.getId());
211         }
212              
213         private void retrieveArticles(Category cat) throws IllegalArgumentException, MalformedURLException, FeedException, IOException {
214                 String[] feeds;
215                 
216                 feeds = getFeeds().get(cat);
217                 
218                 if (feeds != null)
219                         for (String str: feeds)
220                                 try {
221                                         addArticles(cat, getSyndFeed(str));
222                                 } catch (Throwable e) {
223                                         LOG.log(Level.SEVERE,
224                                                 "retrieveArticles failure " + cat.getId() + " " + str,
225                                                 e);
226                                 }
227                 else
228                         LOG.severe("No feed for category " + cat);
229         }
230         
231         /**
232          * Returns a copy.
233          */
234         public List<Article> getArticles(Category cat)
235                         throws IllegalArgumentException, MalformedURLException, FeedException, IOException {
236                 List<Article> articles;
237                 
238                 synchronized (articlesByCategory) {
239                         articles = getArticlesForUpdate(cat);
240                 }
241                 
242                 synchronized (articles) {
243                         return new ArrayList<>(articles);
244                 }
245         }
246         
247         private class Refresher implements Runnable {
248                 private final Category category;
249                 
250                 public Refresher(Category category) {
251                         this.category = category;
252                 }
253                 
254                 @Override
255                 public void run() {                       
256                         LOG.info("refresher "+ category.getId());
257                         
258                         try {
259                                 retrieveArticles(category);
260                         } catch (IllegalArgumentException | FeedException | IOException e) {
261                                 LOG.log(Level.SEVERE, "refresher failure", e);
262                         }                        
263                         
264                         LOG.info("refresher "+ category.getId() + " done");
265                 }                
266         }
267 }