KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > velocity > tools > struts > StrutsUtils


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.velocity.tools.struts;
18
19
20 import java.util.Locale JavaDoc;
21 import java.util.Iterator JavaDoc;
22
23 import javax.servlet.ServletContext JavaDoc;
24 import javax.servlet.http.HttpServletRequest JavaDoc;
25 import javax.servlet.http.HttpSession JavaDoc;
26 import javax.sql.DataSource JavaDoc;
27
28 import org.apache.struts.Globals;
29 import org.apache.struts.action.ActionForm;
30 import org.apache.struts.action.ActionErrors;
31 import org.apache.struts.action.ActionMessage;
32 import org.apache.struts.action.ActionMessages;
33 import org.apache.struts.config.ModuleConfig;
34 import org.apache.struts.config.ForwardConfig;
35 import org.apache.struts.config.ActionConfig;
36 import org.apache.struts.config.FormBeanConfig;
37 import org.apache.struts.upload.MultipartRequestWrapper;
38 import org.apache.struts.util.MessageResources;
39 import org.apache.struts.util.RequestUtils;
40
41 /* deprecated imports */
42 import org.apache.struts.action.ActionFormBeans;
43 import org.apache.struts.action.ActionForward;
44 import org.apache.struts.action.ActionForwards;
45 import org.apache.struts.action.ActionMapping;
46 import org.apache.struts.action.ActionMappings;
47
48 /**
49  * <p>A utility class to expose the Struts shared
50  * resources. All methods are static.</p>
51  *
52  * <p>This class is provided for use by Velocity view tools
53  * that need access to Struts resources. By having all Struts-
54  * specific code in this utility class, maintenance is simplified
55  * and reuse fostered.</p>
56  *
57  * <p>It is the aim, that sooner or later the functionality in
58  * this class is integrated into Struts itself. See
59  * <a HREF="http://nagoya.apache.org/bugzilla/show_bug.cgi?id=16814">Bug #16814</a>
60  * for more on that.</p>
61  *
62  * @author <a HREF="mailto:marinoj@centrum.is">Marino A. Jonsson</a>
63  * @author <a HREF="mailto:nathan@esha.com">Nathan Bubna</a>
64  * @author <a HREF="mailto:sidler@teamup.com">Gabe Sidler</a>
65  * based on code by <a HREF="mailto:ted@husted.org">Ted Husted</a>
66  *
67  * @version $Id: StrutsUtils.java,v 1.16.2.2 2004/03/12 23:36:19 nbubna Exp $
68  */

69 public class StrutsUtils
70 {
71
72     /****************** Struts ServletContext Resources ****************/
73
74     /**
75      * Returns the default configured data source (which must implement
76      * <code>javax.sql.DataSource</code>) or <code>null</code> if not found.
77      *
78      * @param app the servlet context
79      * @deprecated This will be removed in VelocityTools 1.2
80      */

81     public static DataSource JavaDoc getDataSource(ServletContext JavaDoc app)
82     {
83         return (DataSource JavaDoc)app.getAttribute(Globals.DATA_SOURCE_KEY);
84     }
85
86
87     /**
88      * Returns the <code>org.apache.struts.action.ActionFormBeans</code>
89      * collection for this application or <code>null</code> if not found.
90      *
91      * @param app the servlet context
92      * @deprecated This will be removed in VelocityTools 1.2
93      */

94     public static ActionFormBeans getActionFormBeans(ServletContext JavaDoc app)
95     {
96         return (ActionFormBeans)app.getAttribute(Globals.FORM_BEANS_KEY);
97     }
98
99
100     /**
101      * Returns the form bean definition associated with the specified
102      * logical name or <code>null</code> if not found.
103      *
104      * @param name logical name of the requested form bean definition
105      * @param app the servlet context
106      * @deprecated This will be removed in VelocityTools 1.2
107      */

108     public static FormBeanConfig getFormBean(String JavaDoc name, ServletContext JavaDoc app)
109     {
110         ActionFormBeans formBeans = getActionFormBeans(app);
111         if (formBeans == null)
112         {
113             return null;
114         }
115         return formBeans.findFormBean(name);
116
117     }
118
119
120     /**
121      * Returns the <code>org.apache.struts.action.ActionForwards</code>
122      * collection for this application or <code>null</code> if not found.
123      *
124      * @param app the servlet context
125      * @deprecated This will be removed in VelocityTools 1.2
126      */

127     public static ActionForwards getActionForwards(ServletContext JavaDoc app)
128     {
129         return (ActionForwards)app.getAttribute(Globals.FORWARDS_KEY);
130     }
131
132
133     /**
134      * Returns the forwarding associated with the specified logical name
135      * or <code>null</code> if not found.
136      *
137      * @param name Logical name of the requested forwarding
138      * @param app the servlet context
139      * @deprecated This will be removed in VelocityTools 1.2
140      */

141     public static ActionForward getActionForward(String JavaDoc name,
142                                                  ServletContext JavaDoc app)
143     {
144         ActionForwards forwards = getActionForwards(app);
145         if (forwards == null)
146         {
147             return null;
148         }
149         return forwards.findForward(name);
150     }
151
152
153     /**
154      * Returns the <code>org.apache.struts.action.ActionMappings</code>
155      * collection for this application or <code>null</code> if not found.
156      *
157      * @param app the servlet context
158      * @deprecated This will be removed in VelocityTools 1.2
159      */

160     public static ActionMappings getActionMappings(ServletContext JavaDoc app)
161     {
162         return (ActionMappings)app.getAttribute(Globals.MAPPINGS_KEY);
163     }
164
165
166     /**
167      * Returns the mapping associated with the specified request path,
168      * or <code>null</code> if not found.
169      *
170      * @param path Request path for which a mapping is requested
171      * @param app the servlet context
172      * @deprecated This will be removed in VelocityTools 1.2
173      */

174     public static ActionMapping getActionMapping(String JavaDoc path,
175                                                  ServletContext JavaDoc app)
176     {
177         ActionMappings mappings = getActionMappings(app);
178         if (mappings == null)
179         {
180             return null;
181         }
182         return mappings.findMapping(path);
183     }
184
185
186     /**
187      * Returns the message resources for this application or <code>null</code>
188      * if not found.
189      *
190      * @param app the servlet context
191      * @deprecated This will be removed in VelocityTools 1.2
192      */

193     public static MessageResources getMessageResources(ServletContext JavaDoc app)
194     {
195         return (MessageResources)app.getAttribute(Globals.MESSAGES_KEY);
196     }
197
198
199     /**
200      * Returns the message resources for this application or <code>null</code>
201      * if not found.
202      *
203      * @param app the servlet context
204      * @since VelocityTools 1.1
205      */

206     public static MessageResources getMessageResources(HttpServletRequest JavaDoc request,
207                                                        ServletContext JavaDoc app)
208     {
209         /* Identify the current module */
210         ModuleConfig moduleConfig = RequestUtils.getModuleConfig(request, app);
211         return (MessageResources)app.getAttribute(Globals.MESSAGES_KEY +
212                                                   moduleConfig.getPrefix());
213     }
214
215
216     /**
217      * Returns the message resources with the specified bundle name for this application
218      * or <code>null</code> if not found.
219      *
220      * @param app the servlet context
221      * @param bundle The bundle name to look for. If this is <code>null</code>, the
222      * default bundle name is used.
223      * @since VelocityTools 1.1
224      */

225     public static MessageResources getMessageResources(HttpServletRequest JavaDoc request,
226                                                        ServletContext JavaDoc app,
227                                                        String JavaDoc bundle)
228     {
229         MessageResources resources = null;
230
231         /* Identify the current module */
232         ModuleConfig moduleConfig = RequestUtils.getModuleConfig(request, app);
233
234
235         if (bundle == null) {
236             bundle = Globals.MESSAGES_KEY;
237         }
238
239         // First check request scope
240
resources = (MessageResources) request.getAttribute(bundle + moduleConfig.getPrefix());
241
242         if (resources == null) {
243             resources = (MessageResources) app.getAttribute(bundle + moduleConfig.getPrefix());
244         }
245
246         return resources;
247     }
248
249
250     /**
251      * Select the module to which the specified request belongs, and
252      * add return the corresponding ModuleConfig.
253      *
254      * @param urlPath The requested URL
255      * @param app The ServletContext for this web application
256      * @return The ModuleConfig for the given URL path
257      * @since VelocityTools 1.1
258      */

259     public static ModuleConfig selectModule(String JavaDoc urlPath,
260                                             ServletContext JavaDoc app)
261     {
262         /* Match against the list of sub-application prefixes */
263         String JavaDoc prefix = RequestUtils.getModuleName(urlPath, app);
264
265         /* Expose the resources for this sub-application */
266         ModuleConfig config = (ModuleConfig)
267             app.getAttribute(Globals.MODULE_KEY + prefix);
268
269         return config;
270     }
271
272
273     /**
274      * Returns the servlet mapping used for this application or
275      * <code>null</code> if not found. The servlet mapping is
276      * either a path-mapped pattern (<code>/action/*</code>) or an
277      * extension mapped pattern (<code>*.do</code>).
278      *
279      * @param app the servlet context
280      * @deprecated This will be removed in VelocityTools 1.2
281      */

282     public static String JavaDoc getServletMapping(ServletContext JavaDoc app)
283     {
284         return (String JavaDoc)app.getAttribute(Globals.SERVLET_KEY);
285     }
286
287
288     /********************** Struts Session Resources ******************/
289
290     /**
291      * Returns the <code>java.util.Locale</code> for the user. If a
292      * locale object is not found in the user's session, the system
293      * default locale is returned.
294      *
295      * @param request the servlet request
296      * @param session the HTTP session
297      */

298     public static Locale JavaDoc getLocale(HttpServletRequest JavaDoc request,
299                                    HttpSession JavaDoc session)
300     {
301         Locale JavaDoc locale = null;
302
303         if (session != null)
304         {
305             locale = (Locale JavaDoc)session.getAttribute(Globals.LOCALE_KEY);
306         }
307         if (locale == null)
308         {
309             locale = request.getLocale();
310         }
311         return locale;
312     }
313
314
315     /**
316      * Returns the transaction token stored in this session or
317      * <code>null</code> if not used.
318      *
319      * @param session the HTTP session
320      */

321     public static String JavaDoc getToken(HttpSession JavaDoc session)
322     {
323         if (session == null)
324         {
325             return null;
326         }
327         return (String JavaDoc)session.getAttribute(Globals.TRANSACTION_TOKEN_KEY);
328     }
329
330
331     /*********************** Struts Request Resources ****************/
332
333     /**
334      * Returns the Struts errors for this request or <code>null</code>
335      * if none exist.
336      *
337      * @param request the servlet request
338      * @since VelocityTools 1.1
339      */

340     public static ActionMessages getErrors(HttpServletRequest JavaDoc request)
341     {
342         return (ActionMessages)request.getAttribute(Globals.ERROR_KEY);
343     }
344
345     /**
346      * Returns the Struts messages for this request or <code>null</code>
347      * if none exist.
348      *
349      * @param request the servlet request
350      * @since VelocityTools 1.1
351      */

352     public static ActionMessages getMessages(HttpServletRequest JavaDoc request)
353     {
354         return (ActionMessages)request.getAttribute(Globals.MESSAGE_KEY);
355     }
356
357
358     /**
359      * @deprecated use {@link #getErrors(HttpServletRequest request)}.
360      */

361     public static ActionErrors getActionErrors(HttpServletRequest JavaDoc request)
362     {
363         return (ActionErrors)getErrors(request);
364     }
365
366     /**
367      * @deprecated use {@link #getMessages(HttpServletRequest request)}.
368      */

369     public static ActionMessages getActionMessages(HttpServletRequest JavaDoc request)
370     {
371         return getMessages(request);
372     }
373
374
375     /**
376      * Returns the runtime Exception that may have been thrown by a
377      * Struts view tool or compatible presentation extension, and
378      * placed in the request. Returns <code>null</code> if none found.
379      *
380      * @param request the servlet request
381      * @deprecated This will be removed in VelocityTools 1.2
382      */

383     public static Throwable JavaDoc getException(HttpServletRequest JavaDoc request)
384     {
385         return (Throwable JavaDoc)request.getAttribute(Globals.EXCEPTION_KEY);
386     }
387
388
389     /**
390      * Returns the multipart object for this request or <code>null</code>
391      * if none exists.
392      *
393      * @param request the servlet request
394      * @deprecated This will be removed in VelocityTools 1.2
395      */

396     public static MultipartRequestWrapper getMultipartRequestWrapper(HttpServletRequest JavaDoc request)
397     {
398         return (MultipartRequestWrapper)request.getAttribute(Globals.MULTIPART_KEY);
399     }
400
401
402     /**
403      * Returns the <code>ActionForm</code> bean associated with
404      * this request of <code>null</code> if none exists.
405      *
406      * @param request the servlet request
407      * @param session the HTTP session
408      */

409     public static ActionForm getActionForm(HttpServletRequest JavaDoc request,
410                                            HttpSession JavaDoc session)
411     {
412         /* Is there a mapping associated with this request? */
413         ActionConfig mapping =
414             (ActionConfig)request.getAttribute(Globals.MAPPING_KEY);
415         if (mapping == null)
416         {
417             return null;
418         }
419
420         /* Is there a form bean associated with this mapping? */
421         String JavaDoc attribute = mapping.getAttribute();
422         if (attribute == null)
423         {
424             return null;
425         }
426
427         /* Look up the existing form bean */
428         if ("request".equals(mapping.getScope()))
429         {
430             return (ActionForm)request.getAttribute(attribute);
431         }
432         if (session != null)
433         {
434             return (ActionForm)session.getAttribute(attribute);
435         }
436         return null;
437     }
438
439
440     /********************* Important Struts Constants *****************/
441
442     /**
443      * Returns the query parameter name under which a cancel button press
444      * must be reported if form validation is to be skipped.
445      *
446      * @deprecated This will be removed in VelocityTools 1.2
447      */

448     public static String JavaDoc getCancelName()
449     {
450         return org.apache.struts.taglib.html.Constants.CANCEL_PROPERTY;
451     }
452
453
454     /**
455      * Returns the default "GLOBAL" category name that can be used with
456      * messages that are not associated with a particular property.
457      *
458      * @deprecated This will be removed in VelocityTools 1.2
459      */

460     public static String JavaDoc getGlobalErrorName()
461     {
462         return org.apache.struts.action.ActionErrors.GLOBAL_ERROR;
463     }
464
465
466     /**
467      * Returns the query parameter name under which a transaction token
468      * must be reported.
469      *
470      * @deprecated This will be removed in VelocityTools 1.2
471      */

472     public static String JavaDoc getTokenName()
473     {
474         return org.apache.struts.taglib.html.Constants.TOKEN_KEY;
475     }
476
477
478     /*************************** Utilities *************************/
479
480     /**
481      * Returns the form action converted into an action mapping path. The
482      * value of the <code>action</code> property is manipulated as follows in
483      * computing the name of the requested mapping:
484      * <ul>
485      * <li>Any filename extension is removed (on the theory that extension
486      * mapping is being used to select the controller servlet).</li>
487      * <li>If the resulting value does not start with a slash, then a
488      * slash is prepended.</li>
489      * </ul>
490      *
491      * @param action the name of an action as per struts-config.xml
492      * @deprecated This will be removed in VelocityTools 1.2
493      */

494     public static String JavaDoc getActionMappingName(String JavaDoc action)
495     {
496         return RequestUtils.getActionMappingName(action);
497     }
498
499
500     /**
501      * Returns the form action converted into a server-relative URI
502      * reference.
503      *
504      * @param application the servlet context
505      * @param request the servlet request
506      * @param action the name of an action as per struts-config.xml
507      */

508     public static String JavaDoc getActionMappingURL(ServletContext JavaDoc application,
509                                              HttpServletRequest JavaDoc request,
510                                              String JavaDoc action)
511     {
512         StringBuffer JavaDoc value = new StringBuffer JavaDoc(request.getContextPath());
513         ModuleConfig config =
514             (ModuleConfig)request.getAttribute(Globals.MODULE_KEY);
515         if (config != null)
516         {
517             value.append(config.getPrefix());
518         }
519
520         /* Use our servlet mapping, if one is specified */
521         String JavaDoc servletMapping =
522             (String JavaDoc)application.getAttribute(Globals.SERVLET_KEY);
523
524         if (servletMapping != null)
525         {
526             String JavaDoc queryString = null;
527             int question = action.indexOf("?");
528
529             if (question >= 0)
530             {
531                 queryString = action.substring(question);
532             }
533
534             String JavaDoc actionMapping = RequestUtils.getActionMappingName(action);
535
536             if (servletMapping.startsWith("*."))
537             {
538                 value.append(actionMapping);
539                 value.append(servletMapping.substring(1));
540             }
541             else if (servletMapping.endsWith("/*"))
542             {
543                 value.append(servletMapping.substring
544                              (0, servletMapping.length() - 2));
545                 value.append(actionMapping);
546             }
547
548             if (queryString != null)
549             {
550                 value.append(queryString);
551             }
552         }
553         else
554         {
555             /* Otherwise, assume extension mapping is in use and extension is
556              * already included in the action property */

557             if (!action.startsWith("/"))
558             {
559                 value.append("/");
560             }
561             value.append(action);
562         }
563
564         /* Return the completed value */
565         return value.toString();
566     }
567
568
569     /**
570      * Returns the action forward name converted into a server-relative URI
571      * reference.
572      *
573      * @param app the servlet context
574      * @param request the servlet request
575      * @param forward the name of a forward as per struts-config.xml
576      */

577     public static String JavaDoc getForwardURL(HttpServletRequest JavaDoc request,
578                                        ServletContext JavaDoc app,
579                                        String JavaDoc forward)
580     {
581         ModuleConfig moduleConfig = RequestUtils.getModuleConfig(request, app);
582         //TODO? beware of null module config if ActionServlet isn't init'ed?
583
ForwardConfig fc = moduleConfig.findForwardConfig(forward);
584         if (fc == null)
585         {
586             return null;
587         }
588
589         StringBuffer JavaDoc url = new StringBuffer JavaDoc();
590         if (fc.getPath().startsWith("/"))
591         {
592             url.append(request.getContextPath());
593             url.append(RequestUtils.forwardURL(request, fc));
594         }
595         else
596         {
597             url.append(fc.getPath());
598         }
599         return url.toString();
600     }
601
602
603     /**
604      * Returns a formatted error message. The error message is assembled from
605      * the following three pieces: First, value of message resource
606      * "errors.header" is prepended. Then, the list of error messages is
607      * rendered. Finally, the value of message resource "errors.footer"
608      * is appended.
609      *
610      * @param property the category of errors to markup and return
611      * @param request the servlet request
612      * @param session the HTTP session
613      * @param application the servlet context
614      *
615      * @return The formatted error message. If no error messages are queued,
616      * an empty string is returned.
617      */

618     public static String JavaDoc errorMarkup(String JavaDoc property,
619                                      HttpServletRequest JavaDoc request,
620                                      HttpSession JavaDoc session,
621                                      ServletContext JavaDoc application)
622     {
623         return errorMarkup(property, null, request, session, application);
624     }
625
626
627     /**
628      * Returns a formatted error message. The error message is assembled from
629      * the following three pieces: First, value of message resource
630      * "errors.header" is prepended. Then, the list of error messages is
631      * rendered. Finally, the value of message resource "errors.footer"
632      * is appended.
633      *
634      * @param property the category of errors to markup and return
635      * @param bundle the message resource bundle to use
636      * @param request the servlet request
637      * @param session the HTTP session
638      * @param application the servlet context
639      * @since VelocityTools 1.1
640      * @return The formatted error message. If no error messages are queued,
641      * an empty string is returned.
642      */

643     public static String JavaDoc errorMarkup(String JavaDoc property,
644                                      String JavaDoc bundle,
645                                      HttpServletRequest JavaDoc request,
646                                      HttpSession JavaDoc session,
647                                      ServletContext JavaDoc application)
648     {
649         ActionErrors errors = getActionErrors(request);
650         if (errors == null)
651         {
652             return "";
653         }
654
655         /* fetch the error messages */
656         Iterator JavaDoc reports = null;
657         if (property == null)
658         {
659             reports = errors.get();
660         }
661         else
662         {
663             reports = errors.get(property);
664         }
665
666         if (!reports.hasNext())
667         {
668             return "";
669         }
670
671         /* Render the error messages appropriately if errors have been queued */
672         StringBuffer JavaDoc results = new StringBuffer JavaDoc();
673         String JavaDoc header = null;
674         String JavaDoc footer = null;
675         Locale JavaDoc locale = getLocale(request, session);
676
677         MessageResources resources =
678             getMessageResources(request, application, bundle);
679         if (resources != null)
680         {
681             header = resources.getMessage(locale, "errors.header");
682             footer = resources.getMessage(locale, "errors.footer");
683         }
684         if (header == null)
685         {
686             header = "errors.header";
687         }
688         if (footer == null)
689         {
690             footer = "errors.footer";
691         }
692
693         results.append(header);
694         results.append("\r\n");
695
696         String JavaDoc message;
697         while (reports.hasNext())
698         {
699             message = null;
700             ActionMessage report = (ActionMessage)reports.next();
701             if (resources != null)
702             {
703                 message = resources.getMessage(locale,
704                                                report.getKey(),
705                                                report.getValues());
706             }
707             if (message != null)
708             {
709                 results.append(message);
710                 results.append("\r\n");
711             }
712             else
713             {
714                 results.append(report.getKey());
715                 results.append("\r\n");
716             }
717         }
718
719         results.append(footer);
720         results.append("\r\n");
721
722         /* return result */
723         return results.toString();
724     }
725
726 }
727
Popular Tags