1 package ch.busyboxes.agoo.service.impl;
2
3 import org.apache.log4j.Logger;
4
5 import ch.busyboxes.agoo.dao.WatcherTaskDAO;
6 import ch.busyboxes.agoo.model.WatcherTask;
7 import ch.busyboxes.agoo.model.enumeration.TaskState;
8 import ch.busyboxes.agoo.model.enumeration.TaskType;
9 import ch.busyboxes.agoo.service.WatchedFileService;
10 import ch.busyboxes.agoo.service.WatchedFolderService;
11 import ch.busyboxes.agoo.service.WatcherTaskService;
12
13
14
15
16
17
18 public class WatcherTaskServiceImpl implements WatcherTaskService {
19
20
21 private Logger logger = Logger.getLogger(WatcherTaskServiceImpl.class);
22
23
24 private WatchedFolderService watchedFolderService;
25
26
27 private WatchedFileService watchedFileService;
28
29
30 private WatcherTaskDAO watcherTaskDAO;
31
32
33
34
35 @Override
36 public void runNextTask() {
37 WatcherTask nextTask = watcherTaskDAO.fetchNextPendingTask();
38
39 if (nextTask != null) {
40
41 try {
42
43 nextTask.setTaskState(TaskState.RUNNING);
44 watcherTaskDAO.updateTask(nextTask);
45
46
47 switch (nextTask.getTaskType()) {
48 case SCAN_FOLDER:
49
50 watchedFolderService.refreshWatchedFilesInWatchedFolder(nextTask.getTargetId());
51 break;
52
53 case CHECK_FILE:
54
55 watchedFileService.checkWatchedFile(nextTask.getTargetId());
56 break;
57
58 default:
59 throw new RuntimeException("Unhandled task type: " + nextTask.getTaskType());
60 }
61
62
63 watcherTaskDAO.removeTask(nextTask);
64 } catch (Exception e) {
65 logger.error("Error while running task: " + nextTask, e);
66 nextTask.setTaskState(TaskState.ERROR);
67 watcherTaskDAO.updateTask(nextTask);
68 }
69 } else {
70 logger.debug("No pending task found");
71 }
72 }
73
74
75
76
77 @Override
78 public void addScanFolderTask(Long folderId) {
79 watcherTaskDAO.createNewTask(TaskType.SCAN_FOLDER, folderId);
80 }
81
82
83
84
85
86
87 public void setWatcherTaskDAO(WatcherTaskDAO watcherTaskDAO) {
88 this.watcherTaskDAO = watcherTaskDAO;
89 }
90
91
92
93
94
95
96 public void setWatchedFolderService(WatchedFolderService watchedFolderService) {
97 this.watchedFolderService = watchedFolderService;
98 }
99
100
101
102
103
104
105 public void setWatchedFileService(WatchedFileService watchedFileService) {
106 this.watchedFileService = watchedFileService;
107 }
108
109
110
111
112 @Override
113 public void addCheckFileTask(Long fileId) {
114 watcherTaskDAO.createNewTask(TaskType.CHECK_FILE, fileId);
115 }
116
117 }