Added org.simantics.filesystem.services
[simantics/platform.git] / bundles / org.simantics.filesystem.services / src / org / simantics / filesystem / services / internal / sizetracker / DirectorySizeServiceImpl.java
1 package org.simantics.filesystem.services.internal.sizetracker;
2
3 import java.io.IOException;
4 import java.nio.file.Path;
5 import java.util.HashMap;
6 import java.util.Map;
7
8 import org.osgi.service.component.annotations.Activate;
9 import org.osgi.service.component.annotations.Component;
10 import org.osgi.service.component.annotations.Deactivate;
11 import org.simantics.filesystem.services.sizetracker.DirectorySizeService;
12 import org.simantics.filesystem.services.sizetracker.SizeTracker;
13 import org.slf4j.Logger;
14 import org.slf4j.LoggerFactory;
15
16 /**
17  * @author Tuukka Lehtonen
18  * @since 1.31.0
19  */
20 @Component
21 public class DirectorySizeServiceImpl implements DirectorySizeService {
22
23         private Logger logger = LoggerFactory.getLogger(DirectorySizeServiceImpl.class);
24
25         private final Map<Path, SizeTrackerImpl> trackers = new HashMap<>();
26
27         @Override
28         public SizeTracker track(Path directory) throws IOException {
29                 synchronized (trackers) {
30                         SizeTrackerImpl tracker = trackers.get(directory);
31                         if (tracker != null)
32                                 return tracker;
33                         tracker = new SizeTrackerImpl(this, directory);
34                         try {
35                                 tracker.start();
36                                 trackers.put(directory, tracker);
37                                 return tracker;
38                         } catch (IOException e) {
39                                 safeCloseTracker(tracker);
40                                 throw e;
41                         }
42                 }
43         }
44
45         void removeTracker(Path path) {
46                 synchronized (trackers) {
47                         trackers.remove(path);
48                 }
49         }
50
51         public void shutdown() {
52                 synchronized (trackers) {
53                         trackers.forEach((p,t) -> safeCloseTracker(t));
54                         trackers.clear();
55                 }
56         }
57
58         private void safeCloseTracker(SizeTrackerImpl t) {
59                 try {
60                         t.close();
61                 } catch (IOException e) {
62                         logger.error("Error closing size tracker {}", t, e);
63                 }
64         }
65
66         @Activate
67         public void activate() {
68                 //System.out.println("Activated DirectorySizeServiceImpl");
69         }
70
71         @Deactivate
72         public void deactivate() {
73                 //System.out.println("Deactivated DirectorySizeServiceImpl");
74                 shutdown();
75         }
76
77 }