1 package com.trendmicro.grid.acl.ds;
2
3 import com.trendmicro.grid.acl.commons.Paths;
4 import com.trendmicro.grid.acl.commons.Processes;
5 import com.trendmicro.grid.acl.commons.XmlSerializer;
6 import org.slf4j.Logger;
7 import org.slf4j.LoggerFactory;
8
9 import javax.annotation.PreDestroy;
10 import java.io.File;
11 import java.util.concurrent.ScheduledFuture;
12 import java.util.concurrent.TimeUnit;
13
14
15
16
17
18
19
20 public class RepositorySelectorsFile {
21
22 private static final Logger log = LoggerFactory.getLogger(RepositorySelectorsFile.class);
23
24 private static final XmlSerializer<RepositorySelectors> selectorsSerializer;
25
26 static {
27 selectorsSerializer = new XmlSerializer<RepositorySelectors>(
28 RepositorySelectors.class, "", "repository-selection");
29 }
30
31 private RepositorySelectors selectors = new RepositorySelectors();
32 private ScheduledFuture selectorUpdaterHandle;
33
34 private File getRepositorySelectionFile() {
35 String mode = System.getProperty("mode", "undefined");
36 return new File(Paths.getConfigPath(), "repository-selection." + mode + ".xml");
37 }
38
39 public RepositorySelectors getSelectors() {
40 return selectors;
41 }
42
43 public void loadRepositorySelection() {
44 File selectionFile = getRepositorySelectionFile();
45 if (selectionFile.exists()) {
46 try {
47 selectors = selectorsSerializer.load(selectionFile);
48 selectors.setLastModified(selectionFile.lastModified());
49 } catch (Exception e) {
50 log.error("TMACL-00130:Failed to load the repository " +
51 "selection stored inside " + selectionFile, e);
52 }
53 }
54
55
56 if (selectorUpdaterHandle == null) {
57 selectorUpdaterHandle = Processes.getInstance().scheduleAtFixedRate(new Runnable() {
58 public void run() {
59 long fileTime = getRepositorySelectionFile().lastModified() / 1000;
60 long memoryTime = selectors.getLastModified() / 1000;
61
62 if (fileTime > memoryTime) {
63 log.info("TMACL-00210:Reloading the repository selection from disk.");
64 loadRepositorySelection();
65 } else if (fileTime < memoryTime) {
66 log.info("TMACL-00220:Persisting the changed repository selection to disk.");
67 storeRepositorySelection();
68 }
69 }
70 }, 10, 10, TimeUnit.SECONDS);
71 }
72 }
73
74 @PreDestroy
75 public void storeRepositorySelection() {
76 File selectionFile = getRepositorySelectionFile();
77 try {
78 selectorsSerializer.save(selectors, selectionFile, false, 4);
79 selectionFile.setLastModified(selectors.getLastModified());
80 } catch (Exception e) {
81 log.error("TMACL-00150:Failed storing the repository selection to " +
82 selectionFile + ", restarting the process may lead to unexpected results.", e);
83 }
84 }
85 }