fixed computing of entities when the article does not have a description
[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 (lang.equals("en"))
121                         try {
122                                 NER.classify(title, entities, config);
123                                 if (desc != null)
124                                         NER.classify(desc, entities, config);
125                         } catch (ClassCastException | ClassNotFoundException | IOException e1) {
126                                 LOG.log(Level.SEVERE, "Cannot classify " + feedTitle, e1);                         
127                         }
128                 
129                 return new Article(link, title, desc, thumbnail, instant, feedTitle, entities.toArray(new String[0]));
130         }
131         
132         private void addArticles(Category cat, SyndFeed feed) {
133                 String feedTitle;
134                 List<Article> articles;
135                 Article a;
136                 
137                 feedTitle = feed.getTitle().trim();
138                 
139                 LOG.info("addArticles " + cat.getLabel() + " " + feedTitle + " number of articles: " + feed.getEntries().size());
140                 
141                 for (SyndEntry entry: feed.getEntries()) {
142                         String link = entry.getLink().trim();
143                         articles = getArticlesForUpdate(cat);
144                         if (exists(link, articles)) {
145                                 LOG.fine("addArticles " + link + " is already present");
146                                 continue ;
147                         }
148                         
149                         final Instant instant = getArticleInstant(entry);
150                         
151                         if (config.isObsolete(instant))
152                                 continue ;
153                         
154                         a = ArticleStore.singleton.getArticle(link, ()->toArticle(link, entry, feed, cat.getLanguage(), instant));
155                         
156                         synchronized (articles) {
157                                 articles.add(a);
158
159                                 Collections.sort(articles, new Comparator<Article>() {
160                                         @Override
161                                         public int compare(Article o1, Article o2) {
162                                                 if (o1.publicationDate == o2.publicationDate)
163                                                         return 0;
164                                                 if (o1.publicationDate == null)
165                                                         return 1;
166                                                 if (o2.publicationDate == null)
167                                                         return -1;
168                                                 return o2.publicationDate.compareTo(o1.publicationDate);
169                                         }
170                                 });
171                         }
172                 }          
173                 
174                 LOG.info("addArticles done " + cat.getLabel());
175         }
176              
177         private void retrieveArticles(Category cat) throws IllegalArgumentException, MalformedURLException, FeedException, IOException {
178                 List<Feed> feeds;
179                 
180                 feeds = config.getFeedsByCategory().get(cat);
181                 
182                 if (feeds != null)
183                         for (Feed f: feeds)
184                                 try {
185                                         addArticles(cat, getSyndFeed(f.getURL()));
186                                 } catch (Throwable e) {
187                                         LOG.log(Level.SEVERE,
188                                                 "retrieveArticles failure " + cat.getLabel() + " " + f.toString(),
189                                                 e);
190                                 }
191                 else
192                         LOG.severe("No feed for category " + cat);
193         }
194         
195         /**
196          * Returns a copy.
197          */
198         public List<Article> getArticles(Category cat, String entity)
199                         throws IllegalArgumentException, MalformedURLException, FeedException, IOException {
200                 List<Article> articles, result;                
201                 
202                 synchronized (articlesByCategory) {
203                         articles = getArticlesForUpdate(cat);
204                 }
205                 
206                 synchronized (articles) {                       
207                         if (entity == null)
208                                 return new ArrayList<>(articles);
209                         
210                         result = new ArrayList<>(articles.size());
211                         for (Article a: articles)
212                                 if (a.hasEntity(entity))
213                                         result.add(a);
214                         
215                         return result;
216                 }
217         }
218         
219         public List<EntityStat> getEntityStats(Category cat) throws IllegalArgumentException, MalformedURLException, FeedException, IOException {
220                 List<Article> articles;
221                 Map<String, EntityStat> entities;
222                 final String FUNCTION_NAME = "getEntities";
223                 EntityStat s;
224                 List<EntityStat> stats;
225                 Instant minInstant;
226                 
227                 LOG.entering(CLASS_NAME, FUNCTION_NAME, cat);
228                 
229                 articles = getArticles(cat, null);
230                 
231                 minInstant = Instant.now().minus(15, ChronoUnit.DAYS);
232                 
233                 entities = new HashMap<>();
234                 for (Article a: articles)
235                         if (a.getPublicationDate().isAfter(minInstant) && a.getEntities() != null)
236                                 for (String e: a.getEntities()) {
237                                         s = entities.get(e);
238                                         if (s == null) {
239                                                 s = new EntityStat(e);
240                                                 entities.put(e,  s);
241                                         }
242                                         s.increment();
243                                 }                
244                
245                 stats = new ArrayList<>(entities.values());
246                 stats.sort(new Comparator<EntityStat>() {
247
248                         @Override
249                         public int compare(EntityStat o1, EntityStat o2) {
250                                 return Integer.compare(o2.getCount(), o1.getCount());
251                         }
252                         
253                 });
254                 
255                 LOG.exiting(CLASS_NAME, FUNCTION_NAME, stats);
256                 
257                 return stats;
258         }
259         
260         private class Refresher implements Runnable {
261                 private final Category category;
262                 
263                 public Refresher(Category category) {
264                         this.category = category;
265                 }
266                 
267                 @Override
268                 public void run() {                       
269                         LOG.info("refresher "+ category.getLabel());
270                         
271                         try {
272                                 retrieveArticles(category);
273                         } catch (IllegalArgumentException | FeedException | IOException e) {
274                                 LOG.log(Level.SEVERE, "refresher failure", e);
275                         }                        
276                         
277                         LOG.info("refresher "+ category.getLabel() + " done");
278                 }                
279         }
280 }