PropertiesResourceBundleLoader.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.resources.ResourceHandler;
21 import griffon.util.PropertiesReader;
22 import griffon.util.PropertiesResourceBundle;
23 
24 import javax.annotation.Nonnull;
25 import javax.inject.Inject;
26 import javax.inject.Named;
27 import java.io.IOException;
28 import java.net.URL;
29 import java.util.ArrayList;
30 import java.util.Collection;
31 import java.util.List;
32 import java.util.Properties;
33 import java.util.ResourceBundle;
34 
35 import static griffon.util.GriffonNameUtils.requireNonBlank;
36 import static java.util.Objects.requireNonNull;
37 
38 /**
39  @author Andres Almiray
40  @since 2.11.0
41  */
42 @Named("properties")
43 public class PropertiesResourceBundleLoader extends AbstractResourceBundleLoader {
44     protected static final String PROPERTIES_SUFFIX = ".properties";
45 
46     protected final PropertiesReader propertiesReader;
47 
48     @Inject
49     public PropertiesResourceBundleLoader(@Nonnull ResourceHandler resourceHandler,
50                                           @Nonnull PropertiesReader propertiesReader) {
51         super(resourceHandler);
52         this.propertiesReader = requireNonNull(propertiesReader, "Argument 'propertiesReader' must not be null");
53     }
54 
55     @Nonnull
56     @Override
57     public Collection<ResourceBundle> load(@Nonnull String name) {
58         requireNonBlank(name, ERROR_FILENAME_BLANK);
59         List<ResourceBundle> bundles = new ArrayList<>();
60         List<URL> resources = getResources(name, PROPERTIES_SUFFIX);
61         if (resources != null) {
62             for (URL resource : resources) {
63                 if (null == resource) { continue}
64                 try {
65                     Properties properties = propertiesReader.load(resource.openStream());
66                     bundles.add(new PropertiesResourceBundle(properties));
67                 catch (IOException e) {
68                     // ignore
69                 }
70             }
71         }
72         return bundles;
73     }
74 }