KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > cintoo > messages > format > Formatter


1 /*
2  * Copyright 2006 cintoo, Berlin, Germany
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, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package cintoo.messages.format;
17
18 import java.text.MessageFormat JavaDoc;
19 import java.util.MissingResourceException JavaDoc;
20 import java.util.ResourceBundle JavaDoc;
21
22 /**
23  * Formatter for formatting text with arguments. Supports choices.
24  *
25  * @author Stephan J. Schmidt
26  * @version $id$
27  * @since 1.0
28  */

29 public class Formatter {
30   /**
31    * Default constructor.
32    */

33   public Formatter() {
34   }
35
36   /**
37    * Format a string based on the given key and the given bundle.
38    *
39    * @param bundle bundle to get message from
40    * @param key key for the message in the bundle
41    * @return formatted message
42    */

43   public String JavaDoc format(ResourceBundle JavaDoc bundle, String JavaDoc key) {
44     return formatArgs(bundle, key);
45   }
46
47   /**
48    * Format a string based on the given key and the given bundle.
49    *
50    * @param bundle bundle to get message from
51    * @param key key for the message in the bundle
52    * @param args arguments for the message
53    * @return formatted message
54    */

55   public String JavaDoc format(ResourceBundle JavaDoc bundle, String JavaDoc key, Object JavaDoc... args) {
56     return formatArgs(bundle, key, args);
57   }
58
59   private String JavaDoc formatArgs(ResourceBundle JavaDoc bundle, String JavaDoc key, Object JavaDoc... args) {
60     if (null != bundle) {
61       try {
62         return formatArgs(bundle.getString(key), args);
63       } catch (MissingResourceException JavaDoc e) {
64
65       }
66     }
67     return "!" + key + "!";
68   }
69
70   private String JavaDoc formatArgs(String JavaDoc text, Object JavaDoc... args) {
71     return MessageFormat.format(text, args);
72   }
73
74 }
75
Popular Tags