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