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.i18n;
19
20 import griffon.core.i18n.MessageSource;
21 import griffon.core.i18n.NoSuchMessageException;
22 import griffon.util.CompositeResourceBundle;
23
24 import javax.annotation.Nonnull;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.List;
28 import java.util.Locale;
29 import java.util.ResourceBundle;
30
31 import static griffon.util.GriffonClassUtils.requireNonEmpty;
32 import static griffon.util.GriffonNameUtils.requireNonBlank;
33 import static java.util.Objects.requireNonNull;
34
35 /**
36 * @author Andres Almiray
37 * @since 2.0.0
38 */
39 public class CompositeMessageSource extends AbstractMessageSource {
40 private final MessageSource[] messageSources;
41
42 public CompositeMessageSource(@Nonnull Collection<MessageSource> messageSources) {
43 this(toMessageSourceArray(messageSources));
44 }
45
46 public CompositeMessageSource(@Nonnull MessageSource[] messageSources) {
47 this.messageSources = requireNonNull(messageSources, "Argument 'messageSources' must not be null");
48 }
49
50 private static MessageSource[] toMessageSourceArray(@Nonnull Collection<MessageSource> messageSources) {
51 requireNonNull(messageSources, "Argument 'messageSources' must not be null");
52 requireNonEmpty(messageSources, "Argument 'messageSources' must not be empty");
53 return messageSources.toArray(new MessageSource[messageSources.size()]);
54 }
55
56 @Nonnull
57 @Override
58 protected Object doResolveMessageValue(@Nonnull String key, @Nonnull Locale locale) throws NoSuchMessageException {
59 requireNonBlank(key, ERROR_KEY_BLANK);
60 requireNonNull(locale, ERROR_LOCALE_NULL);
61 for (MessageSource messageSource : messageSources) {
62 try {
63 return messageSource.getMessage(key, locale);
64 } catch (NoSuchMessageException nsme) {
65 // ignore
66 }
67 }
68 throw new NoSuchMessageException(key, locale);
69 }
70
71 @Nonnull
72 @Override
73 public ResourceBundle asResourceBundle() {
74 List<ResourceBundle> bundles = new ArrayList<>();
75 for (MessageSource messageSource : messageSources) {
76 bundles.add(messageSource.asResourceBundle());
77 }
78 return new CompositeResourceBundle(bundles);
79 }
80 }
|