1 package cz.cuni.amis.utils.configuration;
2
3 import java.util.Collections;
4 import java.util.HashSet;
5 import java.util.LinkedList;
6 import java.util.List;
7 import java.util.ServiceLoader;
8 import java.util.Set;
9 import java.util.logging.Handler;
10 import java.util.logging.Level;
11 import java.util.logging.LogRecord;
12 import java.util.logging.Logger;
13
14 import cz.cuni.amis.utils.exception.PogamutException;
15 import cz.cuni.amis.utils.logging.DefaultLogFormatter;
16
17
18
19
20
21
22 public class PropertiesManager {
23
24 Logger log = Logger.getLogger("PropertiesManager");
25 private List<PropertyProvider> providers = null;
26
27 public PropertiesManager() {
28 log.addHandler(new Handler() {
29
30 DefaultLogFormatter logFormatter = new DefaultLogFormatter("Platform", false);
31
32 @Override
33 public void close() throws SecurityException {
34 }
35
36 @Override
37 public void flush() {
38 }
39
40 @Override
41 public void publish(LogRecord record) {
42 System.out.println(logFormatter.format(record));
43 }
44
45 });
46 log.setLevel(Level.INFO);
47 log.info("Instantiated");
48 }
49
50 protected List<PropertyProvider> getProvidersList() {
51 try {
52 if (providers == null) {
53 providers = new LinkedList<PropertyProvider>();
54 ServiceLoader<PropertyProvider> loader = ServiceLoader.load(PropertyProvider.class);
55 Set<Class> loaded = new HashSet<Class>();
56 for (PropertyProvider provider : loader) {
57 if (loaded.contains(provider.getClass())) {
58 if (log.isLoggable(Level.WARNING)) log.warning("Attempt to register PropertyProvider of class " + provider.getClass() + " twice, ignoring.");
59 } else {
60 providers.add(provider);
61 loaded.add(provider.getClass());
62 }
63 }
64 Collections.sort(providers);
65
66 logProvidersOrder();
67 }
68 } catch (Exception e) {
69 throw new PogamutException("Could not initialize PropertiesManager: " + e.getMessage(), e, log, this);
70 }
71 return providers;
72 }
73
74 protected void logProvidersOrder() {
75 if (log.isLoggable(Level.INFO)) log.info("Property providers order:");
76 if (getProvidersList() != null && getProvidersList().size() != 0) {
77 for (PropertyProvider provider : getProvidersList()) {
78 String str = "[" + provider.getPriority() + "] \t " + provider.toString();
79 if (log.isLoggable(Level.INFO)) log.info(str);
80 }
81 } else {
82 if (log.isLoggable(Level.WARNING)) log.warning("There are no PropertyProvider(s) registered inside PropertiesManager! No properties will be available!");
83 }
84 }
85
86
87
88
89
90
91
92
93 public String getProperty(String key) {
94 for (PropertyProvider provider : getProvidersList()) {
95 String val = provider.getProperty(key);
96 if (val != null) {
97 if (log.isLoggable(Level.FINEST)) log.finest("Property " + key + " was loaded from " + provider.toString() + ".");
98 return val;
99 }
100 }
101 return null;
102 }
103 }