ResourceBundleConfiguration.java
01 /*
02  * Copyright 2008-2016 the original author or authors.
03  *
04  * Licensed under the Apache License, Version 2.0 (the "License");
05  * you may not use this file except in compliance with the License.
06  * You may obtain a copy of the License at
07  *
08  *     http://www.apache.org/licenses/LICENSE-2.0
09  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.codehaus.griffon.runtime.core;
17 
18 import javax.annotation.Nonnull;
19 import javax.annotation.Nullable;
20 import javax.inject.Inject;
21 import java.util.Enumeration;
22 import java.util.LinkedHashMap;
23 import java.util.Map;
24 import java.util.MissingResourceException;
25 import java.util.ResourceBundle;
26 
27 import static griffon.util.ConfigUtils.getConfigValue;
28 import static griffon.util.GriffonNameUtils.requireNonBlank;
29 import static java.util.Collections.unmodifiableMap;
30 import static java.util.Objects.requireNonNull;
31 
32 /**
33  @author Andres Almiray
34  @since 2.0.0
35  */
36 public class ResourceBundleConfiguration extends AbstractConfiguration {
37     protected static final String ERROR_KEY_BLANK = "Argument 'key' must not be blank";
38     private final ResourceBundle resourceBundle;
39     private final Map<String, Object> flatMap = new LinkedHashMap<>();
40 
41     @Inject
42     public ResourceBundleConfiguration(@Nonnull ResourceBundle resourceBundle) {
43         this.resourceBundle = requireNonNull(resourceBundle, "Argument 'resourceBundle' must not be null");
44         Enumeration<String> keys = resourceBundle.getKeys();
45         while (keys.hasMoreElements()) {
46             String key = keys.nextElement();
47             flatMap.put(key, getConfigValue(resourceBundle, key));
48         }
49     }
50 
51     public boolean containsKey(@Nonnull String key) {
52         return resourceBundle.containsKey(requireNonBlank(key, ERROR_KEY_BLANK));
53     }
54 
55     @Nonnull
56     @Override
57     public Map<String, Object> asFlatMap() {
58         return unmodifiableMap(flatMap);
59     }
60 
61     @Nonnull
62     @Override
63     public ResourceBundle asResourceBundle() {
64         return resourceBundle;
65     }
66 
67     @Nullable
68     @Override
69     public Object get(@Nonnull String key) {
70         try {
71             return getConfigValue(resourceBundle, key);
72         catch (MissingResourceException mre) {
73             return null;
74         }
75     }
76 }