source: SRUAggregator/trunk/src/main/java/eu/clarin/sru/fcs/aggregator/app/Aggregator.java @ 5919

Last change on this file since 5919 was 5919, checked in by emanuel.dima@uni-tuebingen.de, 9 years ago
  1. alpha11: UI refactor
File size: 11.7 KB
Line 
1package eu.clarin.sru.fcs.aggregator.app;
2
3import com.fasterxml.jackson.databind.ObjectMapper;
4import com.optimaize.langdetect.LanguageDetector;
5import com.optimaize.langdetect.LanguageDetectorBuilder;
6import com.optimaize.langdetect.ngram.NgramExtractors;
7import com.optimaize.langdetect.profiles.LanguageProfile;
8import com.optimaize.langdetect.profiles.LanguageProfileReader;
9import com.optimaize.langdetect.text.*;
10import eu.clarin.sru.fcs.aggregator.search.Search;
11import eu.clarin.sru.fcs.aggregator.scan.ScanCrawlTask;
12import eu.clarin.sru.fcs.aggregator.scan.Corpora;
13import eu.clarin.sru.client.SRUVersion;
14import eu.clarin.sru.client.fcs.ClarinFCSClientBuilder;
15import eu.clarin.sru.fcs.aggregator.client.ThrottledClient;
16import eu.clarin.sru.fcs.aggregator.scan.Corpus;
17import eu.clarin.sru.fcs.aggregator.rest.RestService;
18import eu.clarin.sru.fcs.aggregator.scan.Statistics;
19import eu.clarin.sru.fcs.aggregator.lang.LanguagesISO693_3;
20import io.dropwizard.Application;
21import io.dropwizard.assets.AssetsBundle;
22import io.dropwizard.setup.Bootstrap;
23import io.dropwizard.setup.Environment;
24import java.io.File;
25import java.io.IOException;
26import java.io.InputStream;
27import java.util.Collections;
28import java.util.HashMap;
29import java.util.List;
30import java.util.Map;
31import java.util.concurrent.ExecutorService;
32import java.util.concurrent.Executors;
33import java.util.concurrent.ScheduledExecutorService;
34import java.util.concurrent.atomic.AtomicReference;
35import opennlp.tools.tokenize.TokenizerModel;
36import org.slf4j.LoggerFactory;
37
38/**
39 * Main component of the Aggregator application intended to provide users access
40 * to CLARIN-FCS resources.
41 *
42 * The webapp base URL corresponds to the default behavior of displaying the
43 * main aggregator page, where the user can enter query, select the resources of
44 * CQL endpoints (as specified in the Clarin center registry), and search in
45 * these resources. The endpoints/resources selection is optional, by default
46 * all the endpoints root resources are selected.
47 *
48 * If invoked with 'x-aggregation-context' and 'query' parameter, the aggregator
49 * will pre-select provided resources and fill in the query field. This
50 * mechanism is currently used by VLO. Example: POST
51 * http://weblicht.sfs.uni-tuebingen.de/Aggregator HTTP/1.1 operation =
52 * searchRetrieve & version = 1.2 & query = bellen & x-aggregation-context =
53 * {"http://fedora.clarin-d.uni-saarland.de/sru/":["hdl:11858/00-246C-0000-0008-5F2A-0"]}
54 *
55 *
56 * Additionally, if run with the a URL query string parameter 'mode', the
57 * special behavior of the aggregator is triggered:
58 *
59 * /?mode=testing corresponds to the mode where the CQL endpoints are taken not
60 * from Clarin center repository, but from a hard-coded endpoints list; this
61 * functionality is useful for testing the development instances of endpoints,
62 * before they are moved to production. Was done to meet the request from MPI.
63 *
64 * /?mode=search corresponds to the mode where the aggregator page is requested
65 * with the already known query and (optionally) resources to search in, and if
66 * the immediate search is desired. In this case the aggregator search results
67 * page is displayed and search results of the provided query start to fill it
68 * in immediately (i.e. users don't need to click 'search' in the aggregator
69 * page). Was done to meet the request from CLARIN ERIC (Martin Wynne contacted
70 * us).
71 *
72 * /?mode=live corresponds to the mode where the information about corpora are
73 * taken not from the scan cache (crawled in advance), but loaded live, starting
74 * from the request to center registry and then performing scan operation
75 * requests on each CQL endpoint listed there. It takes time to get the
76 * corresponding responses from the endpoints, therefore the Aggregator page
77 * loads very slow in this mode. But this mode is useful for testing of the
78 * newly added or changed corpora without waiting for the next crawl.
79 *
80 *
81 * Adds Application initialization and clean up: only one SRU threaded client is
82 * used in the application, it has to be shut down when the application stops.
83 * One Languages object instance is used within the application.
84 *
85 * @author Yana Panchenko
86 * @author edima
87 *
88 * TODO: try to refine results by language using a language library, with UI
89 * element
90 *
91 * TODO: condensed list of corpora
92 *
93 * TODO: group the list of corpora by institution?
94 *
95 * TODO: fix ordering of corpora in corpora view
96 *
97 * TODO: corpora search should not indicate the ones that don't match
98 *
99 * TODO: Collections view: home link (make a single consistent text for it)
100 *
101 * TODO: tri-state for parent collections; search + message implications
102 *
103 * TODO: version page: credits, open source, see vcr/version page
104 *
105 * TODO: statistics page liked from version page
106 *
107 * TODO: 1. support new spec-compatible centres, see Oliver's mail
108 * (use SRUClient's extraResponseData POJOs)
109 *
110 * TODO: 2. zoom into the results from a corpus, allow functionality only for
111 * the view (search for next set of results)
112 *
113 * TODO: disable popups easily
114 *
115 * TODO: Fix activeSearch memory leak (gc searches older than...)
116 *
117 * TODO: Use weblicht with results
118 *
119 * TODO: Export to personal workspace as csv, excel, tcf, plain text
120 *
121 * TODO: Download to personal workspace as csv, excel, tcf, plain text
122 *
123 * TODO: websockets
124 *
125 * TODO: atomic replace of cached corpora (file)
126 *
127 * TODO: show multiple hits on the same result in multiple rows, linked visually
128 *
129 * TODO: optimise page load
130 *
131 * TODO: improve help page text
132 *
133 */
134public class Aggregator extends Application<AggregatorConfiguration> {
135
136        private static final org.slf4j.Logger log = LoggerFactory.getLogger(Aggregator.class);
137
138        public static final String DE_TOK_MODEL = "tokenizer/de-tuebadz-8.0-token.bin";
139
140        private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
141        private static Aggregator instance;
142        private AggregatorConfiguration.Params params;
143
144        private AtomicReference<Corpora> scanCacheAtom = new AtomicReference<Corpora>(new Corpora());
145        private AtomicReference<Statistics> scanStatsAtom = new AtomicReference<Statistics>(new Statistics());
146        private AtomicReference<Statistics> searchStatsAtom = new AtomicReference<Statistics>(new Statistics());
147
148        private TokenizerModel tokenizerModel;
149        private LanguageDetector languageDetector;
150        private TextObjectFactory textObjectFactory;
151
152        private ThrottledClient sruScanClient = null;
153        private ThrottledClient sruSearchClient = null;
154        private Map<Long, Search> activeSearches = Collections.synchronizedMap(new HashMap<Long, Search>());
155
156        public static void main(String[] args) throws Exception {
157                new Aggregator().run(args);
158        }
159
160        @Override
161        public String getName() {
162                return "FCS Aggregator";
163        }
164
165        @Override
166        public void initialize(Bootstrap<AggregatorConfiguration> bootstrap) {
167                bootstrap.addBundle(new AssetsBundle("/assets", "/", "index.html"));
168        }
169
170        @Override
171        public void run(AggregatorConfiguration config, Environment environment) throws Exception {
172                params = config.aggregatorParams;
173                instance = this;
174
175                System.out.println("Using parameters: ");
176                try {
177                        System.out.println(new ObjectMapper().writerWithDefaultPrettyPrinter().
178                                        writeValueAsString(config.aggregatorParams));
179                } catch (IOException xc) {
180                }
181
182                environment.jersey().setUrlPattern("/rest/*");
183                environment.jersey().register(new RestService());
184
185                try {
186                        init();
187                } catch (Exception ex) {
188                        log.error("INIT EXCEPTION", ex);
189                        throw ex; // force exit
190                }
191        }
192
193        public static Aggregator getInstance() {
194                return instance;
195        }
196
197        public AggregatorConfiguration.Params getParams() {
198                return params;
199        }
200
201        public Corpora getCorpora() {
202                return scanCacheAtom.get();
203        }
204
205        public Statistics getScanStatistics() {
206                return scanStatsAtom.get();
207        }
208
209        public Statistics getSearchStatistics() {
210                return searchStatsAtom.get();
211        }
212
213        public void init() throws IOException {
214                log.info("Aggregator initialization started.");
215                sruScanClient = new ThrottledClient(
216                                new ClarinFCSClientBuilder()
217                                .setConnectTimeout(params.ENDPOINTS_SCAN_TIMEOUT_MS)
218                                .setSocketTimeout(params.ENDPOINTS_SCAN_TIMEOUT_MS)
219                                .addDefaultDataViewParsers()
220                                .enableLegacySupport()
221                                .buildThreadedClient(),
222                                params.SCAN_MAX_CONCURRENT_REQUESTS_PER_ENDPOINT,
223                                params.SEARCH_MAX_CONCURRENT_REQUESTS_PER_ENDPOINT
224                );
225                sruSearchClient = new ThrottledClient(
226                                new ClarinFCSClientBuilder()
227                                .setConnectTimeout(params.ENDPOINTS_SEARCH_TIMEOUT_MS)
228                                .setSocketTimeout(params.ENDPOINTS_SEARCH_TIMEOUT_MS)
229                                .addDefaultDataViewParsers()
230                                .enableLegacySupport()
231                                .buildThreadedClient(),
232                                params.SCAN_MAX_CONCURRENT_REQUESTS_PER_ENDPOINT,
233                                params.SEARCH_MAX_CONCURRENT_REQUESTS_PER_ENDPOINT
234                );
235
236                File corporaCacheFile = new File(params.AGGREGATOR_FILE_PATH);
237                try {
238                        Corpora corpora = new ObjectMapper().readValue(corporaCacheFile, Corpora.class);
239                        scanCacheAtom.set(corpora);
240                        log.info("corpus list read from file; number of root corpora: " + scanCacheAtom.get().getCorpora().size());
241                } catch (Exception e) {
242                        log.error("Error while reading cached corpora:", e);
243                }
244
245                LanguagesISO693_3.getInstance(); // force init
246                initTokenizer();
247                initLanguageDetector();
248
249                ScanCrawlTask task = new ScanCrawlTask(sruScanClient,
250                                params.CENTER_REGISTRY_URL, params.SCAN_MAX_DEPTH,
251                                null, scanCacheAtom, corporaCacheFile, scanStatsAtom);
252                scheduler.scheduleAtFixedRate(task, params.SCAN_TASK_INITIAL_DELAY,
253                                params.SCAN_TASK_INTERVAL, params.getScanTaskTimeUnit());
254
255                log.info("Aggregator initialization finished.");
256        }
257
258        public void shutdown(AggregatorConfiguration config) {
259                log.info("Aggregator is shutting down.");
260                for (Search search : activeSearches.values()) {
261                        search.shutdown();
262                }
263                shutdownAndAwaitTermination(config.aggregatorParams, sruScanClient, scheduler);
264                shutdownAndAwaitTermination(config.aggregatorParams, sruSearchClient, scheduler);
265                log.info("Aggregator shutdown complete.");
266        }
267
268        // this function should be thread-safe
269        public Search startSearch(SRUVersion version, List<Corpus> corpora, String searchString, String searchLang, int maxRecords) throws Exception {
270                if (corpora.isEmpty()) {
271                        // No corpora
272                        return null;
273                } else if (searchString.isEmpty()) {
274                        // No query
275                        return null;
276                } else {
277                        Search sr = new Search(sruSearchClient, version, searchStatsAtom.get(),
278                                        corpora, searchString, searchLang, 1, maxRecords);
279                        activeSearches.put(sr.getId(), sr);
280                        return sr;
281                }
282        }
283
284        public Search getSearchById(Long id) {
285                return activeSearches.get(id);
286        }
287
288        private static void shutdownAndAwaitTermination(AggregatorConfiguration.Params params,
289                        ThrottledClient sruClient, ExecutorService scheduler) {
290                try {
291                        sruClient.shutdown();
292                        scheduler.shutdown();
293                        Thread.sleep(params.EXECUTOR_SHUTDOWN_TIMEOUT_MS);
294                        sruClient.shutdownNow();
295                        scheduler.shutdownNow();
296                        Thread.sleep(params.EXECUTOR_SHUTDOWN_TIMEOUT_MS);
297                } catch (InterruptedException ie) {
298                        sruClient.shutdownNow();
299                        scheduler.shutdownNow();
300                        Thread.currentThread().interrupt();
301                }
302        }
303
304        private void initTokenizer() {
305                TokenizerModel model = null;
306                try {
307                        try (InputStream tokenizerModelDeAsIS = Thread.currentThread().getContextClassLoader().getResourceAsStream(DE_TOK_MODEL)) {
308                                model = new TokenizerModel(tokenizerModelDeAsIS);
309                        }
310                } catch (IOException ex) {
311                        log.error("Failed to load tokenizer model", ex);
312                }
313                tokenizerModel = model;
314        }
315
316        public void initLanguageDetector() throws IOException {
317                List<LanguageProfile> languageProfiles = new LanguageProfileReader().readAll();
318                languageDetector = LanguageDetectorBuilder
319                                .create(NgramExtractors.standard())
320                                .withProfiles(languageProfiles)
321                                .build();
322
323                textObjectFactory = CommonTextObjectFactories.forDetectingOnLargeText();
324        }
325
326        public String detectLanguage(String text) {
327                return languageDetector.detect(textObjectFactory.forText(text)).orNull();
328        }
329}
Note: See TracBrowser for help on using the repository browser.