01 /*
02 * Copyright 2008-2017 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 griffon.util;
17
18 import javax.annotation.Nonnull;
19 import javax.annotation.Nullable;
20 import javax.annotation.PostConstruct;
21 import java.util.Enumeration;
22 import java.util.Iterator;
23 import java.util.LinkedHashMap;
24 import java.util.Map;
25 import java.util.ResourceBundle;
26 import java.util.Set;
27
28 import static griffon.util.ConfigUtils.collectKeys;
29 import static griffon.util.ConfigUtils.getConfigValue;
30 import static griffon.util.GriffonNameUtils.requireNonBlank;
31
32 /**
33 * @author Andres Almiray
34 * @since 2.10.0
35 */
36 public abstract class AbstractInjectionAwareMapResourceBundle extends ResourceBundle {
37 protected final Map<String, Object> entries = new LinkedHashMap<>();
38 protected volatile Set<String> keys;
39
40 @PostConstruct
41 private void postConstruct() {
42 initialize(entries);
43 initializeKeys();
44 }
45
46 protected abstract void initialize(@Nonnull Map<String, Object> entries);
47
48 protected void initializeKeys() {
49 keys = collectKeys(entries);
50 }
51
52 @Nullable
53 @Override
54 protected final Object handleGetObject(@Nonnull String key) {
55 return getConfigValue(entries, requireNonBlank(key, "Argument 'key' must not be blank"));
56 }
57
58 @Nonnull
59 @Override
60 public final Enumeration<String> getKeys() {
61 return new IteratorAsEnumeration<>(keys.iterator());
62 }
63
64 @Override
65 public Set<String> keySet() {
66 return keys;
67 }
68
69 @Override
70 protected Set<String> handleKeySet() {
71 return keys;
72 }
73
74 private static class IteratorAsEnumeration<E> implements Enumeration<E> {
75 private final Iterator<E> iterator;
76
77 public IteratorAsEnumeration(Iterator<E> iterator) {
78 this.iterator = iterator;
79 }
80
81 public boolean hasMoreElements() {
82 return iterator.hasNext();
83 }
84
85 public E nextElement() {
86 return iterator.next();
87 }
88 }
89 }
|