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