/
RequestCycle.java
933 lines (844 loc) · 24 KB
/
RequestCycle.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
/*
* 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.wicket.request.cycle;
import java.util.Optional;
import org.apache.wicket.Application;
import org.apache.wicket.IMetadataContext;
import org.apache.wicket.MetaDataEntry;
import org.apache.wicket.MetaDataKey;
import org.apache.wicket.Page;
import org.apache.wicket.Session;
import org.apache.wicket.ThreadContext;
import org.apache.wicket.WicketRuntimeException;
import org.apache.wicket.core.request.handler.BookmarkablePageRequestHandler;
import org.apache.wicket.core.request.handler.IPageProvider;
import org.apache.wicket.core.request.handler.PageProvider;
import org.apache.wicket.core.request.handler.RenderPageRequestHandler;
import org.apache.wicket.event.IEvent;
import org.apache.wicket.event.IEventSink;
import org.apache.wicket.protocol.http.IRequestLogger;
import org.apache.wicket.request.IExceptionMapper;
import org.apache.wicket.request.IRequestCycle;
import org.apache.wicket.request.IRequestHandler;
import org.apache.wicket.request.IRequestMapper;
import org.apache.wicket.request.Request;
import org.apache.wicket.request.RequestHandlerExecutor;
import org.apache.wicket.request.RequestHandlerExecutor.ReplaceHandlerException;
import org.apache.wicket.request.Response;
import org.apache.wicket.request.Url;
import org.apache.wicket.request.UrlRenderer;
import org.apache.wicket.request.component.IRequestablePage;
import org.apache.wicket.request.handler.resource.ResourceReferenceRequestHandler;
import org.apache.wicket.request.handler.resource.ResourceRequestHandler;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.request.resource.IResource;
import org.apache.wicket.request.resource.ResourceReference;
import org.apache.wicket.request.resource.caching.IStaticCacheableResource;
import org.apache.wicket.util.lang.Args;
import org.apache.wicket.util.lang.Exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* {@link RequestCycle} consists of two steps:
* <ol>
* <li>Resolve request handler
* <li>Execute request handler
* </ol>
* During {@link IRequestHandler} execution the handler can schedule another {@link IRequestHandler}
* to run after it is done, or replace all {@link IRequestHandler}s on stack with another
* {@link IRequestHandler}.
*
* @see #scheduleRequestHandlerAfterCurrent(IRequestHandler)
* @see #replaceAllRequestHandlers(IRequestHandler)
*
* @author Matej Knopp
* @author igor.vaynberg
*/
public class RequestCycle implements IRequestCycle, IEventSink, IMetadataContext<Object, RequestCycle>
{
private static final Logger log = LoggerFactory.getLogger(RequestCycle.class);
/**
* An additional logger which is used to log extra information.
* Could be disabled separately than the main logger if the application developer
* does not want to see this extra information.
*/
private static final Logger logExtra = LoggerFactory.getLogger("RequestCycleExtra");
/**
* Returns request cycle associated with current thread.
*
* @return request cycle instance or <code>null</code> if no request cycle is associated with
* current thread.
*/
public static RequestCycle get()
{
return ThreadContext.getRequestCycle();
}
/**
*
* @param requestCycle
*/
private static void set(RequestCycle requestCycle)
{
ThreadContext.setRequestCycle(requestCycle);
}
private Request request;
private final Response originalResponse;
private final IRequestMapper requestMapper;
private final IExceptionMapper exceptionMapper;
private final RequestCycleListenerCollection listeners;
private UrlRenderer urlRenderer;
/** MetaDataEntry array. */
private MetaDataEntry<?>[] metaData;
/** the time that this request cycle object was created. */
private final long startTime;
private final RequestHandlerExecutor requestHandlerExecutor;
private Response activeResponse;
/**
* Construct.
*
* @param context
*/
public RequestCycle(RequestCycleContext context)
{
Args.notNull(context, "context");
Args.notNull(context.getRequest(), "context.request");
Args.notNull(context.getResponse(), "context.response");
Args.notNull(context.getRequestMapper(), "context.requestMapper");
Args.notNull(context.getExceptionMapper(), "context.exceptionMapper");
listeners = new RequestCycleListenerCollection();
startTime = System.currentTimeMillis();
requestHandlerExecutor = new HandlerExecutor();
activeResponse = context.getResponse();
request = context.getRequest();
originalResponse = context.getResponse();
requestMapper = context.getRequestMapper();
exceptionMapper = context.getExceptionMapper();
}
/**
*
* @return a new url renderer
*/
protected UrlRenderer newUrlRenderer()
{
// All URLs will be rendered relative to current request (can be overridden afterwards)
return new UrlRenderer(getRequest());
}
/**
* Get the original response the request was created with. Access to the original response may
* be necessary if the response has been temporarily replaced but the components require methods
* from original response (i.e. cookie methods of WebResponse, etc).
*
* @return The original response object.
*/
public Response getOriginalResponse()
{
return originalResponse;
}
/**
* Returns {@link UrlRenderer} for this {@link RequestCycle}.
*
* @return UrlRenderer instance.
*/
@Override
public final UrlRenderer getUrlRenderer()
{
if (urlRenderer == null)
{
urlRenderer = newUrlRenderer();
}
return urlRenderer;
}
/**
* Resolves current request to a {@link IRequestHandler}.
*
* @return RequestHandler instance
*/
protected IRequestHandler resolveRequestHandler()
{
return requestMapper.mapRequest(request);
}
/**
* @return How many times will Wicket attempt to render the exception request handler before
* giving up.
*/
protected int getExceptionRetryCount()
{
int retries = 10;
if (Application.exists())
{
retries = Application.get().getRequestCycleSettings().getExceptionRetryCount();
}
return retries;
}
/**
* Convenience method that processes the request and detaches the {@link RequestCycle}.
*
* @return <code>true</code> if the request resolved to a Wicket request, <code>false</code>
* otherwise.
*/
public boolean processRequestAndDetach()
{
boolean result;
try
{
result = processRequest();
}
finally
{
detach();
}
return result;
}
/**
* Processes the request.
*
* @return <code>true</code> if the request resolved to a Wicket request, <code>false</code>
* otherwise.
*/
public boolean processRequest()
{
try
{
set(this);
listeners.onBeginRequest(this);
onBeginRequest();
IRequestHandler handler = resolveRequestHandler();
if (handler == null)
{
// Did not find any suitable handler, thus not executing the request
log.debug(
"No suitable handler found for URL {}, falling back to container to process this request",
request.getUrl());
}
else
{
execute(handler);
return true;
}
}
catch (Exception exception)
{
return executeExceptionRequestHandler(exception, getExceptionRetryCount());
}
finally
{
set(null);
}
return false;
}
/**
* Execute a request handler and notify registered {@link IRequestCycleListener}s.
*
* @param handler
*/
private void execute(IRequestHandler handler)
{
Args.notNull(handler, "handler");
while (handler != null) {
try
{
listeners.onRequestHandlerResolved(this, handler);
IRequestHandler next = requestHandlerExecutor.execute(handler);
listeners.onRequestHandlerExecuted(this, handler);
handler = next;
}
catch (RuntimeException e)
{
ReplaceHandlerException replacer = Exceptions.findCause(e, ReplaceHandlerException.class);
if (replacer == null)
{
throw e;
}
if (replacer.getRemoveScheduled())
{
requestHandlerExecutor.schedule(null);
}
handler = replacer.getReplacementRequestHandler();
}
}
}
/**
* Process the given exception.
*
* @param exception
* @param retryCount
*/
private boolean executeExceptionRequestHandler(Exception exception, int retryCount)
{
IRequestHandler handler = handleException(exception);
if (handler == null)
{
log.error("Error during request processing. URL=" + request.getUrl(), exception);
return false;
}
scheduleRequestHandlerAfterCurrent(null);
try
{
listeners.onExceptionRequestHandlerResolved(this, handler, exception);
execute(handler);
return true;
}
catch (Exception e)
{
if (retryCount > 0)
{
return executeExceptionRequestHandler(exception, retryCount - 1);
}
else
{
log.error("Exception retry count exceeded", e);
return false;
}
}
}
/**
* Return {@link IRequestHandler} for the given exception.
*
* @param e exception to handle
* @return RequestHandler instance
*
* @see IRequestCycleListener#onException(RequestCycle, Exception)
* @see IExceptionMapper#map(Exception)
*/
protected IRequestHandler handleException(final Exception e)
{
if (Application.exists() && Application.get().usesDevelopmentConfig())
{
/*
* Call out the fact that we are processing an exception in a loud way, helps to notice
* them when developing even if they get wrapped or processed in a custom handler.
*/
logExtra.warn("********************************");
logExtra.warn("Handling the following exception", e);
logExtra.warn("********************************");
}
IRequestHandler handler = listeners.onException(this, e);
if (handler != null)
{
return handler;
}
return exceptionMapper.map(e);
}
/**
* @return current request
*/
@Override
public Request getRequest()
{
return request;
}
/**
* INTERNAL This method is for internal Wicket use. Do not call it yourself unless you know what
* you are doing.
*
* @param request
*/
public void setRequest(Request request)
{
// It would be mighty nice if request was final. However during multipart it needs to be set
// to
// MultipartServletWebRequest by Form. It can't be done before creating the request cycle
// (in wicket filter)
// because only the form knows max upload size
this.request = request;
}
/**
* Sets the metadata for this request cycle using the given key. If the metadata object is not
* of the correct type for the metadata key, an IllegalArgumentException will be thrown. For
* information on creating MetaDataKeys, see {@link MetaDataKey}.
*
* @param key
* The singleton key for the metadata
* @param object
* The metadata object
* @param <T>
* @throws IllegalArgumentException
* @see MetaDataKey
*/
@Override
public final <T> RequestCycle setMetaData(final MetaDataKey<T> key, final T object)
{
metaData = key.set(metaData, object);
return this;
}
/**
* Gets metadata for this request cycle using the given key.
*
* @param <T>
* The type of the metadata
*
* @param key
* The key for the data
* @return The metadata or null if no metadata was found for the given key
* @see MetaDataKey
*/
@Override
public final <T> T getMetaData(final MetaDataKey<T> key)
{
return key.get(metaData);
}
/**
* Returns URL for the request handler or <code>null</code> if the handler couldn't have been
* encoded.
* <p>
* <strong>Note</strong>: The produced URL is relative to the filter path. Application code most
* probably need URL relative to the currently used page, for this use
* {@linkplain #urlFor(org.apache.wicket.request.IRequestHandler)}
* </p>
*
* @param handler
* the {@link IRequestHandler request handler} for which to create a callback url
* @return Url instance or <code>null</code>
*/
public Url mapUrlFor(IRequestHandler handler)
{
final Url url = requestMapper.mapHandler(handler);
listeners.onUrlMapped(this, handler, url);
return url;
}
/**
* Returns a {@link Url} for the resource reference
* <p>
* <strong>Note</strong>: The produced URL is relative to the filter path. Application code most
* probably need URL relative to the currently used page, for this use
* {@linkplain #urlFor(org.apache.wicket.request.resource.ResourceReference, org.apache.wicket.request.mapper.parameter.PageParameters)}
* </p>
*
* @param reference
* resource reference
* @param params
* parameters for the resource or {@code null} if none
* @return {@link Url} for the reference
*/
public Url mapUrlFor(ResourceReference reference, PageParameters params)
{
return mapUrlFor(new ResourceReferenceRequestHandler(reference, params));
}
/**
* Returns a bookmarkable URL that references a given page class using a given set of page
* parameters. Since the URL which is returned contains all information necessary to instantiate
* and render the page, it can be stored in a user's browser as a stable bookmark.
* <p>
* <strong>Note</strong>: The produced URL is relative to the filter path. Application code most
* probably need URL relative to the currently used page, for this use
* {@linkplain #urlFor(Class, org.apache.wicket.request.mapper.parameter.PageParameters)}
* </p>
*
* @param <C>
* The type of the page
* @param pageClass
* Class of page
* @param parameters
* Parameters to page or {@code null} if none
* @return Bookmarkable URL to page
*/
public final <C extends Page> Url mapUrlFor(final Class<C> pageClass,
final PageParameters parameters)
{
IRequestHandler handler = new BookmarkablePageRequestHandler(new PageProvider(pageClass,
parameters));
return mapUrlFor(handler);
}
/**
* Returns a rendered {@link Url} for the resource reference
*
* @param reference
* resource reference
* @param params
* parameters for the resource or {@code null} if none
* @return {@link Url} for the reference
*/
public final CharSequence urlFor(ResourceReference reference, PageParameters params)
{
ResourceReferenceRequestHandler handler = new ResourceReferenceRequestHandler(reference,
params);
return urlFor(handler);
}
/**
* Returns a rendered bookmarkable URL that references a given page class using a given set of
* page parameters. Since the URL which is returned contains all information necessary to
* instantiate and render the page, it can be stored in a user's browser as a stable bookmark.
*
* @param <C>
*
* @param pageClass
* Class of page
* @param parameters
* Parameters to page or {@code null} if none
* @return Bookmarkable URL to page
*/
public final <C extends Page> CharSequence urlFor(final Class<C> pageClass,
final PageParameters parameters)
{
IRequestHandler handler = new BookmarkablePageRequestHandler(new PageProvider(pageClass,
parameters));
return urlFor(handler);
}
/**
* Returns the rendered URL for the request handler or <code>null</code> if the handler couldn't
* have been rendered.
* <p>
* The resulting URL will be relative to current page.
*
* @param handler
* @return Url String or <code>null</code>
*/
public CharSequence urlFor(IRequestHandler handler)
{
try
{
Url mappedUrl = mapUrlFor(handler);
CharSequence url = renderUrl(mappedUrl, handler);
return url;
}
catch (Exception x)
{
throw new WicketRuntimeException(String.format(
"An error occurred while generating an Url for handler '%s'", handler), x);
}
}
private String renderUrl(Url url, IRequestHandler handler)
{
if (url != null)
{
boolean shouldEncodeStaticResource = Application.exists() &&
Application.get().getResourceSettings().isEncodeJSessionId();
String renderedUrl = getUrlRenderer().renderUrl(url);
if (handler instanceof ResourceReferenceRequestHandler)
{
ResourceReferenceRequestHandler rrrh = (ResourceReferenceRequestHandler)handler;
IResource resource = rrrh.getResource();
if (resource != null && !(resource instanceof IStaticCacheableResource) ||
shouldEncodeStaticResource)
{
renderedUrl = getOriginalResponse().encodeURL(renderedUrl);
}
}
else if (handler instanceof ResourceRequestHandler)
{
ResourceRequestHandler rrh = (ResourceRequestHandler)handler;
IResource resource = rrh.getResource();
if (resource != null && !(resource instanceof IStaticCacheableResource) ||
shouldEncodeStaticResource)
{
renderedUrl = getOriginalResponse().encodeURL(renderedUrl);
}
}
else
{
renderedUrl = getOriginalResponse().encodeURL(renderedUrl);
}
return renderedUrl;
}
else
{
return null;
}
}
/**
* Detaches {@link RequestCycle} state. Called after request processing is complete
*/
public final void detach()
{
set(this);
try
{
onDetach();
}
finally
{
try
{
onInternalDetach();
}
finally
{
set(null);
}
}
}
private void onInternalDetach()
{
if (Session.exists())
{
Session.get().internalDetach();
}
if (Application.exists())
{
IRequestLogger requestLogger = Application.get().getRequestLogger();
if (requestLogger != null)
requestLogger.performLogging();
}
}
/**
* Called after request processing is complete, usually takes care of detaching state
*/
public void onDetach()
{
try
{
onEndRequest();
listeners.onEndRequest(this);
}
catch (RuntimeException e)
{
log.error("Exception occurred during onEndRequest", e);
}
try
{
requestHandlerExecutor.detach();
}
catch (RuntimeException exception)
{
handleDetachException(exception);
}
finally
{
listeners.onDetach(this);
}
if (Session.exists())
{
Session.get().detach();
}
}
/**
* Called to handle a {@link java.lang.RuntimeException} that might be
* thrown during detaching phase.
*
* @param exception
*/
private void handleDetachException(RuntimeException exception)
{
boolean isBufferedResponse = true;
if (Application.exists())
{
isBufferedResponse = Application.get().getRequestCycleSettings().getBufferResponse();
}
//if application is using a buffered response strategy,
//then we display exception to user.
if (isBufferedResponse)
{
throw exception;
}
else
{
log.error("Error detaching RequestCycle", exception);
}
}
/**
* Convenience method for setting next page to be rendered.
*
* @param page
*/
public void setResponsePage(IRequestablePage page)
{
if (page instanceof Page)
{
((Page) page).setStatelessHint(false);
}
scheduleRequestHandlerAfterCurrent(new RenderPageRequestHandler(new PageProvider(page),
RenderPageRequestHandler.RedirectPolicy.AUTO_REDIRECT));
}
/**
* Convenience method for setting next page to be rendered.
*
* @param pageClass
* The class of the page to render
*/
public void setResponsePage(Class<? extends IRequestablePage> pageClass)
{
setResponsePage(pageClass, null, RenderPageRequestHandler.RedirectPolicy.ALWAYS_REDIRECT);
}
/**
* Convenience method for setting next page to be rendered.
*
* @param pageClass
* The class of the page to render
* @param redirectPolicy
* The policy to use when deciding whether to redirect or not
*/
public void setResponsePage(Class<? extends IRequestablePage> pageClass, RenderPageRequestHandler.RedirectPolicy redirectPolicy)
{
setResponsePage(pageClass, null, redirectPolicy);
}
/**
* Convenience method for setting next page to be rendered.
*
* @param pageClass
* The class of the page to render
* @param parameters
* The query parameters for the page to be rendered
*/
public void setResponsePage(Class<? extends IRequestablePage> pageClass,
PageParameters parameters)
{
setResponsePage(pageClass, parameters, RenderPageRequestHandler.RedirectPolicy.ALWAYS_REDIRECT);
}
/**
* Convenience method for setting next page to be rendered.
*
* @param pageClass
* The class of the page to render
* @param parameters
* The query parameters for the page to be rendered
* @param redirectPolicy
* The policy to use when deciding whether to redirect or not
*/
public void setResponsePage(Class<? extends IRequestablePage> pageClass,
PageParameters parameters, RenderPageRequestHandler.RedirectPolicy redirectPolicy)
{
IPageProvider provider = new PageProvider(pageClass, parameters);
scheduleRequestHandlerAfterCurrent(new RenderPageRequestHandler(provider,
redirectPolicy));
}
/**
* @return The start time for this request
*/
public final long getStartTime()
{
return startTime;
}
/** {@inheritDoc} */
@Override
public void onEvent(IEvent<?> event)
{
}
/**
* Called when the request cycle object is beginning its response
*/
protected void onBeginRequest()
{
}
/**
* Called when the request cycle object has finished its response
*/
protected void onEndRequest()
{
}
/**
* @return listeners
*/
public RequestCycleListenerCollection getListeners()
{
return listeners;
}
/**
* {@inheritDoc}
*/
@Override
public Response getResponse()
{
return activeResponse;
}
/**
* {@inheritDoc}
*/
@Override
public Response setResponse(final Response response)
{
Response current = activeResponse;
activeResponse = response;
return current;
}
/**
* {@inheritDoc}
*/
@Override
public void scheduleRequestHandlerAfterCurrent(IRequestHandler handler)
{
// just delegating the call to {@link IRequestHandlerExecutor} and invoking listeners
requestHandlerExecutor.schedule(handler);
// only forward calls to the listeners when handler is null
if (handler != null)
listeners.onRequestHandlerScheduled(this, handler);
}
/**
* @see RequestHandlerExecutor#getActive()
* @return active handler on executor
*/
public IRequestHandler getActiveRequestHandler()
{
return requestHandlerExecutor.getActive();
}
/**
* @see RequestHandlerExecutor#next()
* @return the handler scheduled to be executed after current by the executor
*/
public IRequestHandler getRequestHandlerScheduledAfterCurrent()
{
return requestHandlerExecutor.next();
}
/**
* @see RequestHandlerExecutor#replaceAll(IRequestHandler)
* @param handler
*/
public void replaceAllRequestHandlers(final IRequestHandler handler)
{
requestHandlerExecutor.replaceAll(handler);
}
/**
* Finds a IRequestHandler which is either the currently executing handler or is scheduled to be
* executed.
*
* @return the found IRequestHandler or {@link Optional#empty()}
*/
@SuppressWarnings("unchecked")
public <T extends IRequestHandler> Optional<T> find(final Class<T> type)
{
if (type == null)
{
return Optional.empty();
}
IRequestHandler result = getActiveRequestHandler();
if (type.isInstance(result))
{
return (Optional<T>)Optional.of(result);
}
result = getRequestHandlerScheduledAfterCurrent();
if (type.isInstance(result))
{
return (Optional<T>)Optional.of(result);
}
return Optional.empty();
}
/**
* Adapts {@link RequestHandlerExecutor} to this {@link RequestCycle}
*
* @author Igor Vaynberg
*/
private class HandlerExecutor extends RequestHandlerExecutor
{
@Override
protected void respond(IRequestHandler handler)
{
Response originalResponse = getResponse();
try
{
handler.respond(RequestCycle.this);
}
finally
{
setResponse(originalResponse);
}
}
@Override
protected void detach(IRequestHandler handler)
{
handler.detach(RequestCycle.this);
}
}
}