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