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