AbstractCompositeResourceBundleBuilder.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.util.CompositeResourceBundle;
19 import griffon.util.CompositeResourceBundleBuilder;
20 
21 import javax.annotation.Nonnull;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.List;
25 import java.util.Locale;
26 import java.util.ResourceBundle;
27 
28 import static griffon.util.GriffonNameUtils.requireNonBlank;
29 import static java.util.Objects.requireNonNull;
30 
31 /**
32  @author Andres Almiray
33  @since 2.0.0
34  */
35 public abstract class AbstractCompositeResourceBundleBuilder implements CompositeResourceBundleBuilder {
36     protected static final String ERROR_BASENAME_BLANK = "Argument 'basename' must not be blank";
37     protected static final String ERROR_LOCALE_NULL = "Argument 'locale' must not be null";
38 
39     @Override
40     @Nonnull
41     public ResourceBundle create(@Nonnull String basename) {
42         return create(basename, Locale.getDefault());
43     }
44 
45     @Override
46     @Nonnull
47     public ResourceBundle create(@Nonnull String basename, @Nonnull Locale locale) {
48         requireNonBlank(basename, ERROR_BASENAME_BLANK);
49         requireNonNull(locale, ERROR_LOCALE_NULL);
50 
51         initialize();
52 
53         String[] combinations = {
54             locale.getLanguage() "_" + locale.getCountry() "_" + locale.getVariant(),
55             locale.getLanguage() "_" + locale.getCountry(),
56             locale.getLanguage()
57         };
58 
59         basename = basename.replace('.''/');
60         List<ResourceBundle> bundles = new ArrayList<>();
61         for (String suffix : combinations) {
62             if (suffix.endsWith("_")) { continue}
63             bundles.addAll(loadBundlesFor(basename + "_" + suffix));
64         }
65         bundles.addAll(loadBundlesFor(basename));
66         if (bundles.size() == 0) {
67             throw new IllegalArgumentException("There are no ResourceBundle resources matching " + basename);
68         }
69 
70         return new CompositeResourceBundle(bundles);
71     }
72 
73     protected abstract void initialize();
74 
75     @Nonnull
76     protected abstract Collection<ResourceBundle> loadBundlesFor(@Nonnull String basename);
77 }