KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > Yasna > forum > tags > CalcTag


1 /**
2  * Copyright (C) 2001 Yasna.com. All rights reserved.
3  *
4  * ===================================================================
5  * The Apache Software License, Version 1.1
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  * notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  * notice, this list of conditions and the following disclaimer in
16  * the documentation and/or other materials provided with the
17  * distribution.
18  *
19  * 3. The end-user documentation included with the redistribution,
20  * if any, must include the following acknowledgment:
21  * "This product includes software developed by
22  * Yasna.com (http://www.yasna.com)."
23  * Alternately, this acknowledgment may appear in the software itself,
24  * if and wherever such third-party acknowledgments normally appear.
25  *
26  * 4. The names "Yazd" and "Yasna.com" must not be used to
27  * endorse or promote products derived from this software without
28  * prior written permission. For written permission, please
29  * contact yazd@yasna.com.
30  *
31  * 5. Products derived from this software may not be called "Yazd",
32  * nor may "Yazd" appear in their name, without prior written
33  * permission of Yasna.com.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED. IN NO EVENT SHALL YASNA.COM OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many
50  * individuals on behalf of Yasna.com. For more information
51  * on Yasna.com, please see <http://www.yasna.com>.
52  */

53
54 /**
55  * Copyright (C) 2000 CoolServlets.com. All rights reserved.
56  *
57  * ===================================================================
58  * The Apache Software License, Version 1.1
59  *
60  * Redistribution and use in source and binary forms, with or without
61  * modification, are permitted provided that the following conditions
62  * are met:
63  *
64  * 1. Redistributions of source code must retain the above copyright
65  * notice, this list of conditions and the following disclaimer.
66  *
67  * 2. Redistributions in binary form must reproduce the above copyright
68  * notice, this list of conditions and the following disclaimer in
69  * the documentation and/or other materials provided with the
70  * distribution.
71  *
72  * 3. The end-user documentation included with the redistribution,
73  * if any, must include the following acknowledgment:
74  * "This product includes software developed by
75  * CoolServlets.com (http://www.coolservlets.com)."
76  * Alternately, this acknowledgment may appear in the software itself,
77  * if and wherever such third-party acknowledgments normally appear.
78  *
79  * 4. The names "Jive" and "CoolServlets.com" must not be used to
80  * endorse or promote products derived from this software without
81  * prior written permission. For written permission, please
82  * contact webmaster@coolservlets.com.
83  *
84  * 5. Products derived from this software may not be called "Jive",
85  * nor may "Jive" appear in their name, without prior written
86  * permission of CoolServlets.com.
87  *
88  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
89  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
90  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
91  * DISCLAIMED. IN NO EVENT SHALL COOLSERVLETS.COM OR
92  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
93  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
94  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
95  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
96  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
97  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
98  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
99  * SUCH DAMAGE.
100  * ====================================================================
101  *
102  * This software consists of voluntary contributions made by many
103  * individuals on behalf of CoolServlets.com. For more information
104  * on CoolServlets.com, please see <http://www.coolservlets.com>.
105  */

106
107 package com.Yasna.forum.tags;
108
109 import java.io.*;
110 import java.util.*;
111 import javax.servlet.*;
112 import javax.servlet.jsp.*;
113 import javax.servlet.jsp.tagext.*;
114 import javax.servlet.http.*;
115 import com.Yasna.forum.tags.*;
116
117 /**
118  * JSP Tag <b>calc</b>, used to calculate and return an integer value.
119  * <p>
120  * Calculates an integer value based on the integer values and operators
121  * found in the body of the calc tag, then returns the value calculated
122  * to the JSP page.
123  * <p>
124  * Valid operators are <b>+</b>, <b>-</b>, <b>*</b>, and <b>/</b>.
125  * <p>
126  * There must be white space between integers and operators.
127  * <p>
128  * Any JSP tags embedded in the body of the calc tag are processed
129  * before the calculation is made.
130  * <p>
131  * Example:
132  * <p>
133  * &lt;jf:calc&gt; &lt;jf:current_depth/&gt; * 4 &lt;/jf:calc&gt;
134  * <p>
135  * JSP Tag Lib Descriptor
136  * <p><pre>
137  * &lt;name&gt;calc&lt;/name&gt;
138  * &lt;tagclass&gt;com.Yasna.forum.tags.CalcTag&lt;/tagclass&gt;
139  * &lt;bodycontent&gt;JSP&lt;/bodycontent&gt;
140  * &lt;info&gt;Calculate an expression&lt;/info&gt;
141  * </pre>
142  *
143  * @author Glenn Nielsen
144  */

145
146 public class CalcTag extends BodyTagSupport
147 {
148   // Result of integer calculation
149
long res = 0;
150
151   /**
152    * Allow the body of the calc tag to be processed.
153    *
154    * @return EVAL_BODY_TAG
155    */

156   public final int doStartTag() throws JspException
157   {
158     return EVAL_BODY_TAG;
159   }
160
161   /**
162    * Read the body of the calc tag to obtain the integer values and operators,
163    * then perform calculation.
164    *
165    * @return SKIP_BODY
166    */

167   public final int doAfterBody() throws JspException
168   {
169     // Use the body of the tag as input for the calculation
170
BodyContent body = getBodyContent();
171     String JavaDoc s = body.getString();
172     // Clear the body since we will output only the result of the calculation
173
body.clearBody();
174
175     // Create a list of integers and operators
176
List l = new LinkedList();
177     int beg = 0,end=0;
178     int len = s.length();
179     char v;
180     boolean digit = false;
181     boolean operator = false;
182     boolean negated = false;
183
184     // Parse the body extracting integers and operators
185
for( end=0; end < len; end++ ) {
186       v = s.charAt(end);
187 // System.out.println("calc char \"" + v + "\" negated=" + negated);
188
if( Character.isWhitespace(v) ) {
189         if( digit ) {
190 // System.out.println("Calc digit \"" + s.substring(beg,end) + "\"");
191
l.add((Object JavaDoc)Long.valueOf(s.substring(beg,end)));
192         } else if( operator ) {
193 // System.out.println("Calc op \"" + s.substring(beg,end) + "\"");
194
l.add((Object JavaDoc)new StringBuffer JavaDoc(s.substring(beg,end)));
195         }
196         digit = negated = operator = false;
197         beg = end;
198       } else if( Character.isDigit(v) ) {
199         if( !operator || negated ) {
200           if( !digit && !negated )beg = end;
201           digit = true;
202           operator = negated = false;
203         }
204       } else {
205         if( !operator && !digit) {
206           beg = end;
207           if( v == '-' )
208             negated = true;
209         } else {
210           negated = false;
211         }
212         operator = true;
213         digit = false;
214       }
215     }
216
217     if( (end - beg) > 0 ) {
218       if( digit ) {
219 // System.out.println("Calc digit \"" + s.substring(beg,end) + "\"");
220
l.add((Object JavaDoc)Long.valueOf(s.substring(beg,end)));
221       } else if( operator ) {
222 // System.out.println("Calc op \"" + s.substring(beg,end) + "\"");
223
l.add((Object JavaDoc)new StringBuffer JavaDoc(s.substring(beg,end)));
224       }
225     }
226     // Calculate the result
227
res = calculate((ListIterator)l.iterator());
228 // System.out.println("calc result: " + res);
229
return SKIP_BODY;
230   }
231
232   /**
233    * Output the result of the calculation
234    *
235    * @return EVAL_PAGE
236    */

237
238   public final int doEndTag() throws JspException
239   {
240     try {
241       pageContext.getOut().write("" + res);
242     } catch(Exception JavaDoc e) {
243       throw new JspException("IO Error: " + e.getMessage());
244     }
245     return EVAL_PAGE;
246   }
247
248   /**
249    * Do the calculation
250    *
251    * @return String - result of the calculation as an integer
252    */

253   private long calculate(ListIterator li) throws JspException
254   {
255     long a = 0;
256     long res = 0;
257     StringBuffer JavaDoc sb = null;
258     Object JavaDoc o;
259     Long JavaDoc v;
260     boolean aset = false;
261
262     // Loop through the list of integers and operators
263
// performing calculations
264
while(li.hasNext()) {
265       o = li.next();
266       if( o.getClass().getName().equals("java.lang.Long") ) {
267     v = (Long JavaDoc)o;
268 // System.out.println("Calc value: " + v.longValue());
269
if( aset ) {
270       if( sb == null ) {
271         throw new JspException("Jive tag calc missing operator.");
272       }
273 // System.out.println("Calc operator: " + sb);
274
if( sb.toString().equals("*") )
275         a *= v.longValue();
276       else if( sb.toString().equals("+") )
277         a += v.longValue();
278           else if( sb.toString().equals("/") )
279             a /= v.longValue();
280           else if( sb.toString().equals("-") )
281             a -= v.longValue();
282       else
283         throw new JspException("Jive tag calc invalid operator \"" +
284         sb + "\"");
285     } else {
286       aset = true;
287       a = v.longValue();
288     }
289       } else {
290     sb = (StringBuffer JavaDoc)o;
291         if( !aset ) {
292       throw new JspException("Jive tag calc must start with a number.");
293     }
294       }
295     }
296     return a;
297   }
298
299 }
300
Popular Tags