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