AbstractMapResourceBundle.java
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 griffon.util;
19 
20 import javax.annotation.Nonnull;
21 import javax.annotation.Nullable;
22 import java.util.Enumeration;
23 import java.util.Iterator;
24 import java.util.LinkedHashMap;
25 import java.util.Map;
26 import java.util.ResourceBundle;
27 import java.util.Set;
28 
29 import static griffon.util.ConfigUtils.collectKeys;
30 import static griffon.util.ConfigUtils.getConfigValue;
31 import static griffon.util.GriffonNameUtils.requireNonBlank;
32 
33 /**
34  @author Andres Almiray
35  @since 2.0.0
36  */
37 public abstract class AbstractMapResourceBundle extends ResourceBundle {
38     protected final Map<String, Object> entries = new LinkedHashMap<>();
39     protected volatile Set<String> keys;
40 
41     public AbstractMapResourceBundle() {
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 }