1 package net.wpitchoune.pnews.servlet;
3 import java.io.IOException;
4 import java.net.MalformedURLException;
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;
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;
21 import org.jsoup.Jsoup;
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;
30 import net.wpitchoune.pnews.Article;
31 import net.wpitchoune.pnews.ArticleStore;
32 import net.wpitchoune.pnews.Category;
33 import net.wpitchoune.pnews.Config;
34 import net.wpitchoune.pnews.EntityStat;
35 import net.wpitchoune.pnews.Feed;
36 import net.wpitchoune.pnews.classifier.NamedEntityRecognizer;
38 public class ArticleProvider {
39 private static final String CLASS_NAME = ArticleProvider.class.getName();
40 private static final Logger LOG = Logger.getLogger(CLASS_NAME);
41 private final Map<Category, List<Article>> articlesByCategory = new HashMap<>();
42 private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());
43 private final Config config;
45 public ArticleProvider(Config config) {
47 for (Category cat: config.getCategories())
48 scheduler.scheduleAtFixedRate(new Refresher(cat), 2, 600, TimeUnit.SECONDS);
51 private static SyndFeed getSyndFeed(String u) throws IllegalArgumentException, FeedException, MalformedURLException, IOException {
54 r = new XmlReader(new URL(u));
56 return new SyndFeedInput().build(r);
59 private List<Article> getArticlesForUpdate(Category cat) {
62 synchronized (articlesByCategory) {
63 result = articlesByCategory.get(cat);
65 result = new ArrayList<>();
66 articlesByCategory.put(cat, result);
72 private boolean exists(String articleLink, List<Article> articles) {
73 synchronized (articles) {
74 for (Article a: articles)
75 if (a.getLink().equals(articleLink))
81 private Instant getArticleInstant(SyndEntry entry) {
84 date = entry.getUpdatedDate();
86 date = entry.getPublishedDate();
91 return date.toInstant();
94 private Article toArticle(String link, SyndEntry entry, SyndFeed feed, String lang, Instant instant) {
95 String desc, title, thumbnail, feedTitle, str;
96 List<String> entities;
98 feedTitle = feed.getTitle();
99 if (feedTitle != null) {
100 feedTitle = feedTitle.trim();
104 for (SyndEnclosure e: entry.getEnclosures()) {
105 if (e.getType().startsWith("image/"))
106 thumbnail = e.getUrl();
110 title = entry.getTitle().trim();
112 if (entry.getDescription() != null) {
113 str = entry.getDescription().getValue();
114 desc = Jsoup.parse(str).text();
117 LOG.severe("No description for " + feedTitle + " - " + title);
120 entities = new ArrayList<>();
121 if (lang.equals("en"))
123 NamedEntityRecognizer.classify(title, entities, config);
125 NamedEntityRecognizer.classify(desc, entities, config);
126 } catch (ClassCastException | ClassNotFoundException | IOException e1) {
127 LOG.log(Level.SEVERE, "Cannot classify " + feedTitle, e1);
130 return new Article(link, title, desc, thumbnail, instant, feedTitle, entities.toArray(new String[0]));
133 private void addArticles(Category cat, SyndFeed feed) {
135 List<Article> articles;
138 feedTitle = feed.getTitle().trim();
140 LOG.info("addArticles " + cat.getLabel() + " " + feedTitle + " number of articles: " + feed.getEntries().size());
142 for (SyndEntry entry: feed.getEntries()) {
143 String link = entry.getLink().trim();
144 articles = getArticlesForUpdate(cat);
145 if (exists(link, articles)) {
146 LOG.fine("addArticles " + link + " is already present");
150 final Instant instant = getArticleInstant(entry);
152 if (config.isObsolete(instant))
155 a = ArticleStore.singleton.getArticle(link, ()->toArticle(link, entry, feed, cat.getLanguage(), instant));
157 synchronized (articles) {
160 Collections.sort(articles, new Comparator<Article>() {
162 public int compare(Article o1, Article o2) {
163 if (o1.getPublicationDate() == o2.getPublicationDate())
165 if (o1.getPublicationDate() == null)
167 if (o2.getPublicationDate() == null)
169 return o2.getPublicationDate().compareTo(o1.getPublicationDate());
175 LOG.info("addArticles done " + cat.getLabel());
178 private void retrieveArticles(Category cat) throws IllegalArgumentException, MalformedURLException, FeedException, IOException {
181 feeds = config.getFeedsByCategory().get(cat);
186 addArticles(cat, getSyndFeed(f.getURL()));
187 } catch (Throwable e) {
188 LOG.log(Level.SEVERE,
189 "retrieveArticles failure " + cat.getLabel() + " " + f.toString(),
193 LOG.severe("No feed for category " + cat);
199 public List<Article> getArticles(Category cat, String entity)
200 throws IllegalArgumentException, MalformedURLException, FeedException, IOException {
201 List<Article> articles, result;
203 synchronized (articlesByCategory) {
204 articles = getArticlesForUpdate(cat);
207 synchronized (articles) {
209 return new ArrayList<>(articles);
211 result = new ArrayList<>(articles.size());
212 for (Article a: articles)
213 if (a.hasEntity(entity))
220 public List<EntityStat> getEntityStats(Category cat) throws IllegalArgumentException, MalformedURLException, FeedException, IOException {
221 List<Article> articles;
222 Map<String, EntityStat> entities;
223 final String FUNCTION_NAME = "getEntities";
225 List<EntityStat> stats;
228 LOG.entering(CLASS_NAME, FUNCTION_NAME, cat);
230 articles = getArticles(cat, null);
232 minInstant = Instant.now().minus(15, ChronoUnit.DAYS);
234 entities = new HashMap<>();
235 for (Article a: articles)
236 if (a.getPublicationDate().isAfter(minInstant) && a.getEntities() != null)
237 for (String e: a.getEntities()) {
240 s = new EntityStat(e);
246 stats = new ArrayList<>(entities.values());
247 stats.sort(new Comparator<EntityStat>() {
250 public int compare(EntityStat o1, EntityStat o2) {
251 return Integer.compare(o2.getCount(), o1.getCount());
256 LOG.exiting(CLASS_NAME, FUNCTION_NAME, stats);
261 private class Refresher implements Runnable {
262 private final Category category;
264 public Refresher(Category category) {
265 this.category = category;
270 LOG.info("refresher "+ category.getLabel());
273 retrieveArticles(category);
274 } catch (IllegalArgumentException | FeedException | IOException e) {
275 LOG.log(Level.SEVERE, "refresher failure", e);
278 LOG.info("refresher "+ category.getLabel() + " done");