OSDN Git Service

6ad7e2f40dba617f7947f9350cd6c3a56d38896e
[coroid/inqubus.git] / frontend / src / yukihane / inqubus / manager / TaskManager.java
1 package yukihane.inqubus.manager;
2
3 import java.util.HashMap;
4 import java.util.Map;
5 import java.util.concurrent.ExecutorService;
6 import java.util.concurrent.Executors;
7 import java.util.concurrent.Future;
8 import java.util.concurrent.FutureTask;
9 import saccubus.worker.convert.Convert;
10 import saccubus.worker.convert.ConvertResult;
11 import saccubus.worker.download.Download;
12 import saccubus.worker.download.DownloadResult;
13 import saccubus.worker.profile.ConvertProfile;
14 import saccubus.worker.profile.DownloadProfile;
15
16 /**
17  *
18  * @author yuki
19  */
20 public class TaskManager {
21
22     private final ExecutorService downloadExecutorService;
23     private final ExecutorService convertExecutorService;
24     private final Map<Integer, ManageTarget<DownloadResult>> downloadTargets = new HashMap<>();
25     private final Map<Integer, ManageTarget<ConvertResult>> convertTargets = new HashMap<>();
26
27     public TaskManager(int maxDownload, int maxConvert) {
28         downloadExecutorService = Executors.newFixedThreadPool(maxDownload);
29         convertExecutorService = Executors.newFixedThreadPool(maxConvert);
30     }
31
32     public synchronized boolean add(Request request) {
33         final DownloadProfile dp = request.getDownloadProfile();
34         final ConvertProfile cp = request.getConvertProfile();
35         if (dp != null && !dp.getVideoProfile().isDownload() && !dp.getCommentProfile().isDownload()) {
36             final Download task = new Download(dp, request.getVideoId(),
37                     request.getDownloadProgressListener());
38             final Future<DownloadResult> future = downloadExecutorService.submit(task);
39             downloadTargets.put(request.getRowId(), new ManageTarget<>(request, future));
40             return true;
41
42         } else if (cp != null && cp.isConvert()) {
43             final Convert task = new Convert(cp, dp.getVideoProfile().getLocalFile(), dp.getCommentProfile().
44                     getLocalFile(), request.getConvertProgressListener());
45             final Future<ConvertResult> future = convertExecutorService.submit(task);
46             convertTargets.put(request.getRowId(), new ManageTarget<>(request, future));
47             return true;
48         }
49         return false;
50     }
51 }
52
53 class ManageTarget<T> {
54
55     private final Request request;
56     private final Future<T> future;
57
58     ManageTarget(Request request, Future<T> future) {
59         this.request = request;
60         this.future = future;
61     }
62
63     Future<T> getFuture() {
64         return future;
65     }
66
67     Request getRequest() {
68         return request;
69     }
70 }