forked from eclipse-ee4j/jersey
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ServerRuntime.java
1282 lines (1105 loc) · 54.5 KB
/
ServerRuntime.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
/*
* Copyright (c) 2012, 2022 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package org.glassfish.jersey.server;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.ServiceUnavailableException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.CompletionCallback;
import javax.ws.rs.container.ConnectionCallback;
import javax.ws.rs.container.TimeoutHandler;
import javax.ws.rs.core.Configuration;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.inject.Provider;
import org.glassfish.jersey.internal.guava.Preconditions;
import org.glassfish.jersey.internal.inject.InjectionManager;
import org.glassfish.jersey.internal.inject.Injections;
import org.glassfish.jersey.internal.inject.Providers;
import org.glassfish.jersey.internal.util.Closure;
import org.glassfish.jersey.internal.util.Producer;
import org.glassfish.jersey.internal.util.PropertiesHelper;
import org.glassfish.jersey.internal.util.collection.Ref;
import org.glassfish.jersey.internal.util.collection.Refs;
import org.glassfish.jersey.internal.util.collection.Value;
import org.glassfish.jersey.message.internal.HeaderValueException;
import org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException;
import org.glassfish.jersey.message.internal.OutboundJaxrsResponse;
import org.glassfish.jersey.message.internal.OutboundMessageContext;
import org.glassfish.jersey.message.internal.TracingLogger;
import org.glassfish.jersey.process.internal.RequestContext;
import org.glassfish.jersey.process.internal.RequestScope;
import org.glassfish.jersey.process.internal.Stage;
import org.glassfish.jersey.process.internal.Stages;
import org.glassfish.jersey.server.internal.LocalizationMessages;
import org.glassfish.jersey.server.internal.ProcessingProviders;
import org.glassfish.jersey.server.internal.ServerTraceEvent;
import org.glassfish.jersey.server.internal.monitoring.EmptyRequestEventBuilder;
import org.glassfish.jersey.server.internal.monitoring.RequestEventBuilder;
import org.glassfish.jersey.server.internal.monitoring.RequestEventImpl;
import org.glassfish.jersey.server.internal.process.Endpoint;
import org.glassfish.jersey.server.internal.process.MappableException;
import org.glassfish.jersey.server.internal.process.RequestProcessingContext;
import org.glassfish.jersey.server.internal.routing.UriRoutingContext;
import org.glassfish.jersey.server.monitoring.ApplicationEventListener;
import org.glassfish.jersey.server.monitoring.RequestEvent;
import org.glassfish.jersey.server.monitoring.RequestEventListener;
import org.glassfish.jersey.server.spi.ContainerResponseWriter;
import org.glassfish.jersey.server.spi.ExternalRequestContext;
import org.glassfish.jersey.server.spi.ExternalRequestScope;
import org.glassfish.jersey.server.spi.ResponseErrorMapper;
import org.glassfish.jersey.spi.ExceptionMappers;
import static org.glassfish.jersey.server.AsyncContext.State.COMPLETED;
import static org.glassfish.jersey.server.AsyncContext.State.RESUMED;
import static org.glassfish.jersey.server.AsyncContext.State.RUNNING;
import static org.glassfish.jersey.server.AsyncContext.State.SUSPENDED;
/**
* Server-side request processing runtime.
*
* @author Marek Potociar
*/
public class ServerRuntime {
private final Stage<RequestProcessingContext> requestProcessingRoot;
private final ProcessingProviders processingProviders;
private final InjectionManager injectionManager;
private final ScheduledExecutorService backgroundScheduler;
private final Provider<ExecutorService> managedAsyncExecutor;
private final RequestScope requestScope;
private final ExceptionMappers exceptionMappers;
private final ApplicationEventListener applicationEventListener;
private final Configuration configuration;
private final ExternalRequestScope externalRequestScope;
private final TracingConfig tracingConfig;
private final TracingLogger.Level tracingThreshold;
private final boolean processResponseErrors;
/** Do not resolve relative URIs in the {@code Location} header */
private final boolean disableLocationHeaderRelativeUriResolution;
/** Resolve relative URIs according to RFC7231 (not JAX-RS 2.0 compliant */
private final boolean rfc7231LocationHeaderRelativeUriResolution;
static ServerRuntime createServerRuntime(
InjectionManager injectionManager,
ServerBootstrapBag bootstrapBag,
Stage<RequestProcessingContext> processingRoot,
ApplicationEventListener eventListener,
ProcessingProviders processingProviders) {
ScheduledExecutorService scheduledExecutorServiceSupplier =
injectionManager.getInstance(ScheduledExecutorService.class, BackgroundSchedulerLiteral.INSTANCE);
Provider<ExecutorService> asyncExecutorServiceSupplier =
() -> injectionManager.getInstance(ExecutorService.class, ManagedAsyncExecutorLiteral.INSTANCE);
return new ServerRuntime(
processingRoot,
processingProviders,
injectionManager,
scheduledExecutorServiceSupplier,
asyncExecutorServiceSupplier,
bootstrapBag.getRequestScope(),
bootstrapBag.getExceptionMappers(),
eventListener,
injectionManager.getInstance(ExternalRequestScope.class),
bootstrapBag.getConfiguration());
}
private ServerRuntime(final Stage<RequestProcessingContext> requestProcessingRoot,
final ProcessingProviders processingProviders,
final InjectionManager injectionManager,
final ScheduledExecutorService backgroundScheduler,
final Provider<ExecutorService> managedAsyncExecutorProvider,
final RequestScope requestScope,
final ExceptionMappers exceptionMappers,
final ApplicationEventListener applicationEventListener,
final ExternalRequestScope externalScope,
final Configuration configuration) {
this.requestProcessingRoot = requestProcessingRoot;
this.processingProviders = processingProviders;
this.injectionManager = injectionManager;
this.backgroundScheduler = backgroundScheduler;
this.managedAsyncExecutor = managedAsyncExecutorProvider;
this.requestScope = requestScope;
this.exceptionMappers = exceptionMappers;
this.applicationEventListener = applicationEventListener;
this.externalRequestScope = externalScope;
this.configuration = configuration;
this.tracingConfig = TracingUtils.getTracingConfig(configuration);
this.tracingThreshold = TracingUtils.getTracingThreshold(configuration);
this.processResponseErrors = PropertiesHelper.isProperty(
configuration.getProperty(ServerProperties.PROCESSING_RESPONSE_ERRORS_ENABLED));
this.disableLocationHeaderRelativeUriResolution = ServerProperties.getValue(configuration.getProperties(),
ServerProperties.LOCATION_HEADER_RELATIVE_URI_RESOLUTION_DISABLED,
Boolean.FALSE, Boolean.class);
this.rfc7231LocationHeaderRelativeUriResolution = ServerProperties.getValue(configuration.getProperties(),
ServerProperties.LOCATION_HEADER_RELATIVE_URI_RESOLUTION_RFC7231,
Boolean.FALSE, Boolean.class);
}
/**
* Process a container request.
*
* @param request container request to be processed.
*/
public void process(final ContainerRequest request) {
TracingUtils.initTracingSupport(tracingConfig, tracingThreshold, request);
TracingUtils.logStart(request);
final UriRoutingContext routingContext = request.getUriRoutingContext();
RequestEventBuilder monitoringEventBuilder = EmptyRequestEventBuilder.INSTANCE;
RequestEventListener monitoringEventListener = null;
if (applicationEventListener != null) {
monitoringEventBuilder = new RequestEventImpl.Builder()
.setContainerRequest(request)
.setExtendedUriInfo(routingContext);
monitoringEventListener = applicationEventListener.onRequest(
monitoringEventBuilder.build(RequestEvent.Type.START));
}
request.setProcessingProviders(processingProviders);
final RequestProcessingContext context = new RequestProcessingContext(injectionManager,
request,
routingContext,
monitoringEventBuilder,
monitoringEventListener);
request.checkState();
final Responder responder = new Responder(context, ServerRuntime.this);
final RequestContext requestScopeInstance = requestScope.createContext();
final AsyncResponderHolder asyncResponderHolder =
new AsyncResponderHolder(responder, externalRequestScope,
requestScopeInstance, externalRequestScope.open(injectionManager));
context.initAsyncContext(asyncResponderHolder);
try {
requestScope.runInScope(requestScopeInstance, new Runnable() {
@Override
public void run() {
try {
// set base URI into response builder thread-local variable
// for later resolving of relative location URIs
if (!disableLocationHeaderRelativeUriResolution) {
final URI uriToUse =
rfc7231LocationHeaderRelativeUriResolution ? request.getRequestUri() : request.getBaseUri();
OutboundJaxrsResponse.Builder.setBaseUri(uriToUse);
}
final Ref<Endpoint> endpointRef = Refs.emptyRef();
final RequestProcessingContext data = Stages.process(context, requestProcessingRoot, endpointRef);
final Endpoint endpoint = endpointRef.get();
if (endpoint == null) {
// not found
throw new NotFoundException();
}
final ContainerResponse response = endpoint.apply(data);
if (!asyncResponderHolder.isAsync()) {
responder.process(response);
} else {
externalRequestScope.suspend(asyncResponderHolder.externalContext, injectionManager);
}
} catch (final Throwable throwable) {
responder.process(throwable);
} finally {
asyncResponderHolder.release();
// clear base URI from the thread
OutboundJaxrsResponse.Builder.clearBaseUri();
}
}
});
} catch (RuntimeException illegalStateException) {
if (!IllegalStateException.class.isInstance(illegalStateException.getCause()) || !injectionManager.isShutdown()) {
// consume the IllegalStateException: InjectionManager has been closed.
throw illegalStateException;
}
}
}
/**
* Get the Jersey server runtime background scheduler.
*
* @return server runtime background scheduler.
* @see BackgroundScheduler
*/
ScheduledExecutorService getBackgroundScheduler() {
return backgroundScheduler;
}
/**
* Ensure that the value a {@value HttpHeaders#LOCATION} header is an absolute URI, if present among headers.
* <p/>
* Relative URI value will be made absolute using a base request URI.
*
* @param location location URI; value of the HTTP {@value HttpHeaders#LOCATION} response header.
* @param headers mutable map of response headers.
* @param request container request.
* @param incompatible if set to {@code true}, uri will be resolved against the request uri, not the base uri;
* this is correct against RFC7231, but does violate the JAX-RS 2.0 specs
*/
private static void ensureAbsolute(final URI location, final MultivaluedMap<String, Object> headers,
final ContainerRequest request, final boolean incompatible) {
if (location == null || location.isAbsolute()) {
return;
}
// according to RFC7231 (HTTP/1.1), this field can contain one single URI reference
final URI uri = incompatible ? request.getRequestUri() : request.getBaseUri();
headers.putSingle(HttpHeaders.LOCATION, uri.resolve(location));
}
private static class AsyncResponderHolder implements Value<AsyncContext> {
private final Responder responder;
private final ExternalRequestScope externalScope;
private final RequestContext requestContext;
private final ExternalRequestContext<?> externalContext;
private volatile AsyncResponder asyncResponder;
private AsyncResponderHolder(final Responder responder,
final ExternalRequestScope externalRequestScope,
final RequestContext requestContext,
final ExternalRequestContext<?> externalContext) {
this.responder = responder;
this.externalScope = externalRequestScope;
this.requestContext = requestContext;
this.externalContext = externalContext;
}
@Override
public AsyncContext get() {
final AsyncResponder ar = new AsyncResponder(responder, requestContext, externalScope, externalContext);
asyncResponder = ar;
return ar;
}
public boolean isAsync() {
final AsyncResponder ar = asyncResponder;
return ar != null && !ar.isRunning();
}
public void release() {
if (asyncResponder == null) {
requestContext.release();
}
}
}
private static class Responder {
private static final Logger LOGGER = Logger.getLogger(Responder.class.getName());
private final RequestProcessingContext processingContext;
private final ServerRuntime runtime;
private final CompletionCallbackRunner completionCallbackRunner = new CompletionCallbackRunner();
private final ConnectionCallbackRunner connectionCallbackRunner = new ConnectionCallbackRunner();
private final TracingLogger tracingLogger;
public Responder(final RequestProcessingContext processingContext, final ServerRuntime runtime) {
this.processingContext = processingContext;
this.runtime = runtime;
this.tracingLogger = TracingLogger.getInstance(processingContext.request());
}
public void process(ContainerResponse response) {
processingContext.monitoringEventBuilder().setContainerResponse(response);
response = processResponse(response);
release(response);
}
private ContainerResponse processResponse(ContainerResponse response) {
final Stage<ContainerResponse> respondingRoot = processingContext.createRespondingRoot();
if (respondingRoot != null) {
response = Stages.process(response, respondingRoot);
}
writeResponse(response);
// no-exception zone
// the methods below are guaranteed to not throw any exceptions
completionCallbackRunner.onComplete(null);
return response;
}
/**
* Process {@code throwable} by using exception mappers and generating the mapped
* response if possible.
* <p>
* Note about logging:
* <ul>
* <li>
* we do not log exceptions that are mapped by ExceptionMappers.
* </li><li>
* All other exceptions are logged: WebApplicationExceptions with entities,
* exceptions that were unsuccessfully mapped
* </li>
* </ul>
* </p>
*
* @param throwable Exception to be processed.
*/
public void process(final Throwable throwable) {
final ContainerRequest request = processingContext.request();
processingContext.monitoringEventBuilder().setException(throwable, RequestEvent.ExceptionCause.ORIGINAL);
processingContext.triggerEvent(RequestEvent.Type.ON_EXCEPTION);
ContainerResponse response = null;
try {
final Response exceptionResponse = mapException(throwable);
try {
try {
response = convertResponse(exceptionResponse);
if (!runtime.disableLocationHeaderRelativeUriResolution) {
ensureAbsolute(response.getLocation(), response.getHeaders(), request,
runtime.rfc7231LocationHeaderRelativeUriResolution);
}
processingContext.monitoringEventBuilder().setContainerResponse(response)
.setResponseSuccessfullyMapped(true);
} finally {
processingContext.triggerEvent(RequestEvent.Type.EXCEPTION_MAPPING_FINISHED);
}
processResponse(response);
} catch (final Throwable respError) {
LOGGER.log(Level.SEVERE, LocalizationMessages.ERROR_PROCESSING_RESPONSE_FROM_ALREADY_MAPPED_EXCEPTION());
processingContext.monitoringEventBuilder()
.setException(respError, RequestEvent.ExceptionCause.MAPPED_RESPONSE);
processingContext.triggerEvent(RequestEvent.Type.ON_EXCEPTION);
throw respError;
}
} catch (final Throwable responseError) {
if (throwable != responseError
&& !(throwable instanceof MappableException && throwable.getCause() == responseError)) {
LOGGER.log(Level.FINE, LocalizationMessages.ERROR_EXCEPTION_MAPPING_ORIGINAL_EXCEPTION(), throwable);
}
if (!processResponseError(responseError)) {
// Pass the exception to the container.
LOGGER.log(Level.FINE, LocalizationMessages.ERROR_EXCEPTION_MAPPING_THROWN_TO_CONTAINER(), responseError);
try {
request.getResponseWriter().failure(responseError);
} finally {
completionCallbackRunner.onComplete(responseError);
}
}
} finally {
release(response);
}
}
/**
* If {@value org.glassfish.jersey.server.ServerProperties#PROCESSING_RESPONSE_ERRORS_ENABLED} is set to true then try to
* handle errors raised during response processing.
*
* @param responseError a throwable that occurred during response processing.
* @return {@code true} if the given response error has been processed, {@code false} otherwise.
*/
private boolean processResponseError(final Throwable responseError) {
boolean processed = false;
if (runtime.processResponseErrors) {
// Try to obtain response from response error mapper.
final Iterable<ResponseErrorMapper> mappers = Providers.getAllProviders(runtime.injectionManager,
ResponseErrorMapper.class);
ContainerResponse processedResponse = null;
try {
Response processedError = null;
for (final ResponseErrorMapper mapper : mappers) {
processedError = mapper.toResponse(responseError);
if (processedError != null) {
break;
}
}
if (processedError != null) {
processedResponse =
processResponse(new ContainerResponse(processingContext.request(), processedError));
processed = true;
}
} catch (final Throwable throwable) {
LOGGER.log(Level.FINE, LocalizationMessages.ERROR_EXCEPTION_MAPPING_PROCESSED_RESPONSE_ERROR(), throwable);
} finally {
if (processedResponse != null) {
release(processedResponse);
}
}
}
return processed;
}
private ContainerResponse convertResponse(final Response exceptionResponse) {
final ContainerResponse containerResponse = new ContainerResponse(processingContext.request(), exceptionResponse);
containerResponse.setMappedFromException(true);
return containerResponse;
}
@SuppressWarnings("unchecked")
private Response mapException(final Throwable originalThrowable) throws Throwable {
LOGGER.log(Level.FINER, LocalizationMessages.EXCEPTION_MAPPING_START(), originalThrowable);
final ThrowableWrap wrap = new ThrowableWrap(originalThrowable);
wrap.tryMappableException();
do {
final Throwable throwable = wrap.getCurrent();
if (wrap.isInMappable() || throwable instanceof WebApplicationException) {
// in case ServerProperties.PROCESSING_RESPONSE_ERRORS_ENABLED is true, allow
// wrapped MessageBodyProviderNotFoundException to propagate
if (runtime.processResponseErrors && throwable instanceof InternalServerErrorException
&& throwable.getCause() instanceof MessageBodyProviderNotFoundException) {
throw throwable;
}
Response waeResponse = null;
if (throwable instanceof WebApplicationException) {
final WebApplicationException webApplicationException = (WebApplicationException) throwable;
// set mapped throwable
processingContext.routingContext().setMappedThrowable(throwable);
waeResponse = webApplicationException.getResponse();
if (waeResponse.hasEntity()) {
LOGGER.log(Level.FINE, LocalizationMessages
.EXCEPTION_MAPPING_WAE_ENTITY(waeResponse.getStatus()), throwable);
return waeResponse;
}
}
final long timestamp = tracingLogger.timestamp(ServerTraceEvent.EXCEPTION_MAPPING);
final ExceptionMapper mapper = runtime.exceptionMappers.findMapping(throwable);
if (mapper != null) {
processingContext.monitoringEventBuilder().setExceptionMapper(mapper);
processingContext.triggerEvent(RequestEvent.Type.EXCEPTION_MAPPER_FOUND);
try {
final Response mappedResponse = mapper.toResponse(throwable);
if (tracingLogger.isLogEnabled(ServerTraceEvent.EXCEPTION_MAPPING)) {
tracingLogger.logDuration(ServerTraceEvent.EXCEPTION_MAPPING,
timestamp, mapper, throwable, throwable.getLocalizedMessage(),
mappedResponse != null ? mappedResponse.getStatusInfo() : "-no-response-");
}
// set mapped throwable
processingContext.routingContext().setMappedThrowable(throwable);
if (mappedResponse != null) {
// response successfully mapped
if (LOGGER.isLoggable(Level.FINER)) {
final String message = String.format(
"Exception '%s' has been mapped by '%s' to response '%s' (%s:%s).",
throwable.getLocalizedMessage(),
mapper.getClass().getName(),
mappedResponse.getStatusInfo().getReasonPhrase(),
mappedResponse.getStatusInfo().getStatusCode(),
mappedResponse.getStatusInfo().getFamily());
LOGGER.log(Level.FINER, message);
}
return mappedResponse;
} else {
return Response.noContent().build();
}
} catch (final Throwable mapperThrowable) {
// spec: If the exception mapping provider throws an exception while creating a Response
// then return a server error (status code 500) response to the client.
LOGGER.log(Level.SEVERE, LocalizationMessages.EXCEPTION_MAPPER_THROWS_EXCEPTION(mapper.getClass()),
mapperThrowable);
LOGGER.log(Level.SEVERE, LocalizationMessages.EXCEPTION_MAPPER_FAILED_FOR_EXCEPTION(), throwable);
return Response.serverError().build();
}
}
if (waeResponse != null) {
LOGGER.log(Level.FINE, LocalizationMessages
.EXCEPTION_MAPPING_WAE_NO_ENTITY(waeResponse.getStatus()), throwable);
return waeResponse;
}
}
// internal mapping
if (throwable instanceof HeaderValueException) {
if (((HeaderValueException) throwable).getContext() == HeaderValueException.Context.INBOUND) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
}
if (!wrap.isInMappable() || !wrap.isWrapped()) {
// user failures (thrown from Resource methods or provider methods)
// spec: Unchecked exceptions and errors that have not been mapped MUST be re-thrown and allowed to
// propagate to the underlying container.
// not logged on this level.
throw wrap.getWrappedOrCurrent();
}
} while (wrap.unwrap() != null);
// jersey failures (not thrown from Resource methods or provider methods) -> rethrow
throw originalThrowable;
}
private ContainerResponse writeResponse(final ContainerResponse response) {
final ContainerRequest request = processingContext.request();
final ContainerResponseWriter writer = request.getResponseWriter();
if (!runtime.disableLocationHeaderRelativeUriResolution) {
ServerRuntime.ensureAbsolute(response.getLocation(), response.getHeaders(), response.getRequestContext(),
runtime.rfc7231LocationHeaderRelativeUriResolution);
}
if (!response.hasEntity()) {
tracingLogger.log(ServerTraceEvent.FINISHED, response.getStatusInfo());
tracingLogger.flush(response.getHeaders());
writer.writeResponseStatusAndHeaders(0, response);
setWrittenResponse(response);
return response;
}
final Object entity = response.getEntity();
boolean skipFinally = false;
final boolean isHead = request.getMethod().equals(HttpMethod.HEAD);
try {
response.setStreamProvider(new OutboundMessageContext.StreamProvider() {
@Override
public OutputStream getOutputStream(final int contentLength) throws IOException {
if (!runtime.disableLocationHeaderRelativeUriResolution) {
ServerRuntime.ensureAbsolute(response.getLocation(), response.getHeaders(),
response.getRequestContext(), runtime.rfc7231LocationHeaderRelativeUriResolution);
}
final OutputStream outputStream = writer.writeResponseStatusAndHeaders(contentLength, response);
return isHead ? null : outputStream;
}
});
if ((writer.enableResponseBuffering() || isHead) && !response.isChunked()) {
response.enableBuffering(runtime.configuration);
}
try {
response.setEntityStream(request.getWorkers().writeTo(
entity,
entity.getClass(),
response.getEntityType(),
response.getEntityAnnotations(),
response.getMediaType(),
response.getHeaders(),
request.getPropertiesDelegate(),
response.getEntityStream(),
request.getWriterInterceptors()));
} catch (final MappableException mpe) {
if (mpe.getCause() instanceof IOException) {
connectionCallbackRunner.onDisconnect(processingContext.asyncContext());
}
throw mpe;
}
tracingLogger.log(ServerTraceEvent.FINISHED, response.getStatusInfo());
tracingLogger.flush(response.getHeaders());
setWrittenResponse(response);
} catch (final Throwable ex) {
if (response.isCommitted()) {
/**
* We're done with processing here. There's nothing we can do about the exception so
* let's just log it.
*/
LOGGER.log(Level.SEVERE, LocalizationMessages.ERROR_WRITING_RESPONSE_ENTITY(), ex);
} else {
skipFinally = true;
if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
} else {
throw new MappableException(ex);
}
}
} finally {
if (!skipFinally) {
boolean close = !response.isChunked();
if (response.isChunked()) {
try {
response.commitStream();
} catch (final Exception e) {
LOGGER.log(Level.SEVERE, LocalizationMessages.ERROR_COMMITTING_OUTPUT_STREAM(), e);
close = true;
}
final ChunkedOutput chunked = (ChunkedOutput) entity;
try {
chunked.setContext(
runtime.requestScope,
runtime.requestScope.referenceCurrent(),
request,
response,
connectionCallbackRunner);
} catch (final IOException ex) {
LOGGER.log(Level.SEVERE, LocalizationMessages.ERROR_WRITING_RESPONSE_ENTITY_CHUNK(), ex);
close = true;
}
// suspend the writer indefinitely (passing null timeout handler is ok in such case) if the output is not
// already closed.
// TODO what to do if we detect that the writer has already been suspended? override the timeout value?
if (!chunked.isClosed()
&& !writer.suspend(AsyncResponder.NO_TIMEOUT, TimeUnit.SECONDS, null)) {
LOGGER.fine(LocalizationMessages.ERROR_SUSPENDING_CHUNKED_OUTPUT_RESPONSE());
}
}
if (close) {
try {
// the response must be closed here instead of just flushed or committed. Some
// output streams writes out bytes only on close (for example GZipOutputStream).
response.close();
} catch (final Exception e) {
LOGGER.log(Level.SEVERE, LocalizationMessages.ERROR_CLOSING_COMMIT_OUTPUT_STREAM(), e);
}
}
}
}
return response;
}
private void setWrittenResponse(final ContainerResponse response) {
processingContext.monitoringEventBuilder()
.setContainerResponse(response)
.setSuccess(response.getStatus() < Response.Status.BAD_REQUEST.getStatusCode())
.setResponseWritten(true);
}
private void release(final ContainerResponse responseContext) {
try {
processingContext.closeableService().close();
// Commit the container response writer if not in chunked mode
// responseContext may be null in case the request processing was cancelled.
if (responseContext != null && !responseContext.isChunked()) {
// responseContext.commitStream();
responseContext.close();
}
} catch (final Throwable throwable) {
LOGGER.log(Level.WARNING, LocalizationMessages.RELEASING_REQUEST_PROCESSING_RESOURCES_FAILED(), throwable);
} finally {
runtime.externalRequestScope.close();
processingContext.triggerEvent(RequestEvent.Type.FINISHED);
}
}
}
private static class AsyncResponder implements AsyncContext, ContainerResponseWriter.TimeoutHandler, CompletionCallback {
private static final Logger LOGGER = Logger.getLogger(AsyncResponder.class.getName());
private static final TimeoutHandler DEFAULT_TIMEOUT_HANDLER = new TimeoutHandler() {
@Override
public void handleTimeout(final AsyncResponse asyncResponse) {
throw new ServiceUnavailableException();
}
};
private final Object stateLock = new Object();
private State state = RUNNING;
private boolean cancelled = false;
private final Responder responder;
// TODO this instance should be released once async invocation is finished.
private final RequestContext requestContext;
private final ExternalRequestContext<?> foreignScopeInstance;
private final ExternalRequestScope requestScopeListener;
private volatile TimeoutHandler timeoutHandler = DEFAULT_TIMEOUT_HANDLER;
private final List<AbstractCallbackRunner<?>> callbackRunners;
public AsyncResponder(final Responder responder,
final RequestContext requestContext,
final ExternalRequestScope requestScopeListener,
final ExternalRequestContext<?> foreignScopeInstance) {
this.responder = responder;
this.requestContext = requestContext;
this.foreignScopeInstance = foreignScopeInstance;
this.requestScopeListener = requestScopeListener;
this.callbackRunners = Collections.unmodifiableList(Arrays.asList(
responder.completionCallbackRunner, responder.connectionCallbackRunner));
responder.completionCallbackRunner.register(this);
}
@Override
public void onTimeout(final ContainerResponseWriter responseWriter) {
final TimeoutHandler handler = timeoutHandler;
try {
synchronized (stateLock) {
if (state == SUSPENDED) {
handler.handleTimeout(this);
}
}
} catch (final Throwable throwable) {
resume(throwable);
}
}
@Override
public void onComplete(final Throwable throwable) {
synchronized (stateLock) {
state = COMPLETED;
}
}
@Override
public void invokeManaged(final Producer<Response> producer) {
responder.runtime.managedAsyncExecutor.get().submit(new Runnable() {
@Override
public void run() {
responder.runtime.requestScope.runInScope(requestContext, new Runnable() {
@Override
public void run() {
try {
requestScopeListener.resume(foreignScopeInstance, responder.runtime.injectionManager);
final Response response = producer.call();
if (response != null) {
resume(response);
}
} catch (final Throwable t) {
resume(t);
}
}
});
}
});
}
@Override
public boolean suspend() {
synchronized (stateLock) {
if (state == RUNNING) {
if (responder.processingContext.request().getResponseWriter().suspend(
AsyncResponse.NO_TIMEOUT, TimeUnit.SECONDS, this)) {
state = SUSPENDED;
return true;
}
}
}
return false;
}
@Override
public boolean resume(final Object response) {
return resume(new Runnable() {
@Override
public void run() {
try {
requestScopeListener.resume(foreignScopeInstance, responder.runtime.injectionManager);
final Response jaxrsResponse =
(response instanceof Response) ? (Response) response : Response.ok(response).build();
if (!responder.runtime.disableLocationHeaderRelativeUriResolution) {
ServerRuntime.ensureAbsolute(jaxrsResponse.getLocation(), jaxrsResponse.getHeaders(),
responder.processingContext.request(),
responder.runtime.rfc7231LocationHeaderRelativeUriResolution);
}
responder.process(new ContainerResponse(responder.processingContext.request(), jaxrsResponse));
} catch (final Throwable t) {
responder.process(t);
}
}
});
}
@Override
public boolean resume(final Throwable error) {
return resume(new Runnable() {
@Override
public void run() {
try {
requestScopeListener.resume(foreignScopeInstance, responder.runtime.injectionManager);
responder.process(new MappableException(error));
} catch (final Throwable error) {
// Ignore the exception - already resumed but may be rethrown by ContainerResponseWriter#failure.
}
}
});
}
private boolean resume(final Runnable handler) {
synchronized (stateLock) {
if (state != SUSPENDED) {
return false;
}
state = RESUMED;
}
try {
responder.runtime.requestScope.runInScope(requestContext, handler);
} finally {
requestContext.release();
}
return true;
}
@Override
public boolean cancel() {
return cancel(new Value<Response>() {
@Override
public Response get() {
return Response.status(Response.Status.SERVICE_UNAVAILABLE).build();
}
});
}
@Override
public boolean cancel(final int retryAfter) {
return cancel(new Value<Response>() {
@Override
public Response get() {
return Response
.status(Response.Status.SERVICE_UNAVAILABLE)
.header(HttpHeaders.RETRY_AFTER, retryAfter)
.build();
}
});
}
@Override
public boolean cancel(final Date retryAfter) {
return cancel(new Value<Response>() {
@Override
public Response get() {
return Response
.status(Response.Status.SERVICE_UNAVAILABLE)
.header(HttpHeaders.RETRY_AFTER, retryAfter)
.build();
}
});
}
private boolean cancel(final Value<Response> responseValue) {
synchronized (stateLock) {
if (cancelled) {
return true;
}
if (state != SUSPENDED) {
return false;
}
state = RESUMED;
cancelled = true;
}
responder.runtime.requestScope.runInScope(requestContext, new Runnable() {
@Override
public void run() {
try {
requestScopeListener.resume(foreignScopeInstance, responder.runtime.injectionManager);
final Response response = responseValue.get();
responder.process(new ContainerResponse(responder.processingContext.request(), response));
} catch (final Throwable t) {
responder.process(t);
}
}
});
return true;
}
public boolean isRunning() {
synchronized (stateLock) {
return state == RUNNING;
}
}
@Override
public boolean isSuspended() {
synchronized (stateLock) {
return state == SUSPENDED;
}
}
@Override
public boolean isCancelled() {
synchronized (stateLock) {
return cancelled;
}
}
@Override
public boolean isDone() {
synchronized (stateLock) {
return state == COMPLETED;
}
}