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