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