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