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