1
2
3
4
5
6
7 package org.astrogrid.datacenter.queriers;
8
9 import org.astrogrid.datacenter.queriers.status.*;
10
11 import java.io.IOException;
12 import java.util.Date;
13 import java.util.Vector;
14 import org.apache.commons.logging.Log;
15 import org.astrogrid.community.Account;
16 import org.astrogrid.datacenter.delegate.DatacenterException;
17 import org.astrogrid.datacenter.query.Query;
18 import org.astrogrid.datacenter.slinger.Slinger;
19
20 /***
21 * Represents a single running query.
22 *
23 * <p>
24 * If two queries will be made on a database, two Querier instances
25 * will be required.
26 * <p>
27 * It is a very abstract class meant to help administer
28 * the queries - concrete subclasses take care of the details of performing the query.
29 * <p>
30 * @see package documentation
31 * <p>
32 * This class provides factory methods for both blocking and non-blocking
33 * queries, hopefully completely hiding the two-way translation process
34 *
35 * @see doQueryGetVotable()
36 * @see spawnQuery
37 * <p>
38 * @author M Hill
39 */
40
41 public class Querier implements Runnable, PluginListener {
42
43
44 protected static final Log log = org.apache.commons.logging.LogFactory.getLog(Querier.class);
45
46 /*** query to perform */
47 private final Query query;
48
49 /*** A handle is used to identify a particular query. It is also used as the
50 * basis for any temporary storage. */
51 private final String id;
52
53 /*** On whose behalf is this querier running */
54 private final Account user;
55
56 /*** Plugin to run */
57 private QuerierPlugin plugin;
58
59 /*** List of listeners who will be updated when the status changes */
60 private Vector listeners = new Vector();
61
62 /*** status of query */
63 private QuerierStatus status;
64
65 /*** true if abort called */
66 private boolean aborted = false;
67
68 /*** Represents what created this querier */
69 private Object source = null;
70
71 /*** For measuring how long the query took - calculated from status change times*/
72
73 /*** For measuring how long query took - calculated from status change times*/
74
75 /*** For measuring how long query took - calculated from status change times*/
76
77
78 /*** temporary used for generating unique handles - see generateHandle() */
79 private static java.util.Random random = new java.util.Random();
80
81
82 /*** This is private so that if the mechanism changes and we make the plugins
83 subclasses of queriers, for example, then we don't have to change the rest of the
84 * code. The query includes details about the results, and the 'aSource' is just
85 * used to indicate where the querier came from - eg a test class, or JSPs, or
86 * CEA, etc */
87 private Querier(Account forUser, Query query, Object aSource) throws IOException {
88 this.id = generateQueryId();
89 this.user = forUser;
90 this.query = query;
91 this.source = aSource;
92
93
94 plugin = QuerierPluginFactory.createPlugin(this);
95
96 setStatus(new QuerierConstructed(this));
97 if (source != null) {
98 status.addDetail("Source: "+source.toString());
99 }
100
101
102
103
104 if (query.getResultsDef() != null)
105 {
106 Slinger.testConnection(query.getTarget(), user);
107 }
108
109
110 }
111
112 /*** Factory method. Query includes the results definition, and 'source' represents
113 * what clas was used to create this querier (optional) */
114 public static Querier makeQuerier(Account forUser, Query query, Object source) throws IOException {
115 if (source != null) {
116 source = source.getClass();
117 }
118
119 Querier querier = new Querier(forUser, query, source);
120
121 return querier;
122 }
123
124 /*** Returns this instances handle */
125 public String getId() { return id; }
126
127 /*** Returns the query for subclasses */
128 public Query getQuery() { return query; }
129
130 /*** Returns the account the querier is being run for */
131 public Account getUser() { return user; }
132
133 /*** Returns the plugin - this is *only* for testing @todo a nicer way of doing this */
134 public QuerierPlugin getPlugin() { return plugin; }
135
136 /*** Returns the class involved in creating this querier instance. Used for
137 * analysis etc */
138 public Object getSource() { return source; }
139
140 /***
141 * Runnable implementation - this method is called when the thread to run
142 * this asynchronously is started. It should just do ask() and handle
143 * any error, because these won't go anywhere otherwise...
144 */
145 public void run() {
146 log.info("Starting Query ["+id+"] asynchronously...");
147
148 try {
149 ask();
150 }
151 catch (Throwable th) {
152 log.error("Exception during Asynchronous Run",th);
153 if (!(getStatus() instanceof QuerierError)) {
154 setStatus(new QuerierError(getStatus(), "", th));
155 }
156 }
157 log.info("...Ending asynchronous Query ["+id+"]");
158
159 }
160
161 /*** Carries out the query via the plugin to do the query.
162 * The plugin does the complete conversion, query and
163 * results processing
164 */
165 public void ask() throws IOException {
166
167
168 if ((query.getResultsDef() == null) || (query.getTarget() == null)) {
169 throw new DatacenterException("No taret given for the results");
170 }
171
172
173 if (!(getStatus() instanceof QuerierAborted)) {
174 plugin.askQuery(user, query, this);
175
176 close();
177 }
178 }
179
180 /*** Asks the plugin for the count (ie number of matches) for
181 * the given query. These are asynchronous (blocking)
182 */
183 public long askCount() throws IOException {
184 return plugin.getCount(user, query, this);
185 }
186
187
188 /***
189 * Closes & tidies up
190 */
191 public void close() {
192 if (!getStatus().isFinished()) {
193 setStatus(new QuerierComplete(getStatus()));
194 }
195 plugin = null;
196 }
197
198 /***
199 * Returns the time it took to complete the query in milliseconds, or the
200 * time since it started (if it's still running). -1 if the query has not
201 * yet started
202 */
203 public long getQueryTimeTaken() {
204
205
206 QuerierStatus status = getStatus();
207 QuerierStatus next = null;
208 while ((status != null) && !(status instanceof QuerierQuerying)) {
209 next = status;
210 status = status.getPrevious();
211 }
212 if (status == null) {
213
214 return -1;
215 }
216 Date queryStarted = status.getTimestamp();
217 if (next != null) {
218
219 return next.getTimestamp().getTime() - queryStarted.getTime();
220 }
221 else {
222 return new Date().getTime() - queryStarted.getTime();
223 }
224 }
225
226 /***
227 * Abort - stops query (if poss) and tidies up
228 */
229 public QuerierStatus abort() {
230
231
232 if (plugin != null) {
233 plugin.abort();
234 setStatus(new QuerierAborted(getStatus()));
235 }
236
237 aborted = true;
238
239 return getStatus();
240
241 }
242
243 /***
244 * For debugging/display
245 */
246 public String toString() {
247 return "Querier ["+getId()+"] ";
248 }
249
250 /***
251 * Returns if the querier is closed and no more operations are possible
252 */
253 public boolean isClosed() {
254 return (status.isFinished());
255 }
256
257 /*** Called by the plugin to register a status change
258 */
259 public void pluginStatusChanged(QuerierStatus newStatus) {
260 setStatus(newStatus);
261 }
262
263
264
265 /***
266 * Sets the status. NB if the new status is ordered before the existing one,
267 * throws an exception (as each querier should only handle one query).
268 * Synchronised as the queriers may be running under a different thread
269 */
270 public synchronized void setStatus(QuerierStatus newStatus) {
271
272 if (status != null) {
273 if ((status instanceof QuerierError) || (newStatus.isBefore(status))) {
274 String msg = "Trying to start a step '"+newStatus+"' when status is already "+status;
275 log.error(msg);
276 throw new IllegalStateException(msg);
277 }
278 }
279
280 log.info("Query ["+id+"] for "+user+", now "+newStatus);
281
282 status = newStatus;
283
284 fireStatusChanged(status);
285 }
286
287 /***
288 * Returns the status - contains more info than the state
289 */
290 public QuerierStatus getStatus() {
291 return status;
292 }
293
294 /***
295 * Register a status listener. This will be informed of changes in status
296 * to the service - IF the service supports such info. Otherwise it will
297 * just get 'starting', 'working' and 'completed' messages based around the
298 * basic http exchange.
299 */
300 public void addListener(QuerierListener aListener) {
301 listeners.add(aListener);
302 }
303
304 /***
305 * Removes a listern
306 */
307 public void removeListener(QuerierListener aListener) {
308 listeners.remove(aListener);
309 }
310 /*** informs all listeners of the new status change. Not threadsafe... should
311 * call setStatus() rather than this directly
312 */
313 private void fireStatusChanged(QuerierStatus newStatus) {
314 for (int i=0;i<listeners.size();i++) {
315 try {
316 ((QuerierListener) listeners.get(i)).queryStatusChanged(this);
317 }
318 catch (RuntimeException e) {
319
320
321 log.error("Listener ("+listeners.get(i)+") failed to handle status change to "+newStatus, e);
322
323 }
324 }
325 }
326
327
328 /***
329 * Helper method to generates a handle for use by a particular instance; uses the current
330 * time to help us debug (ie we can look at the temporary directories and
331 * see which was the last run). Later we could add service/user information
332 * if available
333 * @todo not guaranteed to be unique...
334 */
335 protected static String generateQueryId() {
336 Date todayNow = new Date();
337 return
338 todayNow.getYear()
339 + "-"
340 + todayNow.getMonth()
341 + "-"
342 + todayNow.getDate()
343 + "_"
344 + todayNow.getHours()
345 + "."
346 + todayNow.getMinutes()
347 + "."
348 + todayNow.getSeconds()
349 + "_"
350
351 + (random.nextInt(8999999) + 1000000);
352
353 }
354
355
356
357 }
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637