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