1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package org.apache.struts.util;
22
23 import org.apache.commons.beanutils.BeanUtils;
24 import org.apache.commons.beanutils.PropertyUtils;
25 import org.apache.commons.logging.Log;
26 import org.apache.commons.logging.LogFactory;
27 import org.apache.struts.Globals;
28 import org.apache.struts.action.ActionForm;
29 import org.apache.struts.action.ActionMapping;
30 import org.apache.struts.action.ActionServlet;
31 import org.apache.struts.action.ActionServletWrapper;
32 import org.apache.struts.config.ActionConfig;
33 import org.apache.struts.config.FormBeanConfig;
34 import org.apache.struts.config.ForwardConfig;
35 import org.apache.struts.config.ModuleConfig;
36 import org.apache.struts.upload.FormFile;
37 import org.apache.struts.upload.MultipartRequestHandler;
38 import org.apache.struts.upload.MultipartRequestWrapper;
39
40 import javax.servlet.ServletContext;
41 import javax.servlet.ServletException;
42 import javax.servlet.http.HttpServletRequest;
43 import javax.servlet.http.HttpSession;
44
45 import java.lang.reflect.InvocationTargetException;
46 import java.net.MalformedURLException;
47 import java.net.URL;
48
49 import java.util.ArrayList;
50 import java.util.Collections;
51 import java.util.Enumeration;
52 import java.util.HashMap;
53 import java.util.Hashtable;
54 import java.util.List;
55 import java.util.Locale;
56 import java.util.Map;
57
58
59
60
61
62
63
64 public class RequestUtils {
65
66
67
68
69
70 protected static Log log = LogFactory.getLog(RequestUtils.class);
71
72
73
74
75
76
77
78
79
80
81
82
83
84 public static URL absoluteURL(HttpServletRequest request, String path)
85 throws MalformedURLException {
86 return (new URL(serverURL(request), request.getContextPath() + path));
87 }
88
89
90
91
92
93
94
95
96
97 public static Class applicationClass(String className)
98 throws ClassNotFoundException {
99 return applicationClass(className, null);
100 }
101
102
103
104
105
106
107
108
109
110
111 public static Class applicationClass(String className,
112 ClassLoader classLoader)
113 throws ClassNotFoundException {
114 if (classLoader == null) {
115
116 classLoader = Thread.currentThread().getContextClassLoader();
117
118 if (classLoader == null) {
119 classLoader = RequestUtils.class.getClassLoader();
120 }
121 }
122
123
124 return (classLoader.loadClass(className));
125 }
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144 public static Object applicationInstance(String className)
145 throws ClassNotFoundException, IllegalAccessException,
146 InstantiationException {
147 return applicationInstance(className, null);
148 }
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168 public static Object applicationInstance(String className,
169 ClassLoader classLoader)
170 throws ClassNotFoundException, IllegalAccessException,
171 InstantiationException {
172 return (applicationClass(className, classLoader).newInstance());
173 }
174
175
176
177
178
179
180
181
182
183
184
185
186 public static ActionForm createActionForm(HttpServletRequest request,
187 ActionMapping mapping, ModuleConfig moduleConfig, ActionServlet servlet) {
188
189 String attribute = mapping.getAttribute();
190
191 if (attribute == null) {
192 return (null);
193 }
194
195
196 String name = mapping.getName();
197 FormBeanConfig config = moduleConfig.findFormBeanConfig(name);
198
199 if (config == null) {
200 log.warn("No FormBeanConfig found under '" + name + "'");
201
202 return (null);
203 }
204
205 ActionForm instance =
206 lookupActionForm(request, attribute, mapping.getScope());
207
208
209 if ((instance != null) && config.canReuse(instance)) {
210 return (instance);
211 }
212
213 return createActionForm(config, servlet);
214 }
215
216 private static ActionForm lookupActionForm(HttpServletRequest request,
217 String attribute, String scope) {
218
219 if (log.isDebugEnabled()) {
220 log.debug(" Looking for ActionForm bean instance in scope '"
221 + scope + "' under attribute key '" + attribute + "'");
222 }
223
224 ActionForm instance = null;
225 HttpSession session = null;
226
227 if ("request".equals(scope)) {
228 instance = (ActionForm) request.getAttribute(attribute);
229 } else {
230 session = request.getSession();
231 instance = (ActionForm) session.getAttribute(attribute);
232 }
233
234 return (instance);
235 }
236
237
238
239
240
241
242
243
244
245
246
247
248
249 public static ActionForm createActionForm(FormBeanConfig config,
250 ActionServlet servlet) {
251 if (config == null) {
252 return (null);
253 }
254
255 ActionForm instance = null;
256
257
258 try {
259 instance = config.createActionForm(servlet);
260
261 if (log.isDebugEnabled()) {
262 log.debug(" Creating new "
263 + (config.getDynamic() ? "DynaActionForm" : "ActionForm")
264 + " instance of type '" + config.getType() + "'");
265 log.trace(" --> " + instance);
266 }
267 } catch (Throwable t) {
268 log.error(servlet.getInternal().getMessage("formBean",
269 config.getType()), t);
270 }
271
272 return (instance);
273 }
274
275
276
277
278
279
280
281
282 public static String getServletMapping(ActionServlet servlet) {
283 ServletContext servletContext = servlet.getServletConfig().getServletContext();
284 return (String)servletContext.getAttribute(Globals.SERVLET_KEY);
285 }
286
287
288
289
290
291
292
293
294
295
296
297
298 public static Locale getUserLocale(HttpServletRequest request, String locale) {
299 Locale userLocale = null;
300 HttpSession session = request.getSession(false);
301
302 if (locale == null) {
303 locale = Globals.LOCALE_KEY;
304 }
305
306
307 if (session != null) {
308 userLocale = (Locale) session.getAttribute(locale);
309 }
310
311 if (userLocale == null) {
312
313 userLocale = request.getLocale();
314 }
315
316 return userLocale;
317 }
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332 public static void populate(Object bean, HttpServletRequest request)
333 throws ServletException {
334 populate(bean, null, null, request);
335 }
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362 public static void populate(Object bean, String prefix, String suffix,
363 HttpServletRequest request)
364 throws ServletException {
365
366 HashMap properties = new HashMap();
367
368
369 Enumeration names = null;
370
371
372 Map multipartParameters = null;
373
374 String contentType = request.getContentType();
375 String method = request.getMethod();
376 boolean isMultipart = false;
377
378 if (bean instanceof ActionForm) {
379 ((ActionForm) bean).setMultipartRequestHandler(null);
380 }
381
382 MultipartRequestHandler multipartHandler = null;
383 if ((contentType != null)
384 && (contentType.startsWith("multipart/form-data"))
385 && (method.equalsIgnoreCase("POST"))) {
386
387 ActionServletWrapper servlet;
388
389 if (bean instanceof ActionForm) {
390 servlet = ((ActionForm) bean).getServletWrapper();
391 } else {
392 throw new ServletException("bean that's supposed to be "
393 + "populated from a multipart request is not of type "
394 + "\"org.apache.struts.action.ActionForm\", but type "
395 + "\"" + bean.getClass().getName() + "\"");
396 }
397
398
399 multipartHandler = getMultipartHandler(request);
400
401 if (multipartHandler != null) {
402 isMultipart = true;
403
404
405 servlet.setServletFor(multipartHandler);
406 multipartHandler.setMapping((ActionMapping) request
407 .getAttribute(Globals.MAPPING_KEY));
408
409
410 multipartHandler.handleRequest(request);
411
412
413 Boolean maxLengthExceeded =
414 (Boolean) request.getAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED);
415
416 if ((maxLengthExceeded != null)
417 && (maxLengthExceeded.booleanValue())) {
418 ((ActionForm) bean).setMultipartRequestHandler(multipartHandler);
419 return;
420 }
421
422
423 multipartParameters =
424 getAllParametersForMultipartRequest(request,
425 multipartHandler);
426 names = Collections.enumeration(multipartParameters.keySet());
427 }
428 }
429
430 if (!isMultipart) {
431 names = request.getParameterNames();
432 }
433
434 while (names.hasMoreElements()) {
435 String name = (String) names.nextElement();
436 String stripped = name;
437
438 if (prefix != null) {
439 if (!stripped.startsWith(prefix)) {
440 continue;
441 }
442
443 stripped = stripped.substring(prefix.length());
444 }
445
446 if (suffix != null) {
447 if (!stripped.endsWith(suffix)) {
448 continue;
449 }
450
451 stripped =
452 stripped.substring(0, stripped.length() - suffix.length());
453 }
454
455 Object parameterValue = null;
456
457 if (isMultipart) {
458 parameterValue = multipartParameters.get(name);
459 parameterValue = rationalizeMultipleFileProperty(bean, name, parameterValue);
460 } else {
461 parameterValue = request.getParameterValues(name);
462 }
463
464
465
466 if (!(stripped.startsWith("org.apache.struts."))) {
467 properties.put(stripped, parameterValue);
468 }
469 }
470
471
472 try {
473 BeanUtils.populate(bean, properties);
474 } catch (Exception e) {
475 throw new ServletException("BeanUtils.populate", e);
476 } finally {
477 if (multipartHandler != null) {
478
479
480
481
482 ((ActionForm) bean).setMultipartRequestHandler(multipartHandler);
483 }
484 }
485 }
486
487
488
489
490
491
492
493
494
495
496
497 private static Object rationalizeMultipleFileProperty(Object bean, String name, Object parameterValue) throws ServletException {
498 if (!(parameterValue instanceof FormFile)) {
499 return parameterValue;
500 }
501
502 FormFile formFileValue = (FormFile) parameterValue;
503 try {
504 Class propertyType = PropertyUtils.getPropertyType(bean, name);
505
506 if (List.class.isAssignableFrom(propertyType)) {
507 ArrayList list = new ArrayList(1);
508 list.add(formFileValue);
509 return list;
510 }
511
512 if (propertyType.isArray() && propertyType.getComponentType().equals(FormFile.class)) {
513 return new FormFile[] { formFileValue };
514 }
515
516 } catch (IllegalAccessException e) {
517 throw new ServletException(e);
518 } catch (InvocationTargetException e) {
519 throw new ServletException(e);
520 } catch (NoSuchMethodException e) {
521 throw new ServletException(e);
522 }
523
524
525 return parameterValue;
526
527 }
528
529
530
531
532
533
534
535
536
537
538
539
540
541 private static MultipartRequestHandler getMultipartHandler(
542 HttpServletRequest request)
543 throws ServletException {
544 MultipartRequestHandler multipartHandler = null;
545 String multipartClass =
546 (String) request.getAttribute(Globals.MULTIPART_KEY);
547
548 request.removeAttribute(Globals.MULTIPART_KEY);
549
550
551 if (multipartClass != null) {
552 try {
553 multipartHandler =
554 (MultipartRequestHandler) applicationInstance(multipartClass);
555 } catch (ClassNotFoundException cnfe) {
556 log.error("MultipartRequestHandler class \"" + multipartClass
557 + "\" in mapping class not found, "
558 + "defaulting to global multipart class");
559 } catch (InstantiationException ie) {
560 log.error("InstantiationException when instantiating "
561 + "MultipartRequestHandler \"" + multipartClass + "\", "
562 + "defaulting to global multipart class, exception: "
563 + ie.getMessage());
564 } catch (IllegalAccessException iae) {
565 log.error("IllegalAccessException when instantiating "
566 + "MultipartRequestHandler \"" + multipartClass + "\", "
567 + "defaulting to global multipart class, exception: "
568 + iae.getMessage());
569 }
570
571 if (multipartHandler != null) {
572 return multipartHandler;
573 }
574 }
575
576 ModuleConfig moduleConfig =
577 ModuleUtils.getInstance().getModuleConfig(request);
578
579 multipartClass = moduleConfig.getControllerConfig().getMultipartClass();
580
581
582 if (multipartClass != null) {
583 try {
584 multipartHandler =
585 (MultipartRequestHandler) applicationInstance(multipartClass);
586 } catch (ClassNotFoundException cnfe) {
587 throw new ServletException("Cannot find multipart class \""
588 + multipartClass + "\"" + ", exception: "
589 + cnfe.getMessage());
590 } catch (InstantiationException ie) {
591 throw new ServletException(
592 "InstantiationException when instantiating "
593 + "multipart class \"" + multipartClass + "\", exception: "
594 + ie.getMessage());
595 } catch (IllegalAccessException iae) {
596 throw new ServletException(
597 "IllegalAccessException when instantiating "
598 + "multipart class \"" + multipartClass + "\", exception: "
599 + iae.getMessage());
600 }
601
602 if (multipartHandler != null) {
603 return multipartHandler;
604 }
605 }
606
607 return multipartHandler;
608 }
609
610
611
612
613
614
615
616
617
618
619
620
621
622 private static Map getAllParametersForMultipartRequest(
623 HttpServletRequest request, MultipartRequestHandler multipartHandler) {
624 Map parameters = new HashMap();
625 Hashtable elements = multipartHandler.getAllElements();
626 Enumeration e = elements.keys();
627
628 while (e.hasMoreElements()) {
629 String key = (String) e.nextElement();
630
631 parameters.put(key, elements.get(key));
632 }
633
634 if (request instanceof MultipartRequestWrapper) {
635 request =
636 (HttpServletRequest) ((MultipartRequestWrapper) request)
637 .getRequest();
638 e = request.getParameterNames();
639
640 while (e.hasMoreElements()) {
641 String key = (String) e.nextElement();
642
643 parameters.put(key, request.getParameterValues(key));
644 }
645 } else {
646 log.debug("Gathering multipart parameters for unwrapped request");
647 }
648
649 return parameters;
650 }
651
652
653
654
655
656
657
658
659
660
661 public static String printableURL(URL url) {
662 if (url.getHost() != null) {
663 return (url.toString());
664 }
665
666 String file = url.getFile();
667 String ref = url.getRef();
668
669 if (ref == null) {
670 return (file);
671 } else {
672 StringBuffer sb = new StringBuffer(file);
673
674 sb.append('#');
675 sb.append(ref);
676
677 return (sb.toString());
678 }
679 }
680
681
682
683
684
685
686
687
688
689
690
691
692 public static String actionURL(HttpServletRequest request,
693 ActionConfig action, String pattern) {
694 StringBuffer sb = new StringBuffer();
695
696 if (pattern.endsWith("/*")) {
697 sb.append(pattern.substring(0, pattern.length() - 2));
698 sb.append(action.getPath());
699 } else if (pattern.startsWith("*.")) {
700 ModuleConfig appConfig =
701 ModuleUtils.getInstance().getModuleConfig(request);
702
703 sb.append(appConfig.getPrefix());
704 sb.append(action.getPath());
705 sb.append(pattern.substring(1));
706 } else {
707 throw new IllegalArgumentException(pattern);
708 }
709
710 return sb.toString();
711 }
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768 public static String forwardURL(HttpServletRequest request,
769 ForwardConfig forward) {
770 return forwardURL(request, forward, null);
771 }
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820 public static String forwardURL(HttpServletRequest request,
821 ForwardConfig forward, ModuleConfig moduleConfig) {
822
823 if (moduleConfig == null) {
824 moduleConfig = ModuleUtils.getInstance().getModuleConfig(request);
825 }
826
827 String path = forward.getPath();
828
829
830 String prefix = moduleConfig.getPrefix();
831
832
833 if (forward.getModule() != null) {
834 prefix = forward.getModule();
835
836 if ("/".equals(prefix)) {
837 prefix = "";
838 }
839 }
840
841 StringBuffer sb = new StringBuffer();
842
843
844 String forwardPattern =
845 moduleConfig.getControllerConfig().getForwardPattern();
846
847 if (forwardPattern == null) {
848
849 sb.append(prefix);
850
851
852 if (!path.startsWith("/")) {
853 sb.append("/");
854 }
855
856 sb.append(path);
857 } else {
858 boolean dollar = false;
859
860 for (int i = 0; i < forwardPattern.length(); i++) {
861 char ch = forwardPattern.charAt(i);
862
863 if (dollar) {
864 switch (ch) {
865 case 'M':
866 sb.append(prefix);
867
868 break;
869
870 case 'P':
871
872
873 if (!path.startsWith("/")) {
874 sb.append("/");
875 }
876
877 sb.append(path);
878
879 break;
880
881 case '$':
882 sb.append('$');
883
884 break;
885
886 default:
887 ;
888 }
889
890 dollar = false;
891
892 continue;
893 } else if (ch == '$') {
894 dollar = true;
895 } else {
896 sb.append(ch);
897 }
898 }
899 }
900
901 return (sb.toString());
902 }
903
904
905
906
907
908
909
910
911
912 public static URL requestURL(HttpServletRequest request)
913 throws MalformedURLException {
914 StringBuffer url = requestToServerUriStringBuffer(request);
915
916 return (new URL(url.toString()));
917 }
918
919
920
921
922
923
924
925
926
927
928
929 public static URL serverURL(HttpServletRequest request)
930 throws MalformedURLException {
931 StringBuffer url = requestToServerStringBuffer(request);
932
933 return (new URL(url.toString()));
934 }
935
936
937
938
939
940
941
942
943
944
945
946 public static StringBuffer requestToServerUriStringBuffer(
947 HttpServletRequest request) {
948 StringBuffer serverUri =
949 createServerUriStringBuffer(request.getScheme(),
950 request.getServerName(), request.getServerPort(),
951 request.getRequestURI());
952
953 return serverUri;
954 }
955
956
957
958
959
960
961
962
963
964
965
966
967 public static StringBuffer requestToServerStringBuffer(
968 HttpServletRequest request) {
969 return createServerStringBuffer(request.getScheme(),
970 request.getServerName(), request.getServerPort());
971 }
972
973
974
975
976
977
978
979
980
981
982
983 public static StringBuffer createServerStringBuffer(String scheme,
984 String server, int port) {
985 StringBuffer url = new StringBuffer();
986
987 if (port < 0) {
988 port = 80;
989 }
990
991 url.append(scheme);
992 url.append("://");
993 url.append(server);
994
995 if ((scheme.equals("http") && (port != 80))
996 || (scheme.equals("https") && (port != 443))) {
997 url.append(':');
998 url.append(port);
999 }
1000
1001 return url;
1002 }
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015 public static StringBuffer createServerUriStringBuffer(String scheme,
1016 String server, int port, String uri) {
1017 StringBuffer serverUri = createServerStringBuffer(scheme, server, port);
1018
1019 serverUri.append(uri);
1020
1021 return serverUri;
1022 }
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036 public static String actionIdURL(ForwardConfig forward, HttpServletRequest request, ActionServlet servlet) {
1037 ModuleConfig moduleConfig = null;
1038 if (forward.getModule() != null) {
1039 String prefix = forward.getModule();
1040 moduleConfig = ModuleUtils.getInstance().getModuleConfig(prefix, servlet.getServletContext());
1041 } else {
1042 moduleConfig = ModuleUtils.getInstance().getModuleConfig(request);
1043 }
1044 return actionIdURL(forward.getPath(), moduleConfig, servlet);
1045 }
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058 public static String actionIdURL(String originalPath, ModuleConfig moduleConfig, ActionServlet servlet) {
1059 if (originalPath.startsWith("http") || originalPath.startsWith("/")) {
1060 return null;
1061 }
1062
1063
1064
1065 String actionId = null;
1066 String qs = null;
1067 int qpos = originalPath.indexOf("?");
1068 if (qpos == -1) {
1069 actionId = originalPath;
1070 } else {
1071 actionId = originalPath.substring(0, qpos);
1072 qs = originalPath.substring(qpos);
1073 }
1074
1075
1076 ActionConfig actionConfig = moduleConfig.findActionConfigId(actionId);
1077 if (actionConfig == null) {
1078 if (log.isDebugEnabled()) {
1079 log.debug("No actionId found for " + actionId);
1080 }
1081 return null;
1082 }
1083
1084 String path = actionConfig.getPath();
1085 String mapping = RequestUtils.getServletMapping(servlet);
1086 StringBuffer actionIdPath = new StringBuffer();
1087
1088
1089 if (mapping.startsWith("*")) {
1090 actionIdPath.append(path);
1091 actionIdPath.append(mapping.substring(1));
1092 } else if (mapping.startsWith("/")) {
1093 mapping = mapping.substring(0, mapping.length() - 1);
1094 if (mapping.endsWith("/") && path.startsWith("/")) {
1095 actionIdPath.append(mapping);
1096 actionIdPath.append(path.substring(1));
1097 } else {
1098 actionIdPath.append(mapping);
1099 actionIdPath.append(path);
1100 }
1101 } else {
1102 log.warn("Unknown servlet mapping pattern");
1103 actionIdPath.append(path);
1104 }
1105
1106
1107 if (qs != null) {
1108 actionIdPath.append(qs);
1109 }
1110
1111
1112 if (log.isDebugEnabled()) {
1113 log.debug(originalPath + " unaliased to " + actionIdPath.toString());
1114 }
1115 return actionIdPath.toString();
1116 }
1117 }