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