improved
[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;
102                 Date date;
103                 List<Article> articles;
104                 boolean exist;
105                 
106                 feedTitle = feed.getTitle().trim();
107                 
108                 LOG.info("addArticles " + cat.getId() + " " + feedTitle + " number of articles: " + feed.getEntries().size());
109                 
110                 for (SyndEntry entry: feed.getEntries()) {
111                         thumbnail = null;
112                         for (SyndEnclosure e: entry.getEnclosures()) {
113                                 if (e.getType().startsWith("image/"))
114                                         thumbnail = e.getUrl();    
115                                 break;
116                         }
117                                 
118                         title = entry.getTitle().trim();
119                         
120                         if (entry.getDescription() != null) {                                      
121                                 desc = Jsoup.parse(entry.getDescription().getValue()).text();
122                         } else {       
123                                 desc = null;
124                                 LOG.severe("No description for " + feedTitle + " - " + title);
125                         }
126                         
127                         date = entry.getPublishedDate();
128                         if (date == null)
129                                 date = entry.getUpdatedDate();
130                         if (date == null) {
131                                 LOG.severe("The article " + feedTitle + " - " + title + " does not have a date");
132                                 continue;
133                         }                                
134                         
135                         synchronized(articlesByCategory) {
136                                 link = entry.getLink().trim();
137
138                                 articles = articlesByCategory.get(cat);
139                                 exist = false;
140                                 if (articles == null) {
141                                         articles = new ArrayList<>();
142                                         articlesByCategory.put(cat, articles);
143                                 } else {                                
144                                         for (Article a: articles)
145                                                 if (a.link.equals(link)) {
146                                                         LOG.info("addArticles " + link + " already present");
147                                                         exist = true;
148                                                 }
149                                 }
150                                 
151                                 if (!exist) {
152                                         LOG.fine("add " + cat.getId() + " " + feedTitle + " " + title);
153                                 
154                                         articles.add(new Article(link, cat, title, desc, thumbnail, date,
155                                                         feed.getTitle()));
156
157                                         Collections.sort(articles, new Comparator<Article>() {
158                                                 @Override
159                                                 public int compare(Article o1, Article o2) {
160                                                         return o2.publicationDate.compareTo(o1.publicationDate);
161                                                 }
162
163                                         });
164                                 } else {
165                                         LOG.finest("addArticles already exist: " + title);
166                                 }
167                         }
168                 }          
169                 
170                 LOG.info("addArticles done " + cat.getId());
171         }
172         
173         private void retrieveArticles(Category cat) throws IllegalArgumentException, MalformedURLException, FeedException, IOException {
174                 String[] feeds;
175                 
176                 feeds = getFeeds().get(cat);
177                 
178                 if (feeds != null)
179                         for (String str: feeds)
180                                 try {
181                                         addArticles(cat, getSyndFeed(str));
182                                 } catch (Throwable e) {
183                                         LOG.log(Level.SEVERE,
184                                                 "retrieveArticles failure " + cat.getId() + " " + str,
185                                                 e);
186                                 }
187                 else
188                         LOG.severe("No feed for category " + cat);
189         }
190         
191         public List<Article> getArticles(Category cat)
192                         throws IllegalArgumentException, MalformedURLException, FeedException, IOException {
193                 synchronized (articlesByCategory) {
194                         return articlesByCategory.get(cat);
195                 }
196         }
197         
198         private class Refresher implements Runnable {
199                 private final Category category;
200                 
201                 public Refresher(Category category) {
202                         this.category = category;
203                 }
204                 
205                 @Override
206                 public void run() {
207                         List<Article> articles;
208                         
209                         LOG.info("refresher "+ category.getId());
210                         
211                         try {
212                                 retrieveArticles(category);
213                                 
214                                 synchronized (articlesByCategory) {
215                                         articles = articlesByCategory.get(category);
216                                         if (articles != null && articles.size() > 100) {
217                                                 articlesByCategory.put(category,
218                                                                        articles.subList(0, 100));
219                                                                 
220                                         }
221                                         LOG.info("refresher " + category.getId() + " number of articles: " + articles.size());
222                                 }
223                         } catch (IllegalArgumentException | FeedException | IOException e) {
224                                 LOG.log(Level.SEVERE, "refresher failure", e);
225                         }                        
226                         
227                         LOG.info("refresher "+ category.getId() + " done");
228                 }                
229         }
230 }