df68547f2a80758a12dee67f128c4f4e47232479
[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.francetvinfo.fr/titres.rss",
58                                            "http://www.rfi.fr/general/rss",
59                                            "http://www.cnews.fr/rss/une",
60                                            "http://www.ladepeche.fr/rss/a-la-une.rss",
61                                            "https://www.franceinter.fr/rss/a-la-une.xml",
62                                            "https://www.francebleu.fr/rss/a-la-une.xml",
63                                            "http://www.bfmtv.com/rss/info/flux-rss/flux-toutes-les-actualites/"
64                            });
65                 
66                 result.put(Category.SPORT,
67                                 new String[] { "http://www.france24.com/fr/sports/rss" });
68                 
69                 result.put(Category.FRANCE,
70                                 new String[] { "http://www.france24.com/fr/france/rss",
71                                                "http://www.francetvinfo.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                                                "http://www.frandroid.com/feed",
98                                                "http://www.silicon.fr/feed",
99                                                "http://www.fredzone.org/feed",
100                                                "http://www.futura-sciences.com/rss/actualites.xml",
101                                                "https://www-03.ibm.com/press/fr/fr/rssfeed.wss?keyword=null&maxFeed=&feedType=RSS&topic=all"});
102                 
103                 return result;
104         }
105         
106         private List<Article> getArticlesForUpdate(Category cat) {
107                 List<Article> result;
108                 
109                 synchronized (articlesByCategory) {
110                         result = articlesByCategory.get(cat);
111                         if (result == null) {
112                                 result = new ArrayList<>();
113                                 articlesByCategory.put(cat, result);
114                         }
115                         return result;
116                 }                
117         }
118         
119         private boolean exists(String articleLink, List<Article> articles) {
120                 synchronized (articles) {
121                         for (Article a: articles)
122                                 if (a.link.equals(articleLink))
123                                         return true;
124                 }
125                 return false;
126         }
127         
128         private static Article toArticle(String link, SyndEntry entry, SyndFeed feed) {
129                 String desc, title, thumbnail, feedTitle, str;
130                 Date date;
131                 
132                 feedTitle = feed.getTitle();
133                 if (feedTitle != null) {
134                         feedTitle = feedTitle.trim();
135                 }
136                 
137                 thumbnail = null;
138                 for (SyndEnclosure e: entry.getEnclosures()) {
139                         if (e.getType().startsWith("image/"))
140                                 thumbnail = e.getUrl();    
141                         break;
142                 }
143                 
144                 if (thumbnail == null && feed.getImage() != null)
145                         thumbnail = feed.getImage().getUrl();
146                              
147                 
148                 title = entry.getTitle().trim();
149                 
150                 if (entry.getDescription() != null) {
151                         str = entry.getDescription().getValue();
152                         desc = Jsoup.parse(str).text();
153                 } else {       
154                         desc = null;
155                         LOG.severe("No description for " + feedTitle + " - " + title);
156                 }
157                 
158                 date = entry.getPublishedDate();
159                 if (date == null)
160                         date = entry.getUpdatedDate();
161                 if (date == null)
162                         LOG.severe("The article " + feedTitle + " - " + title + " does not have a date");
163                                      
164                 return new Article(link, title, desc, thumbnail, date, feedTitle);
165         }
166         
167         private void addArticles(Category cat, SyndFeed feed) {
168                 String feedTitle;
169                 List<Article> articles;
170                 Article a;
171                 
172                 feedTitle = feed.getTitle().trim();
173                 
174                 LOG.info("addArticles " + cat.getId() + " " + feedTitle + " number of articles: " + feed.getEntries().size());
175                 
176                 for (SyndEntry entry: feed.getEntries()) {
177                         String link = entry.getLink().trim();
178                         articles = getArticlesForUpdate(cat);
179                         if (exists(link, articles)) {
180                                 LOG.fine("addArticles " + link + " is already present");
181                                 continue ;
182                         }
183                         
184                         a = ArticleStore.singleton.getArticle(link, ()->toArticle(link, entry, feed));
185                         
186                         synchronized (articles) {
187                                 articles.add(a);
188
189                                 Collections.sort(articles, new Comparator<Article>() {
190                                         @Override
191                                         public int compare(Article o1, Article o2) {
192                                                 if (o1.publicationDate == o2.publicationDate)
193                                                         return 0;
194                                                 if (o1.publicationDate == null)
195                                                         return 1;
196                                                 if (o2.publicationDate == null)
197                                                         return -1;
198                                                 return o2.publicationDate.compareTo(o1.publicationDate);
199                                         }
200                                 });
201                         }
202                 }          
203                 
204                 LOG.info("addArticles done " + cat.getId());
205         }
206              
207         private void retrieveArticles(Category cat) throws IllegalArgumentException, MalformedURLException, FeedException, IOException {
208                 String[] feeds;
209                 
210                 feeds = getFeeds().get(cat);
211                 
212                 if (feeds != null)
213                         for (String str: feeds)
214                                 try {
215                                         addArticles(cat, getSyndFeed(str));
216                                 } catch (Throwable e) {
217                                         LOG.log(Level.SEVERE,
218                                                 "retrieveArticles failure " + cat.getId() + " " + str,
219                                                 e);
220                                 }
221                 else
222                         LOG.severe("No feed for category " + cat);
223         }
224         
225         /**
226          * Returns a copy.
227          */
228         public List<Article> getArticles(Category cat)
229                         throws IllegalArgumentException, MalformedURLException, FeedException, IOException {
230                 List<Article> articles;
231                 
232                 synchronized (articlesByCategory) {
233                         articles = getArticlesForUpdate(cat);
234                 }
235                 
236                 synchronized (articles) {
237                         return new ArrayList<>(articles);
238                 }
239         }
240         
241         private class Refresher implements Runnable {
242                 private final Category category;
243                 
244                 public Refresher(Category category) {
245                         this.category = category;
246                 }
247                 
248                 @Override
249                 public void run() {                       
250                         LOG.info("refresher "+ category.getId());
251                         
252                         try {
253                                 retrieveArticles(category);
254                         } catch (IllegalArgumentException | FeedException | IOException e) {
255                                 LOG.log(Level.SEVERE, "refresher failure", e);
256                         }                        
257                         
258                         LOG.info("refresher "+ category.getId() + " done");
259                 }                
260         }
261 }