/
RequestHandler.java
1387 lines (1247 loc) · 73.2 KB
/
RequestHandler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
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
769
770
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
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.apache.ofbiz.webapp.control;
import static org.apache.ofbiz.base.util.UtilGenerics.checkMap;
import java.io.IOException;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Stream;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.ws.rs.core.MultivaluedHashMap;
import org.apache.cxf.jaxrs.model.URITemplate;
import org.apache.ofbiz.base.location.FlexibleLocation;
import org.apache.ofbiz.base.util.Debug;
import org.apache.ofbiz.base.util.SSLUtil;
import org.apache.ofbiz.base.util.StringUtil;
import org.apache.ofbiz.base.util.UtilCodec;
import org.apache.ofbiz.base.util.UtilGenerics;
import org.apache.ofbiz.base.util.UtilHttp;
import org.apache.ofbiz.base.util.UtilMisc;
import org.apache.ofbiz.base.util.UtilObject;
import org.apache.ofbiz.base.util.UtilProperties;
import org.apache.ofbiz.base.util.UtilValidate;
import org.apache.ofbiz.base.util.collections.MultivaluedMapContext;
import org.apache.ofbiz.entity.Delegator;
import org.apache.ofbiz.entity.GenericEntityException;
import org.apache.ofbiz.entity.GenericValue;
import org.apache.ofbiz.entity.util.EntityQuery;
import org.apache.ofbiz.entity.util.EntityUtilProperties;
import org.apache.ofbiz.webapp.OfbizUrlBuilder;
import org.apache.ofbiz.webapp.control.ConfigXMLReader.RequestMap;
import org.apache.ofbiz.webapp.event.EventFactory;
import org.apache.ofbiz.webapp.event.EventHandler;
import org.apache.ofbiz.webapp.event.EventHandlerException;
import org.apache.ofbiz.webapp.stats.ServerHitBin;
import org.apache.ofbiz.webapp.view.ViewFactory;
import org.apache.ofbiz.webapp.view.ViewHandler;
import org.apache.ofbiz.webapp.view.ViewHandlerException;
import org.apache.ofbiz.webapp.website.WebSiteProperties;
import org.apache.ofbiz.webapp.website.WebSiteWorker;
import org.apache.ofbiz.widget.model.ThemeFactory;
/**
* RequestHandler - Request Processor Object
*/
public class RequestHandler {
public static final String module = RequestHandler.class.getName();
private final static String defaultStatusCodeString =
UtilProperties.getPropertyValue("requestHandler", "status-code", "302");
private final ViewFactory viewFactory;
private final EventFactory eventFactory;
private final URL controllerConfigURL;
private final boolean trackServerHit;
private final boolean trackVisit;
private ControllerConfig ccfg;
static class ControllerConfig {
private final MultivaluedMapContext<String, RequestMap> requestMapMap;
private final Map<String, ConfigXMLReader.ViewMap> viewMapMap;
private String statusCodeString;
private final String defaultRequest;
private final Map<String, ConfigXMLReader.Event> firstVisitEventList;
private final Map<String, ConfigXMLReader.Event> preprocessorEventList;
private final Map<String, ConfigXMLReader.Event> postprocessorEventList;
private final String protectView;
ControllerConfig(ConfigXMLReader.ControllerConfig ccfg) throws WebAppConfigurationException {
preprocessorEventList = ccfg.getPreprocessorEventList();
postprocessorEventList = ccfg.getPostprocessorEventList();
requestMapMap = ccfg.getRequestMapMultiMap();
viewMapMap = ccfg.getViewMapMap();
defaultRequest = ccfg.getDefaultRequest();
firstVisitEventList = ccfg.getFirstVisitEventList();
protectView = ccfg.getProtectView();
String status = ccfg.getStatusCode();
statusCodeString = UtilValidate.isEmpty(status) ? defaultStatusCodeString : status;
}
public MultivaluedMapContext<String, RequestMap> getRequestMapMap() {
return requestMapMap;
}
public Map<String, ConfigXMLReader.ViewMap> getViewMapMap() {
return viewMapMap;
}
public String getStatusCodeString() {
return statusCodeString;
}
public String getDefaultRequest() {
return defaultRequest;
}
public void setStatusCodeString(String statusCodeString) {
this.statusCodeString = statusCodeString;
}
public Map<String, ConfigXMLReader.Event> getFirstVisitEventList() {
return firstVisitEventList;
}
public Map<String, ConfigXMLReader.Event> getPreprocessorEventList() {
return preprocessorEventList;
}
public Map<String, ConfigXMLReader.Event> getPostprocessorEventList() {
return postprocessorEventList;
}
public String getProtectView() {
return protectView;
}
}
public static RequestHandler getRequestHandler(ServletContext servletContext) {
RequestHandler rh = (RequestHandler) servletContext.getAttribute("_REQUEST_HANDLER_");
if (rh == null) {
rh = new RequestHandler(servletContext);
servletContext.setAttribute("_REQUEST_HANDLER_", rh);
}
return rh;
}
private RequestHandler(ServletContext context) {
// init the ControllerConfig, but don't save it anywhere, just load it into the cache
this.controllerConfigURL = ConfigXMLReader.getControllerConfigURL(context);
try {
ConfigXMLReader.getControllerConfig(this.controllerConfigURL);
} catch (WebAppConfigurationException e) {
// FIXME: controller.xml errors should throw an exception.
Debug.logError(e, "Exception thrown while parsing controller.xml file: ", module);
}
this.viewFactory = new ViewFactory(context, this.controllerConfigURL);
this.eventFactory = new EventFactory(context, this.controllerConfigURL);
this.trackServerHit = !"false".equalsIgnoreCase(context.getInitParameter("track-serverhit"));
this.trackVisit = !"false".equalsIgnoreCase(context.getInitParameter("track-visit"));
}
public ConfigXMLReader.ControllerConfig getControllerConfig() {
try {
return ConfigXMLReader.getControllerConfig(this.controllerConfigURL);
} catch (WebAppConfigurationException e) {
// FIXME: controller.xml errors should throw an exception.
Debug.logError(e, "Exception thrown while parsing controller.xml file: ", module);
}
return null;
}
/**
* Finds a collection of request maps in {@code ccfg} matching {@code req}.
* Otherwise fall back to matching the {@code defaultReq} field in {@code ccfg}.
*
* @param ccfg The controller containing the current configuration
* @param req The HTTP request to match
* @return a collection of request maps which might be empty
*/
static Collection<RequestMap> resolveURI(ControllerConfig ccfg, HttpServletRequest req) {
Map<String, List<RequestMap>> requestMapMap = ccfg.getRequestMapMap();
Collection<RequestMap> rmaps = resolveTemplateURI(requestMapMap, req);
if (rmaps.isEmpty()) {
Map<String, ConfigXMLReader.ViewMap> viewMapMap = ccfg.getViewMapMap();
String defaultRequest = ccfg.getDefaultRequest();
String path = req.getPathInfo();
String requestUri = getRequestUri(path);
String overrideViewUri = getOverrideViewUri(path);
if (requestMapMap.containsKey(requestUri)
// Ensure that overridden view exists.
&& (overrideViewUri == null || viewMapMap.containsKey(overrideViewUri)
|| ("SOAPService".equals(requestUri) && "wsdl".equalsIgnoreCase(req.getQueryString())))){
rmaps = requestMapMap.get(requestUri);
req.setAttribute("overriddenView", overrideViewUri);
} else if (defaultRequest != null) {
rmaps = requestMapMap.get(defaultRequest);
} else {
rmaps = null;
}
}
return rmaps != null ? rmaps : Collections.emptyList();
}
/**
* Find the request map matching {@code method}.
* Otherwise fall back to the one matching the "all" and "" special methods
* in that respective order.
*
* @param method the HTTP method to match
* @param rmaps the collection of request map candidates
* @return a request map {@code Optional}
*/
static Optional<RequestMap> resolveMethod(String method, Collection<RequestMap> rmaps) {
for (RequestMap map : rmaps) {
if (map.method.equalsIgnoreCase(method)) {
return Optional.of(map);
}
}
if (method.isEmpty()) {
return Optional.empty();
} else if (method.equals("all")) {
return resolveMethod("", rmaps);
} else {
return resolveMethod("all", rmaps);
}
}
/**
* Finds the request maps matching a segmented path.
*
* <p>A segmented path can match request maps where the {@code uri} attribute
* contains an URI template like in the {@code foo/bar/{baz}} example.
*
* @param rMapMap the map associating URIs to a list of request maps corresponding to different HTTP methods
* @param request the HTTP request to match
* @return a collection of request maps which might be empty but not {@code null}
*/
private static Collection<RequestMap> resolveTemplateURI(Map<String, List<RequestMap>> rMapMap,
HttpServletRequest request) {
// Retrieve the request path without the leading '/' character.
String path = request.getPathInfo().substring(1);
MultivaluedHashMap<String, String> vars = new MultivaluedHashMap<>();
for (Map.Entry<String, List<RequestMap>> entry : rMapMap.entrySet()) {
URITemplate uriTemplate = URITemplate.createExactTemplate(entry.getKey());
// Check if current path the URI template exactly.
if (uriTemplate.match(path, vars) && vars.getFirst("FINAL_MATCH_GROUP").equals("/")) {
// Set attributes from template variables to be used in context.
uriTemplate.getVariables().forEach(var -> request.setAttribute(var, vars.getFirst(var)));
return entry.getValue();
}
}
return Collections.emptyList();
}
public void doRequest(HttpServletRequest request, HttpServletResponse response, String chain,
GenericValue userLogin, Delegator delegator) throws RequestHandlerException, RequestHandlerExceptionAllowExternalRequests {
final boolean throwRequestHandlerExceptionOnMissingLocalRequest = EntityUtilProperties.propertyValueEqualsIgnoreCase(
"requestHandler", "throwRequestHandlerExceptionOnMissingLocalRequest", "Y", delegator);
long startTime = System.currentTimeMillis();
HttpSession session = request.getSession();
// Parse controller config.
try {
ccfg = new ControllerConfig(getControllerConfig());
} catch (WebAppConfigurationException e) {
Debug.logError(e, "Exception thrown while parsing controller.xml file: ", module);
throw new RequestHandlerException(e);
}
// workaround if we are in the root webapp
String cname = UtilHttp.getApplicationName(request);
// Grab data from request object to process
String defaultRequestUri = RequestHandler.getRequestUri(request.getPathInfo());
if (request.getAttribute("targetRequestUri") == null) {
if (request.getSession().getAttribute("_PREVIOUS_REQUEST_") != null) {
request.setAttribute("targetRequestUri", request.getSession().getAttribute("_PREVIOUS_REQUEST_"));
} else {
request.setAttribute("targetRequestUri", "/" + defaultRequestUri);
}
}
String requestMissingErrorMessage = "Unknown request ["
+ defaultRequestUri
+ "]; this request does not exist or cannot be called directly.";
String path = request.getPathInfo();
String requestUri = getRequestUri(path);
Collection<RequestMap> rmaps = resolveURI(ccfg, request);
if (rmaps.isEmpty()) {
if (throwRequestHandlerExceptionOnMissingLocalRequest) {
if (path.contains("/checkLogin/")) {
// Nested requests related with checkLogin uselessly clutter the log. There is nothing to worry about, better remove this wrong error message.
return;
} else if (path.contains("/images/") || path.contains("d.png")) {
if (Debug.warningOn()) Debug.logWarning("You should check if this request is really a problem or a false alarm: " + request.getRequestURL(), module);
throw new RequestHandlerException(requestMissingErrorMessage);
} else {
throw new RequestHandlerException(requestMissingErrorMessage);
}
} else {
throw new RequestHandlerExceptionAllowExternalRequests();
}
}
// The "overriddenView" attribute is set by resolveURI when necessary.
String overrideViewUri = (String) request.getAttribute("overriddenView");
String restMethod = request.getParameter("restMethod");
String method = (restMethod != null) ? restMethod : request.getMethod();
RequestMap requestMap = resolveMethod(method, rmaps).orElseThrow(() -> {
String msg = UtilProperties.getMessage("WebappUiLabels", "RequestMethodNotMatchConfig",
UtilMisc.toList(requestUri, method), UtilHttp.getLocale(request));
return new MethodNotAllowedException(msg);
});
String eventReturn = null;
if (requestMap.metrics != null && requestMap.metrics.getThreshold() != 0.0 && requestMap.metrics.getTotalEvents() > 3 && requestMap.metrics.getThreshold() < requestMap.metrics.getServiceRate()) {
eventReturn = "threshold-exceeded";
}
ConfigXMLReader.RequestMap originalRequestMap = requestMap; // Save this so we can update the correct performance metrics.
boolean interruptRequest = false;
// Check for chained request.
if (chain != null) {
String chainRequestUri = RequestHandler.getRequestUri(chain);
requestMap = ccfg.getRequestMapMap().getFirst(chainRequestUri);
if (requestMap == null) {
throw new RequestHandlerException("Unknown chained request [" + chainRequestUri + "]; this request does not exist");
}
if (request.getAttribute("_POST_CHAIN_VIEW_") != null) {
overrideViewUri = (String) request.getAttribute("_POST_CHAIN_VIEW_");
} else {
overrideViewUri = RequestHandler.getOverrideViewUri(chain);
}
if (overrideViewUri != null) {
// put this in a request attribute early in case an event needs to access it
// not using _POST_CHAIN_VIEW_ because it shouldn't be set unless the event execution is successful
request.setAttribute("_CURRENT_CHAIN_VIEW_", overrideViewUri);
}
if (Debug.infoOn()) Debug.logInfo("[RequestHandler]: Chain in place: requestUri=" + chainRequestUri + " overrideViewUri=" + overrideViewUri + showSessionId(request), module);
} else {
// Check if X509 is required and we are not secure; throw exception
if (!request.isSecure() && requestMap.securityCert) {
throw new RequestHandlerException(requestMissingErrorMessage);
}
// Check to make sure we are allowed to access this request directly. (Also checks if this request is defined.)
// If the request cannot be called, or is not defined, check and see if there is a default-request we can process
if (!requestMap.securityDirectRequest) {
if (ccfg.getDefaultRequest() == null || !ccfg.getRequestMapMap().getFirst(ccfg.getDefaultRequest()).securityDirectRequest) {
// use the same message as if it was missing for security reasons, ie so can't tell if it is missing or direct request is not allowed
throw new RequestHandlerException(requestMissingErrorMessage);
} else {
requestMap = ccfg.getRequestMapMap().getFirst(ccfg.getDefaultRequest());
}
}
// Check if we SHOULD be secure and are not.
boolean forwardedHTTPS = "HTTPS".equalsIgnoreCase(request.getHeader("X-Forwarded-Proto"));
if (!request.isSecure() && !forwardedHTTPS && requestMap.securityHttps) {
// If the request method was POST then return an error to avoid problems with XSRF where the request may have come from another machine/program and had the same session ID but was not encrypted as it should have been (we used to let it pass to not lose data since it was too late to protect that data anyway)
if ("POST".equalsIgnoreCase(request.getMethod())) {
// we can't redirect with the body parameters, and for better security from XSRF, just return an error message
Locale locale = UtilHttp.getLocale(request);
String errMsg = UtilProperties.getMessage("WebappUiLabels", "requestHandler.InsecureFormPostToSecureRequest", locale);
Debug.logError("Got a insecure (non-https) form POST to a secure (http) request [" + requestMap.uri + "], returning error", module);
// see if HTTPS is enabled, if not then log a warning instead of throwing an exception
Boolean enableHttps = null;
String webSiteId = WebSiteWorker.getWebSiteId(request);
if (webSiteId != null) {
try {
GenericValue webSite = EntityQuery.use(delegator).from("WebSite").where("webSiteId", webSiteId).cache().queryOne();
if (webSite != null) enableHttps = webSite.getBoolean("enableHttps");
} catch (GenericEntityException e) {
Debug.logWarning(e, "Problems with WebSite entity; using global defaults", module);
}
}
if (enableHttps == null) {
enableHttps = EntityUtilProperties.propertyValueEqualsIgnoreCase("url", "port.https.enabled", "Y", delegator);
}
if (Boolean.FALSE.equals(enableHttps)) {
Debug.logWarning("HTTPS is disabled for this site, so we can't tell if this was encrypted or not which means if a form was POSTed and it was not over HTTPS we don't know, but it would be vulnerable to an XSRF and other attacks: " + errMsg, module);
} else {
throw new RequestHandlerException(errMsg);
}
} else {
StringBuilder urlBuf = new StringBuilder();
urlBuf.append(request.getPathInfo());
if (request.getQueryString() != null) {
urlBuf.append("?").append(request.getQueryString());
}
String newUrl = RequestHandler.makeUrl(request, response, urlBuf.toString());
if (newUrl.toUpperCase().startsWith("HTTPS")) {
// if we are supposed to be secure, redirect secure.
callRedirect(newUrl, response, request, ccfg.getStatusCodeString());
return;
}
}
}
// Check for HTTPS client (x.509) security
if (request.isSecure() && requestMap.securityCert) {
if (!checkCertificates(request, certs -> SSLUtil.isClientTrusted(certs, null))) {
Debug.logWarning(requestMissingErrorMessage, module);
throw new RequestHandlerException(requestMissingErrorMessage);
}
}
// If its the first visit run the first visit events.
if (this.trackVisit(request) && session.getAttribute("_FIRST_VISIT_EVENTS_") == null) {
if (Debug.infoOn()) {
Debug.logInfo("This is the first request in this visit." + showSessionId(request), module);
}
session.setAttribute("_FIRST_VISIT_EVENTS_", "complete");
for (ConfigXMLReader.Event event: ccfg.getFirstVisitEventList().values()) {
try {
String returnString = this.runEvent(request, response, event, null, "firstvisit");
if (returnString == null || "none".equalsIgnoreCase(returnString)) {
interruptRequest = true;
} else if (!"success".equalsIgnoreCase(returnString)) {
throw new EventHandlerException("First-Visit event did not return 'success'.");
}
} catch (EventHandlerException e) {
Debug.logError(e, module);
}
}
}
// Invoke the pre-processor (but NOT in a chain)
for (ConfigXMLReader.Event event: ccfg.getPreprocessorEventList().values()) {
try {
String returnString = this.runEvent(request, response, event, null, "preprocessor");
if (returnString == null || "none".equalsIgnoreCase(returnString)) {
interruptRequest = true;
} else if (!"success".equalsIgnoreCase(returnString)) {
if (!returnString.contains(":_protect_:")) {
throw new EventHandlerException("Pre-Processor event [" + event.invoke + "] did not return 'success'.");
} else { // protect the view normally rendered and redirect to error response view
returnString = returnString.replace(":_protect_:", "");
if (returnString.length() > 0) {
request.setAttribute("_ERROR_MESSAGE_", returnString);
}
eventReturn = null;
// check to see if there is a "protect" response, if so it's ok else show the default_error_response_view
if (!requestMap.requestResponseMap.containsKey("protect")) {
if (ccfg.getProtectView() != null) {
overrideViewUri = ccfg.getProtectView();
} else {
overrideViewUri = EntityUtilProperties.getPropertyValue("security", "default.error.response.view", delegator);
overrideViewUri = overrideViewUri.replace("view:", "");
if ("none:".equals(overrideViewUri)) {
interruptRequest = true;
}
}
}
}
}
} catch (EventHandlerException e) {
Debug.logError(e, module);
}
}
}
// Pre-Processor/First-Visit event(s) can interrupt the flow by returning null.
// Warning: this could cause problems if more then one event attempts to return a response.
if (interruptRequest) {
if (Debug.infoOn()) Debug.logInfo("[Pre-Processor Interrupted Request, not running: [" + requestMap.uri + "]. " + showSessionId(request), module);
return;
}
if (Debug.verboseOn()) Debug.logVerbose("[Processing Request]: " + requestMap.uri + showSessionId(request), module);
request.setAttribute("thisRequestUri", requestMap.uri); // store the actual request URI
// Perform security check.
if (requestMap.securityAuth) {
// Invoke the security handler
// catch exceptions and throw RequestHandlerException if failed.
if (Debug.verboseOn()) Debug.logVerbose("[RequestHandler]: AuthRequired. Running security check. " + showSessionId(request), module);
ConfigXMLReader.Event checkLoginEvent = ccfg.getRequestMapMap().getFirst("checkLogin").event;
String checkLoginReturnString = null;
try {
checkLoginReturnString = this.runEvent(request, response, checkLoginEvent, null, "security-auth");
} catch (EventHandlerException e) {
throw new RequestHandlerException(e.getMessage(), e);
}
if (!"success".equalsIgnoreCase(checkLoginReturnString)) {
// previous URL already saved by event, so just do as the return says...
eventReturn = checkLoginReturnString;
// if the request is an ajax request we don't want to return the default login check
if (!"XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
requestMap = ccfg.getRequestMapMap().getFirst("checkLogin");
} else {
requestMap = ccfg.getRequestMapMap().getFirst("ajaxCheckLogin");
}
}
}
// after security check but before running the event, see if a post-login redirect has completed and we have data from the pre-login request form to use now
// we know this is the case if the _PREVIOUS_PARAM_MAP_ attribute is there, but the _PREVIOUS_REQUEST_ attribute has already been removed
if (request.getSession().getAttribute("_PREVIOUS_PARAM_MAP_FORM_") != null && request.getSession().getAttribute("_PREVIOUS_REQUEST_") == null) {
Map<String, Object> previousParamMap = UtilGenerics.checkMap(request.getSession().getAttribute("_PREVIOUS_PARAM_MAP_FORM_"), String.class, Object.class);
for (Map.Entry<String, Object> previousParamEntry: previousParamMap.entrySet()) {
request.setAttribute(previousParamEntry.getKey(), previousParamEntry.getValue());
}
// to avoid this data being included again, now remove the _PREVIOUS_PARAM_MAP_ attribute
request.getSession().removeAttribute("_PREVIOUS_PARAM_MAP_FORM_");
}
// now we can start looking for the next request response to use
ConfigXMLReader.RequestResponse nextRequestResponse = null;
// Invoke the defined event (unless login failed)
if (eventReturn == null && requestMap.event != null) {
if (requestMap.event.type != null && requestMap.event.path != null && requestMap.event.invoke != null) {
try {
long eventStartTime = System.currentTimeMillis();
// run the request event
eventReturn = this.runEvent(request, response, requestMap.event, requestMap, "request");
if (requestMap.event.metrics != null) {
requestMap.event.metrics.recordServiceRate(1, System.currentTimeMillis() - startTime);
}
// save the server hit for the request event
if (this.trackStats(request)) {
ServerHitBin.countEvent(cname + "." + requestMap.event.invoke, request, eventStartTime,
System.currentTimeMillis() - eventStartTime, userLogin);
}
// set the default event return
if (eventReturn == null) {
nextRequestResponse = ConfigXMLReader.emptyNoneRequestResponse;
}
} catch (EventHandlerException e) {
// check to see if there is an "error" response, if so go there and make an request error message
if (requestMap.requestResponseMap.containsKey("error")) {
eventReturn = "error";
Locale locale = UtilHttp.getLocale(request);
String errMsg = UtilProperties.getMessage("WebappUiLabels", "requestHandler.error_call_event", locale);
request.setAttribute("_ERROR_MESSAGE_", errMsg + ": " + e.toString());
} else {
throw new RequestHandlerException("Error calling event and no error response was specified", e);
}
}
}
}
// Process the eventReturn
// at this point eventReturnString is finalized, so get the RequestResponse
ConfigXMLReader.RequestResponse eventReturnBasedRequestResponse;
if (eventReturn == null) {
eventReturnBasedRequestResponse = null;
} else {
eventReturnBasedRequestResponse = requestMap.requestResponseMap.get(eventReturn);
if (eventReturnBasedRequestResponse == null && "none".equals(eventReturn)) {
eventReturnBasedRequestResponse = ConfigXMLReader.emptyNoneRequestResponse;
}
}
if (eventReturnBasedRequestResponse != null) {
//String eventReturnBasedResponse = requestResponse.value;
if (Debug.verboseOn()) Debug.logVerbose("[Response Qualified]: " + eventReturnBasedRequestResponse.name + ", " + eventReturnBasedRequestResponse.type + ":" + eventReturnBasedRequestResponse.value + showSessionId(request), module);
// If error, then display more error messages:
if ("error".equals(eventReturnBasedRequestResponse.name)) {
if (Debug.errorOn()) {
String errorMessageHeader = "Request " + requestMap.uri + " caused an error with the following message: ";
if (request.getAttribute("_ERROR_MESSAGE_") != null) {
Debug.logError(errorMessageHeader + request.getAttribute("_ERROR_MESSAGE_"), module);
}
if (request.getAttribute("_ERROR_MESSAGE_LIST_") != null) {
Debug.logError(errorMessageHeader + request.getAttribute("_ERROR_MESSAGE_LIST_"), module);
}
}
}
} else if (eventReturn != null) {
// only log this warning if there is an eventReturn (ie skip if no event, etc)
Debug.logWarning("Could not find response in request [" + requestMap.uri + "] for event return [" + eventReturn + "]", module);
}
// Set the next view (don't use event return if success, default to nextView (which is set to eventReturn later if null); also even if success if it is a type "none" response ignore the nextView, ie use the eventReturn)
if (eventReturnBasedRequestResponse != null && (!"success".equals(eventReturnBasedRequestResponse.name) || "none".equals(eventReturnBasedRequestResponse.type))) nextRequestResponse = eventReturnBasedRequestResponse;
// get the previous request info
String previousRequest = (String) request.getSession().getAttribute("_PREVIOUS_REQUEST_");
String loginPass = (String) request.getAttribute("_LOGIN_PASSED_");
// restore previous redirected request's attribute, so redirected page can display previous request's error msg etc.
String preReqAttStr = (String) request.getSession().getAttribute("_REQ_ATTR_MAP_");
if (preReqAttStr != null) {
request.getSession().removeAttribute("_REQ_ATTR_MAP_");
byte[] reqAttrMapBytes = StringUtil.fromHexString(preReqAttStr);
Map<String, Object> preRequestMap = checkMap(UtilObject.getObject(reqAttrMapBytes), String.class, Object.class);
if (UtilValidate.isNotEmpty(preRequestMap)) {
for (Map.Entry<String, Object> entry: preRequestMap.entrySet()) {
String key = entry.getKey();
if ("_ERROR_MESSAGE_LIST_".equals(key) || "_ERROR_MESSAGE_MAP_".equals(key) || "_ERROR_MESSAGE_".equals(key) ||
"_EVENT_MESSAGE_LIST_".equals(key) || "_EVENT_MESSAGE_".equals(key)) {
request.setAttribute(key, entry.getValue());
}
}
}
}
if (Debug.verboseOn()) Debug.logVerbose("[RequestHandler]: previousRequest - " + previousRequest + " (" + loginPass + ")" + showSessionId(request), module);
// if previous request exists, and a login just succeeded, do that now.
if (previousRequest != null && loginPass != null && "TRUE".equalsIgnoreCase(loginPass)) {
request.getSession().removeAttribute("_PREVIOUS_REQUEST_");
// special case to avoid login/logout looping: if request was "logout" before the login, change to null for default success view; do the same for "login" to avoid going back to the same page
if ("logout".equals(previousRequest) || "/logout".equals(previousRequest) || "login".equals(previousRequest) || "/login".equals(previousRequest) || "checkLogin".equals(previousRequest) || "/checkLogin".equals(previousRequest) || "/checkLogin/login".equals(previousRequest)) {
Debug.logWarning("Found special _PREVIOUS_REQUEST_ of [" + previousRequest + "], setting to null to avoid problems, not running request again", module);
} else {
if (Debug.infoOn()) Debug.logInfo("[Doing Previous Request]: " + previousRequest + showSessionId(request), module);
// note that the previous form parameters are not setup (only the URL ones here), they will be found in the session later and handled when the old request redirect comes back
Map<String, Object> previousParamMap = UtilGenerics.checkMap(request.getSession().getAttribute("_PREVIOUS_PARAM_MAP_URL_"), String.class, Object.class);
String queryString = UtilHttp.urlEncodeArgs(previousParamMap, false);
String redirectTarget = previousRequest;
if (UtilValidate.isNotEmpty(queryString)) {
redirectTarget += "?" + queryString;
}
callRedirect(makeLink(request, response, redirectTarget), response, request, ccfg.getStatusCodeString());
return;
}
}
ConfigXMLReader.RequestResponse successResponse = requestMap.requestResponseMap.get("success");
if ((eventReturn == null || "success".equals(eventReturn)) && successResponse != null && "request".equals(successResponse.type)) {
// chains will override any url defined views; but we will save the view for the very end
if (UtilValidate.isNotEmpty(overrideViewUri)) {
request.setAttribute("_POST_CHAIN_VIEW_", overrideViewUri);
}
nextRequestResponse = successResponse;
}
// Make sure we have some sort of response to go to
if (nextRequestResponse == null) nextRequestResponse = successResponse;
if (nextRequestResponse == null) {
throw new RequestHandlerException("Illegal response; handler could not process request [" + requestMap.uri + "] and event return [" + eventReturn + "].");
}
if (Debug.verboseOn()) Debug.logVerbose("[Event Response Selected] type=" + nextRequestResponse.type + ", value=" + nextRequestResponse.value + ". " + showSessionId(request), module);
// ========== Handle the responses - chains/views ==========
// if the request has the save-last-view attribute set, save it now before the view can be rendered or other chain done so that the _LAST* session attributes will represent the previous request
if (nextRequestResponse.saveLastView) {
// Debug.logInfo("======save last view: " + session.getAttribute("_LAST_VIEW_NAME_"));
String lastViewName = (String) session.getAttribute("_LAST_VIEW_NAME_");
// Do not save the view if the last view is the same as the current view and saveCurrentView is false
if (!(!nextRequestResponse.saveCurrentView && "view".equals(nextRequestResponse.type) && nextRequestResponse.value.equals(lastViewName))) {
session.setAttribute("_SAVED_VIEW_NAME_", session.getAttribute("_LAST_VIEW_NAME_"));
session.setAttribute("_SAVED_VIEW_PARAMS_", session.getAttribute("_LAST_VIEW_PARAMS_"));
}
}
String saveName = null;
if (nextRequestResponse.saveCurrentView) { saveName = "SAVED"; }
if (nextRequestResponse.saveHomeView) { saveName = "HOME"; }
if ("request".equals(nextRequestResponse.type)) {
// chained request
Debug.logInfo("[RequestHandler.doRequest]: Response is a chained request." + showSessionId(request), module);
doRequest(request, response, nextRequestResponse.value, userLogin, delegator);
} else {
// ======== handle views ========
// first invoke the post-processor events.
for (ConfigXMLReader.Event event: ccfg.getPostprocessorEventList().values()) {
try {
String returnString = this.runEvent(request, response, event, requestMap, "postprocessor");
if (returnString != null && !"success".equalsIgnoreCase(returnString)) {
throw new EventHandlerException("Post-Processor event did not return 'success'.");
}
} catch (EventHandlerException e) {
Debug.logError(e, module);
}
}
String responseStatusCode = nextRequestResponse.statusCode;
if(UtilValidate.isNotEmpty(responseStatusCode))
ccfg.setStatusCodeString(responseStatusCode);
if ("url".equals(nextRequestResponse.type)) {
if (Debug.verboseOn()) Debug.logVerbose("[RequestHandler.doRequest]: Response is a URL redirect." + showSessionId(request), module);
callRedirect(nextRequestResponse.value, response, request, ccfg.getStatusCodeString());
} else if ("url-redirect".equals(nextRequestResponse.type)) {
// check for a cross-application redirect
if (Debug.verboseOn())
Debug.logVerbose("[RequestHandler.doRequest]: Response is a URL redirect with redirect parameters."
+ showSessionId(request), module);
callRedirect(nextRequestResponse.value + this.makeQueryString(request, nextRequestResponse), response,
request, ccfg.getStatusCodeString());
} else if ("cross-redirect".equals(nextRequestResponse.type)) {
// check for a cross-application redirect
if (Debug.verboseOn()) Debug.logVerbose("[RequestHandler.doRequest]: Response is a Cross-Application redirect." + showSessionId(request), module);
String url = nextRequestResponse.value.startsWith("/") ? nextRequestResponse.value : "/" + nextRequestResponse.value;
callRedirect(url + this.makeQueryString(request, nextRequestResponse), response, request, ccfg.getStatusCodeString());
} else if ("request-redirect".equals(nextRequestResponse.type)) {
if (Debug.verboseOn()) Debug.logVerbose("[RequestHandler.doRequest]: Response is a Request redirect." + showSessionId(request), module);
callRedirect(makeLinkWithQueryString(request, response, "/" + nextRequestResponse.value, nextRequestResponse), response, request, ccfg.getStatusCodeString());
} else if ("request-redirect-noparam".equals(nextRequestResponse.type)) {
if (Debug.verboseOn()) Debug.logVerbose("[RequestHandler.doRequest]: Response is a Request redirect with no parameters." + showSessionId(request), module);
callRedirect(makeLink(request, response, nextRequestResponse.value), response, request, ccfg.getStatusCodeString());
} else if ("view".equals(nextRequestResponse.type)) {
if (Debug.verboseOn()) Debug.logVerbose("[RequestHandler.doRequest]: Response is a view." + showSessionId(request), module);
// check for an override view, only used if "success" = eventReturn
String viewName = (UtilValidate.isNotEmpty(overrideViewUri) && (eventReturn == null || "success".equals(eventReturn))) ? overrideViewUri : nextRequestResponse.value;
renderView(viewName, requestMap.securityExternalView, request, response, saveName);
} else if ("view-last".equals(nextRequestResponse.type)) {
if (Debug.verboseOn()) Debug.logVerbose("[RequestHandler.doRequest]: Response is a view." + showSessionId(request), module);
// check for an override view, only used if "success" = eventReturn
String viewName = (UtilValidate.isNotEmpty(overrideViewUri) && (eventReturn == null || "success".equals(eventReturn))) ? overrideViewUri : nextRequestResponse.value;
// as a further override, look for the _SAVED and then _HOME and then _LAST session attributes
Map<String, Object> urlParams = null;
if (session.getAttribute("_SAVED_VIEW_NAME_") != null) {
viewName = (String) session.getAttribute("_SAVED_VIEW_NAME_");
urlParams = UtilGenerics.cast(session.getAttribute("_SAVED_VIEW_PARAMS_"));
} else if (session.getAttribute("_HOME_VIEW_NAME_") != null) {
viewName = (String) session.getAttribute("_HOME_VIEW_NAME_");
urlParams = UtilGenerics.cast(session.getAttribute("_HOME_VIEW_PARAMS_"));
} else if (session.getAttribute("_LAST_VIEW_NAME_") != null) {
viewName = (String) session.getAttribute("_LAST_VIEW_NAME_");
urlParams = UtilGenerics.cast(session.getAttribute("_LAST_VIEW_PARAMS_"));
} else if (UtilValidate.isNotEmpty(nextRequestResponse.value)) {
viewName = nextRequestResponse.value;
}
if (UtilValidate.isEmpty(viewName) && UtilValidate.isNotEmpty(nextRequestResponse.value)) {
viewName = nextRequestResponse.value;
}
if (urlParams != null) {
for (Map.Entry<String, Object> urlParamEntry: urlParams.entrySet()) {
String key = urlParamEntry.getKey();
// Don't overwrite messages coming from the current event
if (!("_EVENT_MESSAGE_".equals(key) || "_ERROR_MESSAGE_".equals(key)
|| "_EVENT_MESSAGE_LIST_".equals(key) || "_ERROR_MESSAGE_LIST_".equals(key))) {
request.setAttribute(key, urlParamEntry.getValue());
}
}
}
renderView(viewName, requestMap.securityExternalView, request, response, null);
} else if ("view-last-noparam".equals(nextRequestResponse.type)) {
if (Debug.verboseOn()) Debug.logVerbose("[RequestHandler.doRequest]: Response is a view." + showSessionId(request), module);
// check for an override view, only used if "success" = eventReturn
String viewName = (UtilValidate.isNotEmpty(overrideViewUri) && (eventReturn == null || "success".equals(eventReturn))) ? overrideViewUri : nextRequestResponse.value;
// as a further override, look for the _SAVED and then _HOME and then _LAST session attributes
if (session.getAttribute("_SAVED_VIEW_NAME_") != null) {
viewName = (String) session.getAttribute("_SAVED_VIEW_NAME_");
} else if (session.getAttribute("_HOME_VIEW_NAME_") != null) {
viewName = (String) session.getAttribute("_HOME_VIEW_NAME_");
} else if (session.getAttribute("_LAST_VIEW_NAME_") != null) {
viewName = (String) session.getAttribute("_LAST_VIEW_NAME_");
} else if (UtilValidate.isNotEmpty(nextRequestResponse.value)) {
viewName = nextRequestResponse.value;
}
renderView(viewName, requestMap.securityExternalView, request, response, null);
} else if ("view-home".equals(nextRequestResponse.type)) {
if (Debug.verboseOn()) Debug.logVerbose("[RequestHandler.doRequest]: Response is a view." + showSessionId(request), module);
// check for an override view, only used if "success" = eventReturn
String viewName = (UtilValidate.isNotEmpty(overrideViewUri) && (eventReturn == null || "success".equals(eventReturn))) ? overrideViewUri : nextRequestResponse.value;
// as a further override, look for the _HOME session attributes
Map<String, Object> urlParams = null;
if (session.getAttribute("_HOME_VIEW_NAME_") != null) {
viewName = (String) session.getAttribute("_HOME_VIEW_NAME_");
urlParams = UtilGenerics.cast(session.getAttribute("_HOME_VIEW_PARAMS_"));
}
if (urlParams != null) {
for (Map.Entry<String, Object> urlParamEntry: urlParams.entrySet()) {
request.setAttribute(urlParamEntry.getKey(), urlParamEntry.getValue());
}
}
renderView(viewName, requestMap.securityExternalView, request, response, null);
} else if ("none".equals(nextRequestResponse.type)) {
// no view to render (meaning the return was processed by the event)
if (Debug.verboseOn()) Debug.logVerbose("[RequestHandler.doRequest]: Response is handled by the event." + showSessionId(request), module);
}
}
if (originalRequestMap.metrics != null) {
originalRequestMap.metrics.recordServiceRate(1, System.currentTimeMillis() - startTime);
}
}
/** Find the event handler and invoke an event. */
public String runEvent(HttpServletRequest request, HttpServletResponse response,
ConfigXMLReader.Event event, ConfigXMLReader.RequestMap requestMap, String trigger) throws EventHandlerException {
EventHandler eventHandler = eventFactory.getEventHandler(event.type);
String eventReturn = eventHandler.invoke(event, requestMap, request, response);
if (Debug.verboseOn() || (Debug.infoOn() && "request".equals(trigger))) Debug.logInfo("Ran Event [" + event.type + ":" + event.path + "#" + event.invoke + "] from [" + trigger + "], result is [" + eventReturn + "]", module);
return eventReturn;
}
/** Returns the default error page for this request. */
public String getDefaultErrorPage(HttpServletRequest request) {
URL errorPage = null;
try {
String errorPageLocation = getControllerConfig().getErrorpage();
errorPage = FlexibleLocation.resolveLocation(errorPageLocation);
} catch (MalformedURLException e) {
Debug.logError(e, "Exception thrown while parsing controller.xml file: ", module);
}
if (errorPage == null) {
return "/error/error.jsp";
}
return errorPage.toString();
}
/** Returns the default status-code for this request. */
public String getStatusCode(HttpServletRequest request) {
String statusCode = getControllerConfig().getStatusCode();
return UtilValidate.isNotEmpty(statusCode) ? statusCode : null;
}
/** Returns the ViewFactory Object. */
public ViewFactory getViewFactory() {
return viewFactory;
}
/** Returns the EventFactory Object. */
public EventFactory getEventFactory() {
return eventFactory;
}
public static String getRequestUri(String path) {
List<String> pathInfo = StringUtil.split(path, "/");
if (UtilValidate.isEmpty(pathInfo)) {
Debug.logWarning("Got nothing when splitting URI: " + path, module);
return null;
}
if (pathInfo.get(0).indexOf('?') > -1) {
return pathInfo.get(0).substring(0, pathInfo.get(0).indexOf('?'));
} else {
return pathInfo.get(0);
}
}
public static String getOverrideViewUri(String path) {
List<String> pathItemList = StringUtil.split(path, "/");
if (pathItemList == null) {
return null;
}
pathItemList = pathItemList.subList(1, pathItemList.size());
String nextPage = null;
for (String pathItem: pathItemList) {
if (pathItem.indexOf('~') != 0) {
if (pathItem.indexOf('?') > -1) {
pathItem = pathItem.substring(0, pathItem.indexOf('?'));
}
nextPage = (nextPage == null ? pathItem : nextPage + "/" + pathItem);
}
}
return nextPage;
}
private static void callRedirect(String url, HttpServletResponse resp, HttpServletRequest req, String statusCodeString) throws RequestHandlerException {
if (Debug.infoOn()) Debug.logInfo("Sending redirect to: [" + url + "]. " + showSessionId(req), module);
// set the attributes in the session so we can access it.
Enumeration<String> attributeNameEnum = UtilGenerics.cast(req.getAttributeNames());
Map<String, Object> reqAttrMap = new HashMap<>();
Integer statusCode;
try {
statusCode = Integer.valueOf(statusCodeString);
} catch (NumberFormatException e) {
statusCode = 303;
}
while (attributeNameEnum.hasMoreElements()) {
String name = attributeNameEnum.nextElement();
Object obj = req.getAttribute(name);
if (obj instanceof Serializable) {
if (obj instanceof Map) {
// See OFBIZ-750 and OFBIZ-11123 for cases where a value in an inner Map is not serializable
UtilMisc.makeMapSerializable(UtilGenerics.cast(obj));
}
reqAttrMap.put(name, obj);
}
}
if (reqAttrMap.size() > 0) {
byte[] reqAttrMapBytes = UtilObject.getBytes(reqAttrMap);
if (reqAttrMapBytes != null) {
req.getSession().setAttribute("_REQ_ATTR_MAP_", StringUtil.toHexString(reqAttrMapBytes));
}
}
// send the redirect
try {
resp.setStatus(statusCode);
resp.setHeader("Location", url);
resp.setHeader("Connection", "close");
} catch (IllegalStateException ise) {
throw new RequestHandlerException(ise.getMessage(), ise);
}
}
private void renderView(String view, boolean allowExtView, HttpServletRequest req, HttpServletResponse resp, String saveName) throws RequestHandlerException {
GenericValue userLogin = (GenericValue) req.getSession().getAttribute("userLogin");
// workaround if we are in the root webapp
String cname = UtilHttp.getApplicationName(req);
String oldView = view;
if (UtilValidate.isNotEmpty(view) && view.charAt(0) == '/') {
view = view.substring(1);
}
// if the view name starts with the control servlet name and a /, then it was an
// attempt to override the default view with a call back into the control servlet,
// so just get the target view name and use that
String servletName = req.getServletPath();
if (UtilValidate.isNotEmpty(servletName) && servletName.length() > 1 || servletName.startsWith("/")) {
servletName = servletName.substring(1);
}
if (UtilHttp.getVisualTheme(req) == null) {
UtilHttp.setVisualTheme(req.getSession(), ThemeFactory.resolveVisualTheme(req));
}
if (Debug.infoOn()) Debug.logInfo("Rendering View [" + view + "]. " + showSessionId(req), module);
if (view.startsWith(servletName + "/")) {
view = view.substring(servletName.length() + 1);
if (Debug.infoOn()) Debug.logInfo("a manual control servlet request was received, removing control servlet path resulting in: view=" + view, module);
}
if (Debug.verboseOn()) Debug.logVerbose("[Getting View Map]: " + view + showSessionId(req), module);
// before mapping the view, set a request attribute so we know where we are
req.setAttribute("_CURRENT_VIEW_", view);
// save the view in the session for the last view, plus the parameters Map (can use all parameters as they will never go into a URL, will only stay in the session and extra data will be ignored as we won't go to the original request just the view); note that this is saved after the request/view processing has finished so when those run they will get the value from the previous request
Map<String, Object> paramMap = UtilHttp.getParameterMap(req);
// add in the attributes as well so everything needed for the rendering context will be in place if/when we get back to this view
paramMap.putAll(UtilHttp.getAttributeMap(req));
UtilMisc.makeMapSerializable(paramMap);
if (paramMap.containsKey("_LAST_VIEW_NAME_")) { // Used by lookups to keep the real view (request)
req.getSession().setAttribute("_LAST_VIEW_NAME_", paramMap.get("_LAST_VIEW_NAME_"));
} else {
req.getSession().setAttribute("_LAST_VIEW_NAME_", view);
}
req.getSession().setAttribute("_LAST_VIEW_PARAMS_", paramMap);
if ("SAVED".equals(saveName)) {
//Debug.logInfo("======save current view: " + view);
req.getSession().setAttribute("_SAVED_VIEW_NAME_", view);
req.getSession().setAttribute("_SAVED_VIEW_PARAMS_", paramMap);
}
if ("HOME".equals(saveName)) {
//Debug.logInfo("======save home view: " + view);
req.getSession().setAttribute("_HOME_VIEW_NAME_", view);
req.getSession().setAttribute("_HOME_VIEW_PARAMS_", paramMap);
// clear other saved views
req.getSession().removeAttribute("_SAVED_VIEW_NAME_");
req.getSession().removeAttribute("_SAVED_VIEW_PARAMS_");
}
ConfigXMLReader.ViewMap viewMap = (view == null) ? null : getControllerConfig().getViewMapMap().get(view);
if (viewMap == null) {
throw new RequestHandlerException("No definition found for view with name [" + view + "]");
}
String nextPage;
if (viewMap.page == null) {
if (!allowExtView) {
throw new RequestHandlerException("No view to render.");
} else {
nextPage = "/" + oldView;
}
} else {
nextPage = viewMap.page;
}