cleanup
[cdmlib.git] / cdmlib-commons / src / main / java / eu / etaxonomy / cdm / common / monitor / RemotingProgressMonitorThread.java
1 /**
2 * Copyright (C) 2015 EDIT
3 * European Distributed Institute of Taxonomy
4 * http://www.e-taxonomy.eu
5 *
6 * The contents of this file are subject to the Mozilla Public License Version 1.1
7 * See LICENSE.TXT at the top of this package for the full license terms.
8 */
9 package eu.etaxonomy.cdm.common.monitor;
10
11 import java.io.Serializable;
12 import java.util.concurrent.ConcurrentHashMap;
13
14 import org.apache.logging.log4j.LogManager;
15 import org.apache.logging.log4j.Logger;
16
17 /**
18 * Thread class to be used to run monitored jobs
19 *
20 * @author cmathew
21 * @since 22 Oct 2015
22 */
23 public abstract class RemotingProgressMonitorThread extends Thread {
24
25 private static final Logger logger = LogManager.getLogger();
26
27 private static ConcurrentHashMap<IRemotingProgressMonitor, RemotingProgressMonitorThread>
28 monitorsInProgress = new ConcurrentHashMap<>();
29
30 private IRemotingProgressMonitor monitor;
31
32 public void setMonitor(IRemotingProgressMonitor monitor) {
33 if(monitor == null) {
34 throw new IllegalStateException("Monitor is null");
35 }
36 this.monitor = monitor;
37 }
38
39 @Override
40 public void run() {
41 try {
42 monitorsInProgress.put(monitor, this);
43 monitor.setResult(doRun(monitor));
44 } catch(Exception ex) {
45 logger.info("Exception in RemotingProgressMonitorThread ", ex);
46 monitor.setResult(ex);
47 monitor.setIsFailed(true);
48 }
49 monitor.done();
50 monitorsInProgress.remove(monitor);
51 }
52
53 /**
54 * Executes the monitored job.
55 *
56 * @param monitor to be updated by the monitored job
57 * @return result object
58 */
59 public abstract Serializable doRun(IRemotingProgressMonitor monitor);
60
61 /**
62 * Returns a currently running monitor thread corresponding to the
63 * given monitor.
64 *
65 * @param monitor for which the thread
66 * @return
67 */
68 protected static RemotingProgressMonitorThread getMonitorThread(IRemotingProgressMonitor monitor) {
69 return monitorsInProgress.get(monitor);
70 }
71
72 @Override
73 public void interrupt() {
74 super.interrupt();
75 monitor.setCanceled(true);
76 monitor.done();
77 monitorsInProgress.remove(monitor);
78 }
79 }