KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > taglibs > i18n > MessageTag


1 /*
2  * Copyright 1999,2004 The Apache Software Foundation.
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
17 package org.apache.taglibs.i18n;
18
19 import java.io.IOException JavaDoc;
20
21 import java.text.MessageFormat JavaDoc;
22
23 import java.util.Arrays JavaDoc;
24 import java.util.ArrayList JavaDoc;
25 import java.util.List JavaDoc;
26 import java.util.ResourceBundle JavaDoc;
27
28 import javax.servlet.ServletContext JavaDoc;
29
30 import javax.servlet.jsp.JspException JavaDoc;
31 import javax.servlet.jsp.JspTagException JavaDoc;
32 import javax.servlet.jsp.PageContext JavaDoc;
33 import javax.servlet.jsp.tagext.BodyTag JavaDoc;
34 import javax.servlet.jsp.tagext.BodyTagSupport JavaDoc;
35
36 /**
37  * This class implements a body tag that allows you to use a resource bundle
38  * to internationalize content in a web page. The "key" attribute is required,
39  * and is used to look up content in the resource bundle. The "args" attribute
40  * is optional, and if present, provides items to pass to a MessageFormat.
41  *
42  * The BundleTag must first be used in order to ensure that the proper bundle
43  * is loaded.
44  * <P>
45  * <H2>Examples</H2>
46  * <PRE>
47  * &lt;i18n:bundle baseName="test"/&gt;
48  * &lt;i18n:getMessage key="test"/&gt;
49  * &lt;i18n:getMessage key="test" args="1,2,3"/&gt;
50  * etc...
51  * </PRE>
52  * <P>
53  *
54  * @author <a HREF="mailto:tdawson@wamnet.com">Tim Dawson</a>
55  *
56  */

57 public class MessageTag extends BodyTagSupport JavaDoc
58 {
59     // instance variables used during processing
60
private String JavaDoc _key = null;
61     private String JavaDoc _value = null;
62     private ResourceBundle JavaDoc _bundle = null;
63     private String JavaDoc _bundleRef = null;
64     private Object JavaDoc [] _args = null;
65     private boolean _debug = false;
66
67     // these are reused for each message tag; luckily tags are thread-safe
68
private MessageFormat JavaDoc _messageFormat = new MessageFormat JavaDoc("");
69     private List JavaDoc _arguments = new ArrayList JavaDoc();
70
71     /**
72      * sets the key to use when looking up the value in the bundle
73      */

74     public final void setKey(String JavaDoc key)
75     {
76         _key = key;
77     }
78
79     /**
80      * sets the bundle based on a variable defined in the page<br>
81      * if neither bundle or bundleRef are specified, uses the first bundle
82      * defined on the page by the i18n:bundle tag
83      */

84     public final void setBundleRef(String JavaDoc varName)
85     {
86         _bundleRef = varName;
87     }
88
89     /**
90      * sets the bundle to an actual ResourceBundle object<br>
91      * if neither bundle or bundleRef are specified, uses the bundle most recently
92      * defined on the page by the i18n:bundle tag
93      */

94     public final void setBundle(ResourceBundle JavaDoc aBundle)
95     {
96         _bundle = aBundle;
97     }
98
99     /**
100      * @return the bundle to use
101      */

102     private ResourceBundle JavaDoc getBundle() throws JspException JavaDoc
103     {
104         ResourceBundle JavaDoc bundle = _bundle;
105         if ( bundle == null ) {
106             if ( _bundleRef != null ) {
107                 bundle = (ResourceBundle JavaDoc)pageContext.getAttribute(_bundleRef);
108                 if ( bundle == null ) {
109                     throw new JspTagException JavaDoc(
110                         "i18n:message tag, could not find bundleRef=" + _bundleRef);
111                 }
112             } else {
113                 BundleTag bundleTag = (BundleTag)this.findAncestorWithClass(this,BundleTag.class);
114                 if (bundleTag != null) {
115                     return bundleTag.getBundle();
116                 }
117                 bundle = ResourceHelper.getBundle(pageContext);
118             }
119         }
120         return bundle;
121     }
122
123     /**
124      * Turn debugging log messages on or off
125      */

126     public final void setDebug(boolean value)
127     {
128         _debug = value;
129     }
130
131     /**
132      * adds to the list of arguments used when formatting the message
133      */

134     protected final void addArg(Object JavaDoc arg)
135     {
136         _arguments.add(arg);
137         if (_debug) {
138             ServletContext JavaDoc sc = pageContext.getServletContext();
139             sc.log("i18n:message added arg: " + arg.toString());
140         }
141     }
142
143     /**
144      * allows setting all the arguments at once
145      */

146     public final void setArgs(Object JavaDoc[] args)
147     {
148         _args = args;
149     }
150
151     /**
152      * clears the argument list so that sub tags can call addArgument
153      * clears out any previous key and value in case key is not provided,
154      * or the value is null
155      */

156     public final void release()
157     {
158         super.release();
159         if (_arguments != null)
160         {
161             _arguments.clear();
162         }
163         _key = null;
164         _value = null;
165         _bundle = null;
166         _bundleRef = null;
167         _args = null;
168         _debug = false;
169         _messageFormat = null;
170         _arguments = null;
171     }
172
173   /**
174    * locates the bundle and gets the value
175    */

176   public final int doStartTag() throws JspException JavaDoc
177     {
178        // Reset value for resource bundle key
179
_value = null;
180
181        // ensure we have a key
182
if ( _key == null ) {
183             throw new JspTagException JavaDoc("i18n:message tag requires a key attribute.");
184         }
185
186         ResourceBundle JavaDoc bundle = this.getBundle();
187         if ( bundle == null ) {
188             throw new JspTagException JavaDoc(
189                 "i18n:message tag, no bundle available for use.");
190         }
191
192         // Reset the arguments
193
if (_arguments != null) {
194             _arguments.clear();
195         }
196         if ( _args != null ) {
197             _arguments.addAll(Arrays.asList(_args));
198         }
199
200         // see if the bundle has a value, if not, we default to the tag contents
201
try {
202             _value = bundle.getString(_key);
203             if (_debug) {
204                 ServletContext JavaDoc sc = pageContext.getServletContext();
205                 sc.log("i18n:message tag: template for " + _key + " is: " + _value);
206             }
207         } catch (java.util.MissingResourceException JavaDoc e) {
208             ServletContext JavaDoc sc = pageContext.getServletContext();
209             sc.log("i18n:message tag, value not found for key:" + _key);
210         }
211
212         return EVAL_BODY_TAG;
213     }
214
215     /**
216      * If key is not found, use the body content as a default value.
217      */

218     public int doAfterBody() throws JspException JavaDoc
219     {
220         // if the value is null, use the body content
221
if ( _value == null ) {
222           _value = bodyContent.getString();
223         }
224         // cleanup
225
bodyContent.clearBody();
226         return SKIP_BODY;
227     }
228
229     /**
230      * Performs the proper runtime substitution. If an id attribute was
231      * specified, then it is assumed that this tag is merely defining a
232      * string variable; otherwise output is provided.
233      */

234     public final int doEndTag() throws JspException JavaDoc
235     {
236         try {
237             // perform parameter substitutions
238
if ( _value != null && _arguments != null && _arguments.size() > 0) {
239                 // reformat the value as specified
240
_messageFormat.setLocale(getBundle().getLocale());
241                 _messageFormat.applyPattern(_value);
242                 _value = _messageFormat.format(_arguments.toArray());
243             }
244
245             if ( _value == null) {
246                 if (_debug) {
247                     ServletContext JavaDoc sc = pageContext.getServletContext();
248                     sc.log("i18n: message: skipping null value for " + _key);
249                 }
250             } else if (id != null) {
251                 // define the variable in the page context
252
pageContext.setAttribute(id,_value);
253             } else {
254                 // print the value to the JspWriter
255
this.pageContext.getOut().print(_value);
256             }
257         } catch (java.io.IOException JavaDoc e) {
258             throw new JspTagException JavaDoc("i18n:message tag IO Error: " + e.getMessage());
259         }
260
261         // only process the body once
262
return EVAL_PAGE;
263     }
264
265 }
266
Popular Tags