View Javadoc

1   /*
2    * Copyright 2004-2009 the Seasar Foundation and the Others.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
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,
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
15   */
16  package org.seasar.cubby.util;
17  
18  import java.text.MessageFormat;
19  import java.util.MissingResourceException;
20  import java.util.ResourceBundle;
21  
22  import org.seasar.cubby.internal.controller.ThreadContext;
23  
24  /**
25   * メッセージリソースを取得するユーティリティクラスです。
26   * 
27   * @author agata
28   */
29  public class Messages {
30  
31  	/**
32  	 * 指定されたメッセージリソースから指定されたキーの値を取得し、置換処理を行ったメッセージを取得します。
33  	 * 
34  	 * @param resource
35  	 *            メッセージリソース
36  	 * @param key
37  	 *            メッセージキー
38  	 * @param args
39  	 *            置換文字列
40  	 * @return 置換処理後のメッセージ
41  	 */
42  	public static String getText(final ResourceBundle resource,
43  			final String key, final Object... args) {
44  		try {
45  			final String text = resource.getString(key);
46  			return MessageFormat.format(text, args);
47  		} catch (final MissingResourceException e) {
48  			return key;
49  		}
50  	}
51  
52  	/**
53  	 * メッセージリソース(messages.properties)から指定されたキーの値を取得し、置換処理を行ったメッセージを取得します。
54  	 * 
55  	 * <pre>
56  	 * msg.sample2=メッセージ中に置換文字列を使用できます(引数1={0}, 引数2={1})。
57  	 * 
58  	 * // 「メッセージ中に置換文字列を使用できます(引数1=foo, 引数2=bar)。」
59  	 * String message = Messages.getText(&quot;msg.sample2&quot;, &quot;foo&quot;, &quot;bar&quot;);
60  	 * </pre>
61  	 * 
62  	 * @see Messages#getText(ResourceBundle, String, Object...)
63  	 * @param key
64  	 *            メッセージキー
65  	 * @param args
66  	 *            置換文字列
67  	 * @return 置換処理後のメッセージ
68  	 */
69  	public static String getText(final String key, final Object... args) {
70  		final ResourceBundle messagesResourceBundle = ThreadContext
71  				.getMessagesResourceBundle();
72  		return getText(messagesResourceBundle, key, args);
73  	}
74  }