ba96fe39856c1aff444dc4dc2aabe0c9be5e5f8a
[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.time.Instant;
7 import java.time.temporal.ChronoUnit;
8 import java.util.ArrayList;
9 import java.util.Collections;
10 import java.util.Comparator;
11 import java.util.Date;
12 import java.util.HashMap;
13 import java.util.List;
14 import java.util.Map;
15 import java.util.concurrent.Executors;
16 import java.util.concurrent.ScheduledExecutorService;
17 import java.util.concurrent.TimeUnit;
18 import java.util.logging.Level;
19 import java.util.logging.Logger;
20
21 import org.jsoup.Jsoup;
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 import com.rometools.rome.io.XmlReader;
29
30 import pnews.Article;
31 import pnews.Category;
32 import pnews.EntityStat;
33 import pnews.Feed;
34 import pnews.NER;
35
36 public class ArticleProvider {
37         private static final String CLASS_NAME = ArticleProvider.class.getName();
38         private static final Logger LOG = Logger.getLogger(CLASS_NAME);
39         private final Map<Category, List<Article>> articlesByCategory = new HashMap<>();
40         private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());
41         private final Config config;
42         
43         public ArticleProvider(Config config) {
44                 this.config = config;
45                 for (Category cat: config.getCategories())
46                         scheduler.scheduleAtFixedRate(new Refresher(cat), 2, 600, TimeUnit.SECONDS);
47         }
48         
49         private static SyndFeed getSyndFeed(String u) throws IllegalArgumentException, FeedException, MalformedURLException, IOException {
50                 XmlReader r;
51                 
52                 r = new XmlReader(new URL(u));
53                 
54                 return new SyndFeedInput().build(r);                
55         }
56         
57         private List<Article> getArticlesForUpdate(Category cat) {
58                 List<Article> result;
59                 
60                 synchronized (articlesByCategory) {
61                         result = articlesByCategory.get(cat);
62                         if (result == null) {
63                                 result = new ArrayList<>();
64                                 articlesByCategory.put(cat, result);
65                         }
66                         return result;
67                 }                
68         }
69         
70         private boolean exists(String articleLink, List<Article> articles) {
71                 synchronized (articles) {
72                         for (Article a: articles)
73                                 if (a.link.equals(articleLink))
74                                         return true;
75                 }
76                 return false;
77         }
78         
79         private Instant getArticleInstant(SyndEntry entry) {
80                 Date date;
81                 
82                 date = entry.getUpdatedDate();       
83                 if (date == null)
84                         date = entry.getPublishedDate();
85
86                 if (date == null)
87                         return Instant.now();
88                 
89                 return date.toInstant();
90         }
91         
92         private Article toArticle(String link, SyndEntry entry, SyndFeed feed, String lang, Instant instant) {
93                 String desc, title, thumbnail, feedTitle, str;
94                 Date date;
95                 List<String> entities;
96                 
97                 feedTitle = feed.getTitle();
98                 if (feedTitle != null) {
99                         feedTitle = feedTitle.trim();
100                 }
101                 
102                 thumbnail = null;
103                 for (SyndEnclosure e: entry.getEnclosures()) {
104                         if (e.getType().startsWith("image/"))
105                                 thumbnail = e.getUrl();    
106                         break;
107                 }
108                                 
109                 title = entry.getTitle().trim();
110                 
111                 if (entry.getDescription() != null) {
112                         str = entry.getDescription().getValue();
113                         desc = Jsoup.parse(str).text();
114                 } else {       
115                         desc = null;
116                         LOG.severe("No description for " + feedTitle + " - " + title);
117                 }
118                                 
119                 entities = new ArrayList<>();
120                 if (desc != null && lang.equals("en"))
121                         try {
122                                 NER.classify(title, entities, config);
123                                 NER.classify(desc, entities, config);
124                         } catch (ClassCastException | ClassNotFoundException | IOException e1) {
125                                 LOG.log(Level.SEVERE, "Cannot classify " + feedTitle, e1);                         
126                         }
127                 
128                 return new Article(link, title, desc, thumbnail, instant, feedTitle, entities.toArray(new String[0]));
129         }
130         
131         private void addArticles(Category cat, SyndFeed feed) {
132                 String feedTitle;
133                 List<Article> articles;
134                 Article a;
135                 
136                 feedTitle = feed.getTitle().trim();
137                 
138                 LOG.info("addArticles " + cat.getLabel() + " " + feedTitle + " number of articles: " + feed.getEntries().size());
139                 
140                 for (SyndEntry entry: feed.getEntries()) {
141                         String link = entry.getLink().trim();
142                         articles = getArticlesForUpdate(cat);
143                         if (exists(link, articles)) {
144                                 LOG.fine("addArticles " + link + " is already present");
145                                 continue ;
146                         }
147                         
148                         final Instant instant = getArticleInstant(entry);
149                         
150                         if (config.isObsolete(instant))
151                                 continue ;
152                         
153                         a = ArticleStore.singleton.getArticle(link, ()->toArticle(link, entry, feed, cat.getLanguage(), instant));
154                         
155                         synchronized (articles) {
156                                 articles.add(a);
157
158                                 Collections.sort(articles, new Comparator<Article>() {
159                                         @Override
160                                         public int compare(Article o1, Article o2) {
161                                                 if (o1.publicationDate == o2.publicationDate)
162                                                         return 0;
163                                                 if (o1.publicationDate == null)
164                                                         return 1;
165                                                 if (o2.publicationDate == null)
166                                                         return -1;
167                                                 return o2.publicationDate.compareTo(o1.publicationDate);
168                                         }
169                                 });
170                         }
171                 }          
172                 
173                 LOG.info("addArticles done " + cat.getLabel());
174         }
175              
176         private void retrieveArticles(Category cat) throws IllegalArgumentException, MalformedURLException, FeedException, IOException {
177                 List<Feed> feeds;
178                 
179                 feeds = config.getFeedsByCategory().get(cat);
180                 
181                 if (feeds != null)
182                         for (Feed f: feeds)
183                                 try {
184                                         addArticles(cat, getSyndFeed(f.getURL()));
185                                 } catch (Throwable e) {
186                                         LOG.log(Level.SEVERE,
187                                                 "retrieveArticles failure " + cat.getLabel() + " " + f.toString(),
188                                                 e);
189                                 }
190                 else
191                         LOG.severe("No feed for category " + cat);
192         }
193         
194         /**
195          * Returns a copy.
196          */
197         public List<Article> getArticles(Category cat, String entity)
198                         throws IllegalArgumentException, MalformedURLException, FeedException, IOException {
199                 List<Article> articles, result;                
200                 
201                 synchronized (articlesByCategory) {
202                         articles = getArticlesForUpdate(cat);
203                 }
204                 
205                 synchronized (articles) {                       
206                         if (entity == null)
207                                 return new ArrayList<>(articles);
208                         
209                         result = new ArrayList<>(articles.size());
210                         for (Article a: articles)
211                                 if (a.hasEntity(entity))
212                                         result.add(a);
213                         
214                         return result;
215                 }
216         }
217         
218         public List<EntityStat> getEntityStats(Category cat) throws IllegalArgumentException, MalformedURLException, FeedException, IOException {
219                 List<Article> articles;
220                 Map<String, EntityStat> entities;
221                 final String FUNCTION_NAME = "getEntities";
222                 EntityStat s;
223                 List<EntityStat> stats;
224                 Instant minInstant;
225                 
226                 LOG.entering(CLASS_NAME, FUNCTION_NAME, cat);
227                 
228                 articles = getArticles(cat, null);
229                 
230                 minInstant = Instant.now().minus(15, ChronoUnit.DAYS);
231                 
232                 entities = new HashMap<>();
233                 for (Article a: articles)
234                         if (a.getPublicationDate().isAfter(minInstant) && a.getEntities() != null)
235                                 for (String e: a.getEntities()) {
236                                         s = entities.get(e);
237                                         if (s == null) {
238                                                 s = new EntityStat(e);
239                                                 entities.put(e,  s);
240                                         }
241                                         s.increment();
242                                 }                
243                
244                 stats = new ArrayList<>(entities.values());
245                 stats.sort(new Comparator<EntityStat>() {
246
247                         @Override
248                         public int compare(EntityStat o1, EntityStat o2) {
249                                 return Integer.compare(o2.getCount(), o1.getCount());
250                         }
251                         
252                 });
253                 
254                 LOG.exiting(CLASS_NAME, FUNCTION_NAME, stats);
255                 
256                 return stats;
257         }
258         
259         private class Refresher implements Runnable {
260                 private final Category category;
261                 
262                 public Refresher(Category category) {
263                         this.category = category;
264                 }
265                 
266                 @Override
267                 public void run() {                       
268                         LOG.info("refresher "+ category.getLabel());
269                         
270                         try {
271                                 retrieveArticles(category);
272                         } catch (IllegalArgumentException | FeedException | IOException e) {
273                                 LOG.log(Level.SEVERE, "refresher failure", e);
274                         }                        
275                         
276                         LOG.info("refresher "+ category.getLabel() + " done");
277                 }                
278         }
279 }