AbstractMapConfiguration.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 org.codehaus.griffon.runtime.core.configuration;
19 
20 import griffon.util.AbstractMapResourceBundle;
21 
22 import javax.annotation.Nonnull;
23 import javax.annotation.Nullable;
24 import java.util.Collections;
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.Objects.requireNonNull;
32 
33 /**
34  @author Andres Almiray
35  @since 2.11.0
36  */
37 public abstract class AbstractMapConfiguration extends AbstractConfiguration {
38     protected static final String ERROR_KEY_BLANK = "Argument 'key' must not be blank";
39     private static final String ERROR_MAP_NULL = "Argument 'map' must not be null";
40     private final Map<String, Object> map;
41 
42     protected AbstractMapConfiguration(@Nonnull Map<String, Object> map) {
43         this.map = requireNonNull(map, ERROR_MAP_NULL);
44     }
45 
46     @Override
47     public boolean containsKey(@Nonnull String key) {
48         return map.containsKey(requireNonBlank(key, ERROR_KEY_BLANK));
49     }
50 
51     @Nonnull
52     @Override
53     public Map<String, Object> asFlatMap() {
54         return Collections.unmodifiableMap(map);
55     }
56 
57     @Nonnull
58     @Override
59     public ResourceBundle asResourceBundle() {
60         return new AbstractMapResourceBundle() {
61             @Override
62             protected void initialize(@Nonnull Map<String, Object> entries) {
63                 entries.putAll(map);
64             }
65         };
66     }
67 
68     @Nullable
69     @Override
70     public Object get(@Nonnull String key) {
71         try {
72             return getConfigValue(map, key);
73         catch (MissingResourceException mre) {
74             return null;
75         }
76     }
77 }