KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > jasper > runtime > JspRuntimeLibrary


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17
18 package org.apache.jasper.runtime;
19
20 import java.beans.PropertyEditor JavaDoc;
21 import java.beans.PropertyEditorManager JavaDoc;
22 import java.io.ByteArrayOutputStream JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.io.OutputStreamWriter JavaDoc;
25 import java.lang.reflect.Method JavaDoc;
26 import java.security.AccessController JavaDoc;
27 import java.security.PrivilegedActionException JavaDoc;
28 import java.security.PrivilegedExceptionAction JavaDoc;
29 import java.util.Enumeration JavaDoc;
30
31 import javax.servlet.RequestDispatcher JavaDoc;
32 import javax.servlet.ServletException JavaDoc;
33 import javax.servlet.ServletRequest JavaDoc;
34 import javax.servlet.ServletResponse JavaDoc;
35 import javax.servlet.http.HttpServletRequest JavaDoc;
36 import javax.servlet.jsp.JspWriter JavaDoc;
37 import javax.servlet.jsp.PageContext JavaDoc;
38 import javax.servlet.jsp.tagext.BodyContent JavaDoc;
39
40 import org.apache.jasper.JasperException;
41 import org.apache.jasper.compiler.Localizer;
42
43 /**
44  * Bunch of util methods that are used by code generated for useBean,
45  * getProperty and setProperty.
46  *
47  * The __begin, __end stuff is there so that the JSP engine can
48  * actually parse this file and inline them if people don't want
49  * runtime dependencies on this class. However, I'm not sure if that
50  * works so well right now. It got forgotten at some point. -akv
51  *
52  * @author Mandar Raje
53  * @author Shawn Bayern
54  */

55 public class JspRuntimeLibrary {
56     
57     private static final String JavaDoc SERVLET_EXCEPTION
58     = "javax.servlet.error.exception";
59     private static final String JavaDoc JSP_EXCEPTION
60     = "javax.servlet.jsp.jspException";
61
62     protected static class PrivilegedIntrospectHelper
63     implements PrivilegedExceptionAction JavaDoc {
64
65     private Object JavaDoc bean;
66     private String JavaDoc prop;
67     private String JavaDoc value;
68     private ServletRequest JavaDoc request;
69     private String JavaDoc param;
70     private boolean ignoreMethodNF;
71
72         PrivilegedIntrospectHelper(Object JavaDoc bean, String JavaDoc prop,
73                                    String JavaDoc value, ServletRequest JavaDoc request,
74                                    String JavaDoc param, boolean ignoreMethodNF)
75         {
76         this.bean = bean;
77         this.prop = prop;
78         this.value = value;
79             this.request = request;
80         this.param = param;
81         this.ignoreMethodNF = ignoreMethodNF;
82         }
83          
84         public Object JavaDoc run() throws JasperException {
85         internalIntrospecthelper(
86                 bean,prop,value,request,param,ignoreMethodNF);
87             return null;
88         }
89     }
90
91     /**
92      * Returns the value of the javax.servlet.error.exception request
93      * attribute value, if present, otherwise the value of the
94      * javax.servlet.jsp.jspException request attribute value.
95      *
96      * This method is called at the beginning of the generated servlet code
97      * for a JSP error page, when the "exception" implicit scripting language
98      * variable is initialized.
99      */

100     public static Throwable JavaDoc getThrowable(ServletRequest JavaDoc request) {
101     Throwable JavaDoc error = (Throwable JavaDoc) request.getAttribute(SERVLET_EXCEPTION);
102     if (error == null) {
103         error = (Throwable JavaDoc) request.getAttribute(JSP_EXCEPTION);
104         if (error != null) {
105         /*
106          * The only place that sets JSP_EXCEPTION is
107          * PageContextImpl.handlePageException(). It really should set
108          * SERVLET_EXCEPTION, but that would interfere with the
109          * ErrorReportValve. Therefore, if JSP_EXCEPTION is set, we
110          * need to set SERVLET_EXCEPTION.
111          */

112         request.setAttribute(SERVLET_EXCEPTION, error);
113         }
114     }
115
116     return error;
117     }
118
119     public static boolean coerceToBoolean(String JavaDoc s) {
120     if (s == null || s.length() == 0)
121         return false;
122     else
123         return Boolean.valueOf(s).booleanValue();
124     }
125
126     public static byte coerceToByte(String JavaDoc s) {
127     if (s == null || s.length() == 0)
128         return (byte) 0;
129     else
130         return Byte.valueOf(s).byteValue();
131     }
132
133     public static char coerceToChar(String JavaDoc s) {
134     if (s == null || s.length() == 0) {
135         return (char) 0;
136     } else {
137         // this trick avoids escaping issues
138
return (char)(int) s.charAt(0);
139     }
140     }
141
142     public static double coerceToDouble(String JavaDoc s) {
143     if (s == null || s.length() == 0)
144         return (double) 0;
145     else
146         return Double.valueOf(s).doubleValue();
147     }
148
149     public static float coerceToFloat(String JavaDoc s) {
150     if (s == null || s.length() == 0)
151         return (float) 0;
152     else
153         return Float.valueOf(s).floatValue();
154     }
155
156     public static int coerceToInt(String JavaDoc s) {
157     if (s == null || s.length() == 0)
158         return 0;
159     else
160         return Integer.valueOf(s).intValue();
161     }
162
163     public static short coerceToShort(String JavaDoc s) {
164     if (s == null || s.length() == 0)
165         return (short) 0;
166     else
167         return Short.valueOf(s).shortValue();
168     }
169
170     public static long coerceToLong(String JavaDoc s) {
171     if (s == null || s.length() == 0)
172         return (long) 0;
173     else
174         return Long.valueOf(s).longValue();
175     }
176
177     public static Object JavaDoc coerce(String JavaDoc s, Class JavaDoc target) {
178
179     boolean isNullOrEmpty = (s == null || s.length() == 0);
180
181     if (target == Boolean JavaDoc.class) {
182         if (isNullOrEmpty) {
183         s = "false";
184         }
185         return new Boolean JavaDoc(s);
186     } else if (target == Byte JavaDoc.class) {
187         if (isNullOrEmpty)
188         return new Byte JavaDoc((byte) 0);
189         else
190         return new Byte JavaDoc(s);
191     } else if (target == Character JavaDoc.class) {
192         if (isNullOrEmpty)
193         return new Character JavaDoc((char) 0);
194         else
195         return new Character JavaDoc(s.charAt(0));
196     } else if (target == Double JavaDoc.class) {
197         if (isNullOrEmpty)
198         return new Double JavaDoc(0);
199         else
200         return new Double JavaDoc(s);
201     } else if (target == Float JavaDoc.class) {
202         if (isNullOrEmpty)
203         return new Float JavaDoc(0);
204         else
205         return new Float JavaDoc(s);
206     } else if (target == Integer JavaDoc.class) {
207         if (isNullOrEmpty)
208         return new Integer JavaDoc(0);
209         else
210         return new Integer JavaDoc(s);
211     } else if (target == Short JavaDoc.class) {
212         if (isNullOrEmpty)
213         return new Short JavaDoc((short) 0);
214         else
215         return new Short JavaDoc(s);
216     } else if (target == Long JavaDoc.class) {
217         if (isNullOrEmpty)
218         return new Long JavaDoc(0);
219         else
220         return new Long JavaDoc(s);
221     } else {
222         return null;
223     }
224     }
225
226    // __begin convertMethod
227
public static Object JavaDoc convert(String JavaDoc propertyName, String JavaDoc s, Class JavaDoc t,
228                  Class JavaDoc propertyEditorClass)
229        throws JasperException
230     {
231         try {
232             if (s == null) {
233                 if (t.equals(Boolean JavaDoc.class) || t.equals(Boolean.TYPE))
234                     s = "false";
235                 else
236                     return null;
237             }
238         if (propertyEditorClass != null) {
239         return getValueFromBeanInfoPropertyEditor(
240                     t, propertyName, s, propertyEditorClass);
241         } else if ( t.equals(Boolean JavaDoc.class) || t.equals(Boolean.TYPE) ) {
242                 if (s.equalsIgnoreCase("on") || s.equalsIgnoreCase("true"))
243                     s = "true";
244                 else
245                     s = "false";
246                 return new Boolean JavaDoc(s);
247             } else if ( t.equals(Byte JavaDoc.class) || t.equals(Byte.TYPE) ) {
248                 return new Byte JavaDoc(s);
249             } else if (t.equals(Character JavaDoc.class) || t.equals(Character.TYPE)) {
250                 return s.length() > 0 ? new Character JavaDoc(s.charAt(0)) : null;
251             } else if ( t.equals(Short JavaDoc.class) || t.equals(Short.TYPE) ) {
252                 return new Short JavaDoc(s);
253             } else if ( t.equals(Integer JavaDoc.class) || t.equals(Integer.TYPE) ) {
254                 return new Integer JavaDoc(s);
255             } else if ( t.equals(Float JavaDoc.class) || t.equals(Float.TYPE) ) {
256                 return new Float JavaDoc(s);
257             } else if ( t.equals(Long JavaDoc.class) || t.equals(Long.TYPE) ) {
258                 return new Long JavaDoc(s);
259             } else if ( t.equals(Double JavaDoc.class) || t.equals(Double.TYPE) ) {
260                 return new Double JavaDoc(s);
261             } else if ( t.equals(String JavaDoc.class) ) {
262                 return s;
263             } else if ( t.equals(java.io.File JavaDoc.class) ) {
264                 return new java.io.File JavaDoc(s);
265             } else if (t.getName().equals("java.lang.Object")) {
266                 return new Object JavaDoc[] {s};
267         } else {
268         return getValueFromPropertyEditorManager(
269                                             t, propertyName, s);
270             }
271         } catch (Exception JavaDoc ex) {
272             throw new JasperException(ex);
273         }
274     }
275     // __end convertMethod
276

277     // __begin introspectMethod
278
public static void introspect(Object JavaDoc bean, ServletRequest JavaDoc request)
279                                   throws JasperException
280     {
281     Enumeration JavaDoc e = request.getParameterNames();
282     while ( e.hasMoreElements() ) {
283         String JavaDoc name = (String JavaDoc) e.nextElement();
284         String JavaDoc value = request.getParameter(name);
285         introspecthelper(bean, name, value, request, name, true);
286     }
287     }
288     // __end introspectMethod
289

290     // __begin introspecthelperMethod
291
public static void introspecthelper(Object JavaDoc bean, String JavaDoc prop,
292                                         String JavaDoc value, ServletRequest JavaDoc request,
293                                         String JavaDoc param, boolean ignoreMethodNF)
294                                         throws JasperException
295     {
296         if( System.getSecurityManager() != null ) {
297             try {
298                 PrivilegedIntrospectHelper dp =
299             new PrivilegedIntrospectHelper(
300             bean,prop,value,request,param,ignoreMethodNF);
301                 AccessController.doPrivileged(dp);
302             } catch( PrivilegedActionException JavaDoc pe) {
303                 Exception JavaDoc e = pe.getException();
304                 throw (JasperException)e;
305             }
306         } else {
307             internalIntrospecthelper(
308         bean,prop,value,request,param,ignoreMethodNF);
309         }
310     }
311
312     private static void internalIntrospecthelper(Object JavaDoc bean, String JavaDoc prop,
313                     String JavaDoc value, ServletRequest JavaDoc request,
314                     String JavaDoc param, boolean ignoreMethodNF)
315                     throws JasperException
316     {
317         Method JavaDoc method = null;
318         Class JavaDoc type = null;
319         Class JavaDoc propertyEditorClass = null;
320     try {
321         java.beans.BeanInfo JavaDoc info
322         = java.beans.Introspector.getBeanInfo(bean.getClass());
323         if ( info != null ) {
324         java.beans.PropertyDescriptor JavaDoc pd[]
325             = info.getPropertyDescriptors();
326         for (int i = 0 ; i < pd.length ; i++) {
327             if ( pd[i].getName().equals(prop) ) {
328             method = pd[i].getWriteMethod();
329             type = pd[i].getPropertyType();
330             propertyEditorClass = pd[i].getPropertyEditorClass();
331             break;
332             }
333         }
334         }
335         if ( method != null ) {
336         if (type.isArray()) {
337                     if (request == null) {
338             throw new JasperException(
339                     Localizer.getMessage("jsp.error.beans.setproperty.noindexset"));
340                     }
341             Class JavaDoc t = type.getComponentType();
342             String JavaDoc[] values = request.getParameterValues(param);
343             //XXX Please check.
344
if(values == null) return;
345             if(t.equals(String JavaDoc.class)) {
346             method.invoke(bean, new Object JavaDoc[] { values });
347             } else {
348             Object JavaDoc tmpval = null;
349             createTypedArray (prop, bean, method, values, t,
350                       propertyEditorClass);
351             }
352         } else {
353             if(value == null || (param != null && value.equals(""))) return;
354             Object JavaDoc oval = convert(prop, value, type, propertyEditorClass);
355             if ( oval != null )
356             method.invoke(bean, new Object JavaDoc[] { oval });
357         }
358         }
359     } catch (Exception JavaDoc ex) {
360         throw new JasperException(ex);
361     }
362         if (!ignoreMethodNF && (method == null)) {
363             if (type == null) {
364         throw new JasperException(
365                     Localizer.getMessage("jsp.error.beans.noproperty",
366                      prop,
367                      bean.getClass().getName()));
368             } else {
369         throw new JasperException(
370                 Localizer.getMessage("jsp.error.beans.nomethod.setproperty",
371                      prop,
372                      type.getName(),
373                      bean.getClass().getName()));
374             }
375         }
376     }
377     // __end introspecthelperMethod
378

379     //-------------------------------------------------------------------
380
// functions to convert builtin Java data types to string.
381
//-------------------------------------------------------------------
382
// __begin toStringMethod
383
public static String JavaDoc toString(Object JavaDoc o) {
384         return String.valueOf(o);
385     }
386
387     public static String JavaDoc toString(byte b) {
388         return new Byte JavaDoc(b).toString();
389     }
390
391     public static String JavaDoc toString(boolean b) {
392         return new Boolean JavaDoc(b).toString();
393     }
394
395     public static String JavaDoc toString(short s) {
396         return new Short JavaDoc(s).toString();
397     }
398
399     public static String JavaDoc toString(int i) {
400         return new Integer JavaDoc(i).toString();
401     }
402
403     public static String JavaDoc toString(float f) {
404         return new Float JavaDoc(f).toString();
405     }
406
407     public static String JavaDoc toString(long l) {
408         return new Long JavaDoc(l).toString();
409     }
410
411     public static String JavaDoc toString(double d) {
412         return new Double JavaDoc(d).toString();
413     }
414
415     public static String JavaDoc toString(char c) {
416         return new Character JavaDoc(c).toString();
417     }
418     // __end toStringMethod
419

420
421     /**
422      * Create a typed array.
423      * This is a special case where params are passed through
424      * the request and the property is indexed.
425      */

426     public static void createTypedArray(String JavaDoc propertyName,
427                     Object JavaDoc bean,
428                     Method JavaDoc method,
429                     String JavaDoc[] values,
430                     Class JavaDoc t,
431                     Class JavaDoc propertyEditorClass)
432             throws JasperException {
433
434     try {
435         if (propertyEditorClass != null) {
436         Object JavaDoc[] tmpval = new Integer JavaDoc[values.length];
437         for (int i=0; i<values.length; i++) {
438             tmpval[i] = getValueFromBeanInfoPropertyEditor(
439                             t, propertyName, values[i], propertyEditorClass);
440         }
441         method.invoke (bean, new Object JavaDoc[] {tmpval});
442         } else if (t.equals(Integer JavaDoc.class)) {
443         Integer JavaDoc []tmpval = new Integer JavaDoc[values.length];
444         for (int i = 0 ; i < values.length; i++)
445             tmpval[i] = new Integer JavaDoc (values[i]);
446         method.invoke (bean, new Object JavaDoc[] {tmpval});
447         } else if (t.equals(Byte JavaDoc.class)) {
448         Byte JavaDoc[] tmpval = new Byte JavaDoc[values.length];
449         for (int i = 0 ; i < values.length; i++)
450             tmpval[i] = new Byte JavaDoc (values[i]);
451         method.invoke (bean, new Object JavaDoc[] {tmpval});
452         } else if (t.equals(Boolean JavaDoc.class)) {
453         Boolean JavaDoc[] tmpval = new Boolean JavaDoc[values.length];
454         for (int i = 0 ; i < values.length; i++)
455             tmpval[i] = new Boolean JavaDoc (values[i]);
456         method.invoke (bean, new Object JavaDoc[] {tmpval});
457         } else if (t.equals(Short JavaDoc.class)) {
458         Short JavaDoc[] tmpval = new Short JavaDoc[values.length];
459         for (int i = 0 ; i < values.length; i++)
460             tmpval[i] = new Short JavaDoc (values[i]);
461         method.invoke (bean, new Object JavaDoc[] {tmpval});
462         } else if (t.equals(Long JavaDoc.class)) {
463         Long JavaDoc[] tmpval = new Long JavaDoc[values.length];
464         for (int i = 0 ; i < values.length; i++)
465             tmpval[i] = new Long JavaDoc (values[i]);
466         method.invoke (bean, new Object JavaDoc[] {tmpval});
467         } else if (t.equals(Double JavaDoc.class)) {
468         Double JavaDoc[] tmpval = new Double JavaDoc[values.length];
469         for (int i = 0 ; i < values.length; i++)
470             tmpval[i] = new Double JavaDoc (values[i]);
471         method.invoke (bean, new Object JavaDoc[] {tmpval});
472         } else if (t.equals(Float JavaDoc.class)) {
473         Float JavaDoc[] tmpval = new Float JavaDoc[values.length];
474         for (int i = 0 ; i < values.length; i++)
475             tmpval[i] = new Float JavaDoc (values[i]);
476         method.invoke (bean, new Object JavaDoc[] {tmpval});
477         } else if (t.equals(Character JavaDoc.class)) {
478         Character JavaDoc[] tmpval = new Character JavaDoc[values.length];
479         for (int i = 0 ; i < values.length; i++)
480             tmpval[i] = new Character JavaDoc(values[i].charAt(0));
481         method.invoke (bean, new Object JavaDoc[] {tmpval});
482         } else if (t.equals(int.class)) {
483         int []tmpval = new int[values.length];
484         for (int i = 0 ; i < values.length; i++)
485             tmpval[i] = Integer.parseInt (values[i]);
486         method.invoke (bean, new Object JavaDoc[] {tmpval});
487         } else if (t.equals(byte.class)) {
488         byte[] tmpval = new byte[values.length];
489         for (int i = 0 ; i < values.length; i++)
490             tmpval[i] = Byte.parseByte (values[i]);
491         method.invoke (bean, new Object JavaDoc[] {tmpval});
492         } else if (t.equals(boolean.class)) {
493         boolean[] tmpval = new boolean[values.length];
494         for (int i = 0 ; i < values.length; i++)
495             tmpval[i] = (Boolean.valueOf(values[i])).booleanValue();
496         method.invoke (bean, new Object JavaDoc[] {tmpval});
497         } else if (t.equals(short.class)) {
498         short[] tmpval = new short[values.length];
499         for (int i = 0 ; i < values.length; i++)
500             tmpval[i] = Short.parseShort (values[i]);
501         method.invoke (bean, new Object JavaDoc[] {tmpval});
502         } else if (t.equals(long.class)) {
503         long[] tmpval = new long[values.length];
504         for (int i = 0 ; i < values.length; i++)
505             tmpval[i] = Long.parseLong (values[i]);
506         method.invoke (bean, new Object JavaDoc[] {tmpval});
507         } else if (t.equals(double.class)) {
508         double[] tmpval = new double[values.length];
509         for (int i = 0 ; i < values.length; i++)
510             tmpval[i] = Double.valueOf(values[i]).doubleValue();
511         method.invoke (bean, new Object JavaDoc[] {tmpval});
512         } else if (t.equals(float.class)) {
513         float[] tmpval = new float[values.length];
514         for (int i = 0 ; i < values.length; i++)
515             tmpval[i] = Float.valueOf(values[i]).floatValue();
516         method.invoke (bean, new Object JavaDoc[] {tmpval});
517         } else if (t.equals(char.class)) {
518         char[] tmpval = new char[values.length];
519         for (int i = 0 ; i < values.length; i++)
520             tmpval[i] = values[i].charAt(0);
521         method.invoke (bean, new Object JavaDoc[] {tmpval});
522         } else {
523         Object JavaDoc[] tmpval = new Integer JavaDoc[values.length];
524         for (int i=0; i<values.length; i++) {
525             tmpval[i] =
526             getValueFromPropertyEditorManager(
527                                             t, propertyName, values[i]);
528         }
529         method.invoke (bean, new Object JavaDoc[] {tmpval});
530         }
531     } catch (Exception JavaDoc ex) {
532             throw new JasperException ("error in invoking method", ex);
533     }
534     }
535
536     /**
537      * Escape special shell characters.
538      * @param unescString The string to shell-escape
539      * @return The escaped shell string.
540      */

541
542     public static String JavaDoc escapeQueryString(String JavaDoc unescString) {
543     if ( unescString == null )
544         return null;
545    
546     String JavaDoc escString = "";
547     String JavaDoc shellSpChars = "&;`'\"|*?~<>^()[]{}$\\\n";
548    
549     for(int index=0; index<unescString.length(); index++) {
550         char nextChar = unescString.charAt(index);
551
552         if( shellSpChars.indexOf(nextChar) != -1 )
553         escString += "\\";
554
555         escString += nextChar;
556     }
557     return escString;
558     }
559
560     /**
561      * Decode an URL formatted string.
562      * @param encoded The string to decode.
563      * @return The decoded string.
564      */

565
566     public static String JavaDoc decode(String JavaDoc encoded) {
567         // speedily leave if we're not needed
568
if (encoded == null) return null;
569         if (encoded.indexOf('%') == -1 && encoded.indexOf('+') == -1)
570         return encoded;
571
572     //allocate the buffer - use byte[] to avoid calls to new.
573
byte holdbuffer[] = new byte[encoded.length()];
574
575         char holdchar;
576         int bufcount = 0;
577
578         for (int count = 0; count < encoded.length(); count++) {
579         char cur = encoded.charAt(count);
580             if (cur == '%') {
581             holdbuffer[bufcount++] =
582           (byte)Integer.parseInt(encoded.substring(count+1,count+3),16);
583                 if (count + 2 >= encoded.length())
584                     count = encoded.length();
585                 else
586                     count += 2;
587             } else if (cur == '+') {
588         holdbuffer[bufcount++] = (byte) ' ';
589         } else {
590             holdbuffer[bufcount++] = (byte) cur;
591             }
592         }
593     // REVISIT -- remedy for Deprecated warning.
594
//return new String(holdbuffer,0,0,bufcount);
595
return new String JavaDoc(holdbuffer,0,bufcount);
596     }
597
598     // __begin lookupReadMethodMethod
599
public static Object JavaDoc handleGetProperty(Object JavaDoc o, String JavaDoc prop)
600     throws JasperException {
601         if (o == null) {
602         throw new JasperException(
603                 Localizer.getMessage("jsp.error.beans.nullbean"));
604         }
605     Object JavaDoc value = null;
606         try {
607             Method JavaDoc method = getReadMethod(o.getClass(), prop);
608         value = method.invoke(o, (Object JavaDoc[]) null);
609         } catch (Exception JavaDoc ex) {
610         throw new JasperException (ex);
611         }
612         return value;
613     }
614     // __end lookupReadMethodMethod
615

616     // handles <jsp:setProperty> with EL expression for 'value' attribute
617
/** Use proprietaryEvaluate
618     public static void handleSetPropertyExpression(Object bean,
619         String prop, String expression, PageContext pageContext,
620         VariableResolver variableResolver, FunctionMapper functionMapper )
621     throws JasperException
622     {
623     try {
624             Method method = getWriteMethod(bean.getClass(), prop);
625         method.invoke(bean, new Object[] {
626         pageContext.getExpressionEvaluator().evaluate(
627             expression,
628             method.getParameterTypes()[0],
629                     variableResolver,
630                     functionMapper,
631                     null )
632         });
633     } catch (Exception ex) {
634         throw new JasperException(ex);
635     }
636     }
637 **/

638     public static void handleSetPropertyExpression(Object JavaDoc bean,
639         String JavaDoc prop, String JavaDoc expression, PageContext JavaDoc pageContext,
640     ProtectedFunctionMapper functionMapper )
641         throws JasperException
642     {
643         try {
644             Method JavaDoc method = getWriteMethod(bean.getClass(), prop);
645             method.invoke(bean, new Object JavaDoc[] {
646                 PageContextImpl.proprietaryEvaluate(
647                     expression,
648                     method.getParameterTypes()[0],
649             pageContext,
650                     functionMapper,
651                     false )
652             });
653         } catch (Exception JavaDoc ex) {
654             throw new JasperException(ex);
655         }
656     }
657
658     public static void handleSetProperty(Object JavaDoc bean, String JavaDoc prop,
659                      Object JavaDoc value)
660     throws JasperException
661     {
662     try {
663             Method JavaDoc method = getWriteMethod(bean.getClass(), prop);
664         method.invoke(bean, new Object JavaDoc[] { value });
665     } catch (Exception JavaDoc ex) {
666         throw new JasperException(ex);
667     }
668     }
669     
670     public static void handleSetProperty(Object JavaDoc bean, String JavaDoc prop,
671                      int value)
672     throws JasperException
673     {
674     try {
675             Method JavaDoc method = getWriteMethod(bean.getClass(), prop);
676         method.invoke(bean, new Object JavaDoc[] { new Integer JavaDoc(value) });
677     } catch (Exception JavaDoc ex) {
678         throw new JasperException(ex);
679     }
680     }
681     
682     public static void handleSetProperty(Object JavaDoc bean, String JavaDoc prop,
683                      short value)
684     throws JasperException
685     {
686     try {
687             Method JavaDoc method = getWriteMethod(bean.getClass(), prop);
688         method.invoke(bean, new Object JavaDoc[] { new Short JavaDoc(value) });
689     } catch (Exception JavaDoc ex) {
690         throw new JasperException(ex);
691     }
692     }
693     
694     public static void handleSetProperty(Object JavaDoc bean, String JavaDoc prop,
695                      long value)
696     throws JasperException
697     {
698     try {
699             Method JavaDoc method = getWriteMethod(bean.getClass(), prop);
700         method.invoke(bean, new Object JavaDoc[] { new Long JavaDoc(value) });
701     } catch (Exception JavaDoc ex) {
702         throw new JasperException(ex);
703     }
704     }
705     
706     public static void handleSetProperty(Object JavaDoc bean, String JavaDoc prop,
707                      double value)
708     throws JasperException
709     {
710     try {
711             Method JavaDoc method = getWriteMethod(bean.getClass(), prop);
712         method.invoke(bean, new Object JavaDoc[] { new Double JavaDoc(value) });
713     } catch (Exception JavaDoc ex) {
714         throw new JasperException(ex);
715     }
716     }
717     
718     public static void handleSetProperty(Object JavaDoc bean, String JavaDoc prop,
719                      float value)
720     throws JasperException
721     {
722     try {
723             Method JavaDoc method = getWriteMethod(bean.getClass(), prop);
724         method.invoke(bean, new Object JavaDoc[] { new Float JavaDoc(value) });
725     } catch (Exception JavaDoc ex) {
726         throw new JasperException(ex);
727     }
728     }
729     
730     public static void handleSetProperty(Object JavaDoc bean, String JavaDoc prop,
731                      char value)
732     throws JasperException
733     {
734     try {
735             Method JavaDoc method = getWriteMethod(bean.getClass(), prop);
736         method.invoke(bean, new Object JavaDoc[] { new Character JavaDoc(value) });
737     } catch (Exception JavaDoc ex) {
738         throw new JasperException(ex);
739     }
740     }
741
742     public static void handleSetProperty(Object JavaDoc bean, String JavaDoc prop,
743                      byte value)
744     throws JasperException
745     {
746     try {
747             Method JavaDoc method = getWriteMethod(bean.getClass(), prop);
748         method.invoke(bean, new Object JavaDoc[] { new Byte JavaDoc(value) });
749     } catch (Exception JavaDoc ex) {
750         throw new JasperException(ex);
751     }
752     }
753     
754     public static void handleSetProperty(Object JavaDoc bean, String JavaDoc prop,
755                      boolean value)
756     throws JasperException
757     {
758     try {
759             Method JavaDoc method = getWriteMethod(bean.getClass(), prop);
760         method.invoke(bean, new Object JavaDoc[] { new Boolean JavaDoc(value) });
761     } catch (Exception JavaDoc ex) {
762         throw new JasperException(ex);
763     }
764     }
765     
766     public static Method JavaDoc getWriteMethod(Class JavaDoc beanClass, String JavaDoc prop)
767     throws JasperException {
768     Method JavaDoc method = null;
769         Class JavaDoc type = null;
770     try {
771         java.beans.BeanInfo JavaDoc info
772                 = java.beans.Introspector.getBeanInfo(beanClass);
773         if ( info != null ) {
774         java.beans.PropertyDescriptor JavaDoc pd[]
775             = info.getPropertyDescriptors();
776         for (int i = 0 ; i < pd.length ; i++) {
777             if ( pd[i].getName().equals(prop) ) {
778             method = pd[i].getWriteMethod();
779             type = pd[i].getPropertyType();
780             break;
781             }
782         }
783             } else {
784                 // just in case introspection silently fails.
785
throw new JasperException(
786                     Localizer.getMessage("jsp.error.beans.nobeaninfo",
787                      beanClass.getName()));
788             }
789         } catch (Exception JavaDoc ex) {
790             throw new JasperException (ex);
791         }
792         if (method == null) {
793             if (type == null) {
794         throw new JasperException(
795                         Localizer.getMessage("jsp.error.beans.noproperty",
796                          prop,
797                          beanClass.getName()));
798             } else {
799         throw new JasperException(
800             Localizer.getMessage("jsp.error.beans.nomethod.setproperty",
801                      prop,
802                      type.getName(),
803                      beanClass.getName()));
804             }
805         }
806         return method;
807     }
808
809     public static Method JavaDoc getReadMethod(Class JavaDoc beanClass, String JavaDoc prop)
810         throws JasperException {
811
812         Method JavaDoc method = null;
813         Class JavaDoc type = null;
814         try {
815             java.beans.BeanInfo JavaDoc info
816                 = java.beans.Introspector.getBeanInfo(beanClass);
817             if ( info != null ) {
818                 java.beans.PropertyDescriptor JavaDoc pd[]
819                     = info.getPropertyDescriptors();
820                 for (int i = 0 ; i < pd.length ; i++) {
821                     if ( pd[i].getName().equals(prop) ) {
822                         method = pd[i].getReadMethod();
823                         type = pd[i].getPropertyType();
824                         break;
825                     }
826                 }
827             } else {
828                 // just in case introspection silently fails.
829
throw new JasperException(
830                     Localizer.getMessage("jsp.error.beans.nobeaninfo",
831                      beanClass.getName()));
832         }
833     } catch (Exception JavaDoc ex) {
834         throw new JasperException (ex);
835     }
836         if (method == null) {
837             if (type == null) {
838         throw new JasperException(
839                     Localizer.getMessage("jsp.error.beans.noproperty", prop,
840                      beanClass.getName()));
841             } else {
842         throw new JasperException(
843                     Localizer.getMessage("jsp.error.beans.nomethod", prop,
844                      beanClass.getName()));
845             }
846         }
847
848     return method;
849     }
850
851     //*********************************************************************
852
// PropertyEditor Support
853

854     public static Object JavaDoc getValueFromBeanInfoPropertyEditor(
855                    Class JavaDoc attrClass, String JavaDoc attrName, String JavaDoc attrValue,
856                Class JavaDoc propertyEditorClass)
857     throws JasperException
858     {
859     try {
860         PropertyEditor JavaDoc pe = (PropertyEditor JavaDoc)propertyEditorClass.newInstance();
861         pe.setAsText(attrValue);
862         return pe.getValue();
863     } catch (Exception JavaDoc ex) {
864         throw new JasperException(
865                 Localizer.getMessage("jsp.error.beans.property.conversion",
866                      attrValue, attrClass.getName(), attrName,
867                      ex.getMessage()));
868     }
869     }
870
871     public static Object JavaDoc getValueFromPropertyEditorManager(
872                  Class JavaDoc attrClass, String JavaDoc attrName, String JavaDoc attrValue)
873     throws JasperException
874     {
875     try {
876         PropertyEditor JavaDoc propEditor =
877         PropertyEditorManager.findEditor(attrClass);
878         if (propEditor != null) {
879         propEditor.setAsText(attrValue);
880         return propEditor.getValue();
881         } else {
882         throw new IllegalArgumentException JavaDoc(
883                     Localizer.getMessage("jsp.error.beans.propertyeditor.notregistered"));
884         }
885     } catch (IllegalArgumentException JavaDoc ex) {
886         throw new JasperException(
887                 Localizer.getMessage("jsp.error.beans.property.conversion",
888                      attrValue, attrClass.getName(), attrName,
889                      ex.getMessage()));
890     }
891     }
892
893
894     // ************************************************************************
895
// General Purpose Runtime Methods
896
// ************************************************************************
897

898
899     /**
900      * Convert a possibly relative resource path into a context-relative
901      * resource path that starts with a '/'.
902      *
903      * @param request The servlet request we are processing
904      * @param relativePath The possibly relative resource path
905      */

906     public static String JavaDoc getContextRelativePath(ServletRequest JavaDoc request,
907                                                 String JavaDoc relativePath) {
908
909         if (relativePath.startsWith("/"))
910             return (relativePath);
911         if (!(request instanceof HttpServletRequest JavaDoc))
912             return (relativePath);
913         HttpServletRequest JavaDoc hrequest = (HttpServletRequest JavaDoc) request;
914         String JavaDoc uri = (String JavaDoc)
915             request.getAttribute("javax.servlet.include.servlet_path");
916         if (uri != null) {
917             String JavaDoc pathInfo = (String JavaDoc)
918                 request.getAttribute("javax.servlet.include.path_info");
919             if (pathInfo == null) {
920                 if (uri.lastIndexOf('/') >= 0)
921                     uri = uri.substring(0, uri.lastIndexOf('/'));
922             }
923         }
924         else {
925             uri = hrequest.getServletPath();
926             if (uri.lastIndexOf('/') >= 0)
927                 uri = uri.substring(0, uri.lastIndexOf('/'));
928         }
929         return uri + '/' + relativePath;
930
931     }
932
933
934     /**
935      * Perform a RequestDispatcher.include() operation, with optional flushing
936      * of the response beforehand.
937      *
938      * @param request The servlet request we are processing
939      * @param response The servlet response we are processing
940      * @param relativePath The relative path of the resource to be included
941      * @param out The Writer to whom we are currently writing
942      * @param flush Should we flush before the include is processed?
943      *
944      * @exception IOException if thrown by the included servlet
945      * @exception ServletException if thrown by the included servlet
946      */

947     public static void include(ServletRequest JavaDoc request,
948                                ServletResponse JavaDoc response,
949                                String JavaDoc relativePath,
950                                JspWriter JavaDoc out,
951                                boolean flush)
952         throws IOException JavaDoc, ServletException JavaDoc {
953
954         if (flush && !(out instanceof BodyContent JavaDoc))
955             out.flush();
956
957         // FIXME - It is tempting to use request.getRequestDispatcher() to
958
// resolve a relative path directly, but Catalina currently does not
959
// take into account whether the caller is inside a RequestDispatcher
960
// include or not. Whether Catalina *should* take that into account
961
// is a spec issue currently under review. In the mean time,
962
// replicate Jasper's previous behavior
963

964         String JavaDoc resourcePath = getContextRelativePath(request, relativePath);
965         RequestDispatcher JavaDoc rd = request.getRequestDispatcher(resourcePath);
966
967         rd.include(request,
968                    new ServletResponseWrapperInclude(response, out));
969
970     }
971
972     /**
973      * URL encodes a string, based on the supplied character encoding.
974      * This performs the same function as java.next.URLEncode.encode
975      * in J2SDK1.4, and should be removed if the only platform supported
976      * is 1.4 or higher.
977      * @param s The String to be URL encoded.
978      * @param enc The character encoding
979      * @return The URL encoded String
980      */

981     public static String JavaDoc URLEncode(String JavaDoc s, String JavaDoc enc) {
982
983     if (s == null) {
984         return "null";
985     }
986
987     if (enc == null) {
988         enc = "ISO-8859-1"; // The default request encoding
989
}
990
991     StringBuffer JavaDoc out = new StringBuffer JavaDoc(s.length());
992     ByteArrayOutputStream JavaDoc buf = new ByteArrayOutputStream JavaDoc();
993     OutputStreamWriter JavaDoc writer = null;
994     try {
995         writer = new OutputStreamWriter JavaDoc(buf, enc);
996     } catch (java.io.UnsupportedEncodingException JavaDoc ex) {
997         // Use the default encoding?
998
writer = new OutputStreamWriter JavaDoc(buf);
999     }
1000    
1001    for (int i = 0; i < s.length(); i++) {
1002        int c = s.charAt(i);
1003        if (c == ' ') {
1004        out.append('+');
1005        } else if (isSafeChar(c)) {
1006        out.append((char)c);
1007        } else {
1008        // convert to external encoding before hex conversion
1009
try {
1010            writer.write(c);
1011            writer.flush();
1012        } catch(IOException JavaDoc e) {
1013            buf.reset();
1014            continue;
1015        }
1016        byte[] ba = buf.toByteArray();
1017        for (int j = 0; j < ba.length; j++) {
1018            out.append('%');
1019            // Converting each byte in the buffer
1020
out.append(Character.forDigit((ba[j]>>4) & 0xf, 16));
1021            out.append(Character.forDigit(ba[j] & 0xf, 16));
1022        }
1023        buf.reset();
1024        }
1025    }
1026    return out.toString();
1027    }
1028
1029    private static boolean isSafeChar(int c) {
1030    if (c >= 'a' && c <= 'z') {
1031        return true;
1032    }
1033    if (c >= 'A' && c <= 'Z') {
1034        return true;
1035    }
1036    if (c >= '0' && c <= '9') {
1037        return true;
1038    }
1039    if (c == '-' || c == '_' || c == '.' || c == '!' ||
1040        c == '~' || c == '*' || c == '\'' || c == '(' || c == ')') {
1041        return true;
1042    }
1043    return false;
1044    }
1045
1046}
1047
Popular Tags