DefaultCompositeResourceBundleBuilder.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.util;
19 
20 import griffon.core.injection.Injector;
21 import griffon.util.ResourceBundleLoader;
22 
23 import javax.annotation.Nonnull;
24 import javax.inject.Inject;
25 import javax.inject.Provider;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.ResourceBundle;
31 import java.util.concurrent.ConcurrentHashMap;
32 
33 import static griffon.util.AnnotationUtils.sortByDependencies;
34 import static java.util.Objects.requireNonNull;
35 
36 /**
37  @author Andres Almiray
38  @since 2.0.0
39  */
40 public class DefaultCompositeResourceBundleBuilder extends AbstractCompositeResourceBundleBuilder {
41     protected static final String ERROR_INJECTOR_NULL = "Argument 'injector' must not be null";
42 
43     private final Provider<Injector> injector;
44     private final Map<String, ResourceBundleLoader> loaders = new ConcurrentHashMap<>();
45 
46     @Inject
47     public DefaultCompositeResourceBundleBuilder(@Nonnull Provider<Injector> injector) {
48         this.injector = requireNonNull(injector, ERROR_INJECTOR_NULL);
49     }
50 
51     protected void initialize() {
52         if (loaders.isEmpty()) {
53             Collection<ResourceBundleLoader> instances = injector.get().getInstances(ResourceBundleLoader.class);
54             loaders.putAll(sortByDependencies(instances, """resource bundle loader"));
55         }
56     }
57 
58     @Nonnull
59     protected Collection<ResourceBundle> loadBundlesFor(@Nonnull String basename) {
60         List<ResourceBundle> bundles = new ArrayList<>();
61         for (Map.Entry<String, ResourceBundleLoader> e : loaders.entrySet()) {
62             Collection<ResourceBundle> loaded = e.getValue().load(basename);
63             if (!loaded.isEmpty()) {
64                 bundles.addAll(loaded);
65             }
66         }
67 
68         return bundles;
69     }
70 }