1 package org.kuali.common.jute.env;
2
3 import static com.google.common.base.Optional.absent;
4 import static com.google.common.base.Optional.fromNullable;
5 import static com.google.common.base.Preconditions.checkState;
6 import static org.kuali.common.jute.base.Precondition.checkNotBlank;
7 import static org.kuali.common.jute.base.Precondition.checkNotNull;
8
9 import java.util.List;
10
11 import javax.inject.Inject;
12
13 import org.kuali.common.jute.system.VirtualSystem;
14
15 import com.google.common.base.Function;
16 import com.google.common.base.Optional;
17 import com.google.common.collect.ImmutableList;
18
19 public final class StandardEnvironment implements Environment {
20
21 @Inject
22 public StandardEnvironment(VirtualSystem system, @AlternateKeyFunctions List<Function<String, String>> alternateKeyFunctions) {
23 this.system = checkNotNull(system, "system");
24 this.alternateKeyFunctions = ImmutableList.copyOf(alternateKeyFunctions);
25 }
26
27 private final VirtualSystem system;
28 private final ImmutableList<Function<String, String>> alternateKeyFunctions;
29
30 public VirtualSystem getSystem() {
31 return system;
32 }
33
34 @Override
35 public Optional<String> getProperty(String key) {
36 checkNotBlank(key, "key");
37 Optional<String> sys = fromNullable(system.getProperties().getProperty(key));
38 if (sys.isPresent()) {
39 return sys;
40 }
41 Optional<String> env = fromNullable(system.getEnvironment().getProperty(key));
42 if (env.isPresent()) {
43 return env;
44 }
45 for (Function<String, String> alternateKeyFunction : alternateKeyFunctions) {
46 String alternateKey = alternateKeyFunction.apply(key);
47 env = fromNullable(system.getEnvironment().getProperty(alternateKey));
48 if (env.isPresent()) {
49 return env;
50 }
51 }
52 return absent();
53 }
54
55 @Override
56 public boolean containsProperty(String key) {
57 checkNotBlank(key, "key");
58 return getProperty(key).isPresent();
59 }
60
61 @Override
62 public String getProperty(String key, String defaultValue) {
63 checkNotBlank(key, "key");
64 Optional<String> value = getProperty(key);
65 if (value.isPresent()) {
66 return value.get();
67 } else {
68 return defaultValue;
69 }
70 }
71
72 @Override
73 public String getRequiredProperty(String key) {
74 Optional<String> value = getProperty(key);
75 checkState(value.isPresent(), "'%s' is required", key);
76 return value.get();
77 }
78
79 }