/* Return early on cancellation */
if (monitor.isCanceled() || Owl.isShuttingDown())
return false;
/* Need to index News and perform Searches */
RAMDirectory directory = null;
final IndexSearcher[] searcher = new IndexSearcher[1];
if (needToIndex(enabledFilters)) {
boolean indexDescription = needToIndexDescription(enabledFilters);
directory = new RAMDirectory();
directory.setLockFactory(NoLockFactory.getNoLockFactory());
/* Index News */
try {
IndexWriter indexWriter = new IndexWriter(directory, Indexer.createAnalyzer());
for (int i = 0; i < news.size(); i++) {
/* Return early on cancellation */
if (monitor.isCanceled() || Owl.isShuttingDown())
return false;
NewsDocument document = new NewsDocument(news.get(i));
document.addFields(indexDescription);
document.getDocument().getField(SearchDocument.ENTITY_ID_TEXT).setValue(String.valueOf(i));
indexWriter.addDocument(document.getDocument());
}
indexWriter.close();
searcher[0] = new IndexSearcher(directory);
} catch (Exception e) {
directory.close();
throw e;
}
}
/* Remember the news already filtered */
List<INews> filteredNews = new ArrayList<INews>(news.size());
boolean filterMatchedAll = false;
/* Iterate over Filters */
for (ISearchFilter filter : enabledFilters) {
/* No Search Required */
if (filter.getSearch() == null) {
filterMatchedAll = true;
List<INews> remainingNews = new ArrayList<INews>(news);
remainingNews.removeAll(filteredNews);
if (!remainingNews.isEmpty())
applyFilter(filter, remainingNews);
/* Done - we only support 1 filter per News */
break;
}
/* Search Required */
else if (directory != null && searcher[0] != null) {
/* Return early if cancelled and nothing filtered yet */
if ((monitor.isCanceled() || Owl.isShuttingDown()) && filteredNews.isEmpty())
return false;
try {
final List<INews> matchingNews = new ArrayList<INews>(3);
/* Perform Query */
Query query = ModelSearchQueries.createQuery(filter.getSearch());
searcher[0].search(query, new HitCollector() {
@Override
public void collect(int doc, float score) {
try {
Document document = searcher[0].doc(doc);
int index = Integer.valueOf(document.get(SearchDocument.ENTITY_ID_TEXT));
matchingNews.add(news.get(index));
} catch (CorruptIndexException e) {
Activator.getDefault().logError(e.getMessage(), e);
} catch (IOException e) {
Activator.getDefault().logError(e.getMessage(), e);
}
}
});
/* Apply Filter */
matchingNews.removeAll(filteredNews);
if (!matchingNews.isEmpty()) {
applyFilter(filter, matchingNews);
filteredNews.addAll(matchingNews);
}
} catch (IOException e) {
directory.close();
throw e;
}
}
}
/* Free RAMDirectory if it was built */
if (directory != null)
directory.close();
return filterMatchedAll || !filteredNews.isEmpty();
}