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