01: /*******************************************************************************
02: * Portions created by Sebastian Thomschke are copyright (c) 2005-2007 Sebastian
03: * Thomschke.
04: *
05: * All Rights Reserved. This program and the accompanying materials
06: * are made available under the terms of the Eclipse Public License v1.0
07: * which accompanies this distribution, and is available at
08: * http://www.eclipse.org/legal/epl-v10.html
09: *
10: * Contributors:
11: * Sebastian Thomschke - initial implementation.
12: *******************************************************************************/package net.sf.oval.localization;
13:
14: import java.util.Enumeration;
15: import java.util.LinkedList;
16: import java.util.List;
17: import java.util.Map;
18: import java.util.ResourceBundle;
19:
20: import net.sf.oval.internal.CollectionFactoryHolder;
21:
22: /**
23: * Default implementation that resolves messages based
24: * on the registered resource bundles.
25: *
26: * @author Sebastian Thomschke
27: */
28: public class MessageResolverImpl implements MessageResolver {
29: private final Map<ResourceBundle, List<String>> messageBundleKeys = CollectionFactoryHolder
30: .getFactory().createMap(8);
31:
32: private final LinkedList<ResourceBundle> messageBundles = new LinkedList<ResourceBundle>();
33:
34: public static final MessageResolverImpl INSTANCE = new MessageResolverImpl();
35:
36: public MessageResolverImpl() {
37: // add the message bundle for the pre-built constraints in the default locale
38: addMessageBundle(ResourceBundle
39: .getBundle("net/sf/oval/Messages"));
40: }
41:
42: /**
43: * Adds a message bundle
44: *
45: * @param messageBundle
46: * @return true if the bundle was registered and false if it was already registered
47: */
48: public final boolean addMessageBundle(
49: final ResourceBundle messageBundle) {
50: if (messageBundles.contains(messageBundle))
51: return false;
52:
53: messageBundles.addFirst(messageBundle);
54: final List<String> keys = CollectionFactoryHolder.getFactory()
55: .createList();
56:
57: for (final Enumeration<String> keysEnum = messageBundle
58: .getKeys(); keysEnum.hasMoreElements();) {
59: keys.add(keysEnum.nextElement());
60: }
61:
62: messageBundleKeys.put(messageBundle, keys);
63:
64: return true;
65: }
66:
67: public String getMessage(final String key) {
68: for (final ResourceBundle bundle : messageBundles) {
69: final List<String> keys = messageBundleKeys.get(bundle);
70: if (keys.contains(key)) {
71: return bundle.getString(key);
72: }
73: }
74: return null;
75: }
76:
77: /**
78: * Removes the message bundle
79: *
80: * @param messageBundle
81: * @return true if the bundle was registered and false if it wasn't registered
82: */
83: public boolean removeMessageBundle(
84: final ResourceBundle messageBundle) {
85: if (!messageBundles.contains(messageBundle))
86: return false;
87:
88: messageBundles.remove(messageBundle);
89: return true;
90: }
91: }
|