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

Last change on this file since 6065 was 6065, checked in by emanuel.dima@uni-tuebingen.de, 9 years ago
  1. alpha 25: removed unused iso-639-2 support and unused german tokenizer; fixed bug related to xml unencoding; changed weblicht config
File size: 11.8 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.client.fcs.ClarinFCSEndpointDescriptionParser;
16import eu.clarin.sru.fcs.aggregator.client.ThrottledClient;
17import eu.clarin.sru.fcs.aggregator.scan.Corpus;
18import eu.clarin.sru.fcs.aggregator.rest.RestService;
19import eu.clarin.sru.fcs.aggregator.scan.Statistics;
20import eu.clarin.sru.fcs.aggregator.util.LanguagesISO693;
21import io.dropwizard.Application;
22import io.dropwizard.assets.AssetsBundle;
23import io.dropwizard.setup.Bootstrap;
24import io.dropwizard.setup.Environment;
25import java.io.File;
26import java.io.IOException;
27import java.util.ArrayList;
28import java.util.Collections;
29import java.util.HashMap;
30import java.util.List;
31import java.util.Map;
32import java.util.concurrent.ExecutorService;
33import java.util.concurrent.Executors;
34import java.util.concurrent.ScheduledExecutorService;
35import java.util.concurrent.atomic.AtomicReference;
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: ?use weblicht only to show up in zoomed mode
89 * - send only tcf with only a text layer and language (from the list in params)
90 *
91 * TODO: add the modes described above (except live)
92 *
93 * TODO: zoom into the results from a corpus, allow functionality only for
94 * the view (search for next set of results)
95 *
96 * TODO: Export search results to personal workspace as csv, excel, tcf, plain
97 * text: ask Marie/Wei about oauth ways to do that ndg oauth; ask Menzo, Willem,
98 * Twan (they did a test, it worked)
99 *
100 * TODO: add PiWik support, tracking the following:
101 * - visits, searches, search per corpus
102 *
103 * TODO: BUG: language detection is immediate, in UI; export implications
104 *
105 * TODO: websockets
106 *
107 * TODO: show multiple hits on the same result in multiple rows, linked visually
108 *
109 * TODO: optimise page load
110 *
111 * TODO: test it in IE, other browsers
112 *
113 * TODO: tri-state for parent collections; search + message implications
114 *
115 * TODO: improve help page text
116 *
117 */
118public class Aggregator extends Application<AggregatorConfiguration> {
119
120        private static final org.slf4j.Logger log = LoggerFactory.getLogger(Aggregator.class);
121
122        public static final String DE_TOK_MODEL = "tokenizer/de-tuebadz-8.0-token.bin";
123
124        private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
125        private static Aggregator instance;
126        private AggregatorConfiguration.Params params;
127
128        private AtomicReference<Corpora> scanCacheAtom = new AtomicReference<Corpora>(new Corpora());
129        private AtomicReference<Statistics> scanStatsAtom = new AtomicReference<Statistics>(new Statistics());
130        private AtomicReference<Statistics> searchStatsAtom = new AtomicReference<Statistics>(new Statistics());
131
132        private LanguageDetector languageDetector;
133        private TextObjectFactory textObjectFactory;
134
135        private ThrottledClient sruScanClient = null;
136        private ThrottledClient sruSearchClient = null;
137        private Map<Long, Search> activeSearches = Collections.synchronizedMap(new HashMap<Long, Search>());
138
139        public static void main(String[] args) throws Exception {
140                new Aggregator().run(args);
141        }
142
143        @Override
144        public String getName() {
145                return "FCS Aggregator";
146        }
147
148        @Override
149        public void initialize(Bootstrap<AggregatorConfiguration> bootstrap) {
150                bootstrap.addBundle(new AssetsBundle("/assets", "/", "index.html", "static"));
151        }
152
153        @Override
154        public void run(AggregatorConfiguration config, Environment environment) throws Exception {
155                params = config.aggregatorParams;
156                instance = this;
157
158                System.out.println("Using parameters: ");
159                try {
160                        System.out.println(new ObjectMapper().writerWithDefaultPrettyPrinter().
161                                        writeValueAsString(config.aggregatorParams));
162                } catch (IOException xc) {
163                }
164
165                environment.getApplicationContext().setErrorHandler(new ErrorPageHandler());
166                environment.jersey().setUrlPattern("/rest/*");
167                environment.jersey().register(new RestService());
168
169                try {
170                        init();
171                } catch (Exception ex) {
172                        log.error("INIT EXCEPTION", ex);
173                        throw ex; // force exit
174                }
175        }
176
177        public static Aggregator getInstance() {
178                return instance;
179        }
180
181        public AggregatorConfiguration.Params getParams() {
182                return params;
183        }
184
185        public Corpora getCorpora() {
186                return scanCacheAtom.get();
187        }
188
189        public Statistics getScanStatistics() {
190                return scanStatsAtom.get();
191        }
192
193        public Statistics getSearchStatistics() {
194                return searchStatsAtom.get();
195        }
196
197        public void init() throws IOException {
198                log.info("Aggregator initialization started.");
199                sruScanClient = new ThrottledClient(
200                                new ClarinFCSClientBuilder()
201                                .setConnectTimeout(params.ENDPOINTS_SCAN_TIMEOUT_MS)
202                                .setSocketTimeout(params.ENDPOINTS_SCAN_TIMEOUT_MS)
203                                .addDefaultDataViewParsers()
204                                .registerExtraResponseDataParser(
205                                                new ClarinFCSEndpointDescriptionParser())
206                                .enableLegacySupport()
207                                .buildThreadedClient(),
208                                params.SCAN_MAX_CONCURRENT_REQUESTS_PER_ENDPOINT
209                );
210                sruSearchClient = new ThrottledClient(
211                                new ClarinFCSClientBuilder()
212                                .setConnectTimeout(params.ENDPOINTS_SEARCH_TIMEOUT_MS)
213                                .setSocketTimeout(params.ENDPOINTS_SEARCH_TIMEOUT_MS)
214                                .addDefaultDataViewParsers()
215                                .enableLegacySupport()
216                                .buildThreadedClient(),
217                                params.SEARCH_MAX_CONCURRENT_REQUESTS_PER_ENDPOINT
218                );
219
220                File corporaCacheFile = new File(params.AGGREGATOR_FILE_PATH);
221                File corporaOldCacheFile = new File(params.AGGREGATOR_FILE_PATH_BACKUP);
222
223                // init corpora from file
224                {
225                        Corpora corpora = null;
226                        try {
227                                corpora = new ObjectMapper().readValue(corporaCacheFile, Corpora.class);
228                        } catch (Exception xc) {
229                                log.error("Failed to load cached corpora from primary file:", xc);
230                        }
231                        if (corpora == null) {
232                                try {
233                                        corpora = new ObjectMapper().readValue(corporaOldCacheFile, Corpora.class);
234                                } catch (Exception e) {
235                                        log.error("Failed to load cached corpora from backup file:", e);
236                                }
237                        }
238                        if (corpora != null) {
239                                scanCacheAtom.set(corpora);
240                                log.info("corpus list read from file; number of root corpora: " + scanCacheAtom.get().getCorpora().size());
241                        }
242                }
243
244                LanguagesISO693.getInstance(); // force init
245                initLanguageDetector();
246
247                ScanCrawlTask task = new ScanCrawlTask(sruScanClient,
248                                params.CENTER_REGISTRY_URL, params.SCAN_MAX_DEPTH,
249                                params.additionalCQLEndpoints,
250                                null, scanCacheAtom, corporaCacheFile, corporaOldCacheFile,
251                                scanStatsAtom, searchStatsAtom);
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,
270                        String searchString, String searchLang, int maxRecords) throws Exception {
271                if (corpora.isEmpty()) {
272                        // No corpora
273                        return null;
274                } else if (searchString.isEmpty()) {
275                        // No query
276                        return null;
277                } else {
278                        Search sr = new Search(sruSearchClient, version, searchStatsAtom.get(),
279                                        corpora, searchString, searchLang, 1, maxRecords);
280                        if ((activeSearches.size() % 100) == 0) {
281                                List<Long> toBeRemoved = new ArrayList<Long>();
282                                long t0 = System.currentTimeMillis();
283                                for (Map.Entry<Long, Search> e : activeSearches.entrySet()) {
284                                        if (t0 - e.getValue().getCreatedAt() > 1800 * 1000) {
285                                                toBeRemoved.add(e.getKey());
286                                        }
287                                }
288                                for (Long l : toBeRemoved) {
289                                        activeSearches.remove(l);
290                                }
291                        }
292                        activeSearches.put(sr.getId(), sr);
293                        return sr;
294                }
295        }
296
297        public Search getSearchById(Long id) {
298                return activeSearches.get(id);
299        }
300
301        private static void shutdownAndAwaitTermination(AggregatorConfiguration.Params params,
302                        ThrottledClient sruClient, ExecutorService scheduler) {
303                try {
304                        sruClient.shutdown();
305                        scheduler.shutdown();
306                        Thread.sleep(params.EXECUTOR_SHUTDOWN_TIMEOUT_MS);
307                        sruClient.shutdownNow();
308                        scheduler.shutdownNow();
309                        Thread.sleep(params.EXECUTOR_SHUTDOWN_TIMEOUT_MS);
310                } catch (InterruptedException ie) {
311                        sruClient.shutdownNow();
312                        scheduler.shutdownNow();
313                        Thread.currentThread().interrupt();
314                }
315        }
316
317        public void initLanguageDetector() throws IOException {
318                List<LanguageProfile> languageProfiles = new LanguageProfileReader().readAll();
319                languageDetector = LanguageDetectorBuilder
320                                .create(NgramExtractors.standard())
321                                .withProfiles(languageProfiles)
322                                .build();
323
324                textObjectFactory = CommonTextObjectFactories.forDetectingOnLargeText();
325        }
326
327        public String detectLanguage(String text) {
328                return languageDetector.detect(textObjectFactory.forText(text)).orNull();
329        }
330}
Note: See TracBrowser for help on using the repository browser.