/
SynchronousDispatcher.java
executable file
·548 lines (509 loc) · 18.4 KB
/
SynchronousDispatcher.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
package org.jboss.resteasy.core;
import org.jboss.resteasy.core.interception.PreMatchContainerRequestContext;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ResourceContext;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Providers;
import org.jboss.resteasy.plugins.server.servlet.Cleanable;
import org.jboss.resteasy.plugins.server.servlet.Cleanables;
import org.jboss.resteasy.resteasy_jaxrs.i18n.LogMessages;
import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages;
import org.jboss.resteasy.specimpl.BuiltResponse;
import org.jboss.resteasy.specimpl.RequestImpl;
import org.jboss.resteasy.spi.Failure;
import org.jboss.resteasy.spi.HttpRequest;
import org.jboss.resteasy.spi.HttpRequestPreprocessor;
import org.jboss.resteasy.spi.HttpResponse;
import org.jboss.resteasy.spi.InternalDispatcher;
import org.jboss.resteasy.spi.InternalServerErrorException;
import org.jboss.resteasy.spi.Registry;
import org.jboss.resteasy.spi.ResteasyAsynchronousContext;
import org.jboss.resteasy.spi.ResteasyConfiguration;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.jboss.resteasy.spi.UnhandledException;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
@SuppressWarnings("unchecked")
public class SynchronousDispatcher implements Dispatcher
{
protected ResteasyProviderFactory providerFactory;
protected Registry registry;
protected List<HttpRequestPreprocessor> requestPreprocessors = new ArrayList<HttpRequestPreprocessor>();
protected Map<Class, Object> defaultContextObjects = new HashMap<Class, Object>();
protected Set<String> unwrappedExceptions = new HashSet<String>();
protected boolean bufferExceptionEntityRead = false;
protected boolean bufferExceptionEntity = true;
public SynchronousDispatcher(final ResteasyProviderFactory providerFactory)
{
this.providerFactory = providerFactory;
this.registry = new ResourceMethodRegistry(providerFactory);
defaultContextObjects.put(Providers.class, providerFactory);
defaultContextObjects.put(Registry.class, registry);
defaultContextObjects.put(Dispatcher.class, this);
defaultContextObjects.put(InternalDispatcher.class, InternalDispatcher.getInstance());
}
public SynchronousDispatcher(final ResteasyProviderFactory providerFactory, final ResourceMethodRegistry registry)
{
this(providerFactory);
this.registry = registry;
defaultContextObjects.put(Registry.class, registry);
}
public ResteasyProviderFactory getProviderFactory()
{
return providerFactory;
}
public Registry getRegistry()
{
return registry;
}
public Map<Class, Object> getDefaultContextObjects()
{
return defaultContextObjects;
}
public Set<String> getUnwrappedExceptions()
{
return unwrappedExceptions;
}
public Response preprocess(HttpRequest request)
{
Response aborted = null;
try
{
for (HttpRequestPreprocessor preprocessor : this.requestPreprocessors)
{
preprocessor.preProcess(request);
}
ContainerRequestFilter[] requestFilters = providerFactory.getContainerRequestFilterRegistry().preMatch();
// FIXME: support async
PreMatchContainerRequestContext requestContext = new PreMatchContainerRequestContext(request, requestFilters, null);
aborted = requestContext.filter();
}
catch (Exception e)
{
//logger.error("Failed in preprocess, mapping exception", e);
aborted = new ExceptionHandler(providerFactory, unwrappedExceptions).handleException(request, e);
}
return aborted;
}
/**
* Call pre-process ContainerRequestFilters.
*
* @param request http request
* @param response http response
* @param continuation runnable
*/
protected void preprocess(HttpRequest request, HttpResponse response, Runnable continuation)
{
Response aborted = null;
PreMatchContainerRequestContext requestContext = null;
try
{
for (HttpRequestPreprocessor preprocessor : this.requestPreprocessors)
{
preprocessor.preProcess(request);
}
ContainerRequestFilter[] requestFilters = providerFactory.getContainerRequestFilterRegistry().preMatch();
requestContext = new PreMatchContainerRequestContext(request, requestFilters,
() -> {
continuation.run();
return null;
});
aborted = requestContext.filter();
}
catch (Exception e)
{
//logger.error("Failed in preprocess, mapping exception", e);
// we only want to catch exceptions happening in the filters, not in the continuation
if(requestContext == null || !requestContext.startedContinuation())
{
writeException(request, response, e, t -> {});
return;
}
else
{
rethrow(e);
}
}
if (aborted != null)
{
writeResponse(request, response, aborted);
return;
}
}
public static <T extends Throwable> void rethrow(Throwable t) throws T
{
throw (T)t;
}
@Deprecated
public void writeException(HttpRequest request, HttpResponse response, Throwable e)
{
writeException(request, response, e, t -> {});
}
public void writeException(HttpRequest request, HttpResponse response, Throwable e, Consumer<Throwable> onComplete)
{
if (!bufferExceptionEntityRead)
{
bufferExceptionEntityRead = true;
ResteasyConfiguration context = ResteasyProviderFactory.getContextData(ResteasyConfiguration.class);
if (context != null)
{
String s = context.getParameter("resteasy.buffer.exception.entity");
if (s != null)
{
bufferExceptionEntity = Boolean.parseBoolean(s);
}
}
}
if (response.isCommitted())
{
LogMessages.LOGGER.debug(Messages.MESSAGES.responseIsCommitted());
onComplete.accept(null);
return;
}
Response handledResponse = new ExceptionHandler(providerFactory, unwrappedExceptions).handleException(request, e);
if (handledResponse == null) throw new UnhandledException(e);
if (!bufferExceptionEntity)
{
response.getOutputHeaders().add("resteasy.buffer.exception.entity", "false");
}
try
{
ServerResponseWriter.writeNomapResponse(((BuiltResponse) handledResponse), request, response, providerFactory, onComplete);
}
catch (Exception e1)
{
throw new UnhandledException(e1);
}
}
public void invoke(HttpRequest request, HttpResponse response)
{
try
{
pushContextObjects(request, response);
preprocess(request, response, () -> {
ResourceInvoker invoker = null;
try
{
try
{
invoker = getInvoker(request);
}
catch (Exception exception)
{
//logger.error("getInvoker() failed mapping exception", exception);
writeException(request, response, exception, t -> {});
return;
}
invoke(request, response, invoker);
}
finally
{
// we're probably clearing it twice but still required
clearContextData();
}
});
}
finally
{
clearContextData();
}
}
/**
* Propagate NotFoundException. This is used for Filters.
*
* @param request http request
* @param response http response
*/
public void invokePropagateNotFound(HttpRequest request, HttpResponse response) throws NotFoundException
{
try
{
pushContextObjects(request, response);
preprocess(request, response, () -> {
ResourceInvoker invoker = null;
try
{
try
{
invoker = getInvoker(request);
}
catch (Exception failure)
{
if (failure instanceof NotFoundException)
{
throw ((NotFoundException) failure);
}
else
{
//logger.error("getInvoker() failed mapping exception", failure);
writeException(request, response, failure, t->{});
return;
}
}
invoke(request, response, invoker);
}
finally
{
// we're probably clearing it twice but still required
clearContextData();
}
});
}
finally
{
clearContextData();
}
}
public ResourceInvoker getInvoker(HttpRequest request)
throws Failure
{
LogMessages.LOGGER.pathInfo(request.getUri().getPath());
if (!request.isInitial())
{
throw new InternalServerErrorException(Messages.MESSAGES.isNotInitialRequest(request.getUri().getPath()));
}
ResourceInvoker invoker = registry.getResourceInvoker(request);
if (invoker == null)
{
throw new NotFoundException(Messages.MESSAGES.unableToFindJaxRsResource(request.getUri().getPath()));
}
return invoker;
}
public void pushContextObjects(final HttpRequest request, final HttpResponse response)
{
Map contextDataMap = ResteasyProviderFactory.getContextDataMap();
contextDataMap.put(HttpRequest.class, request);
contextDataMap.put(HttpResponse.class, response);
contextDataMap.put(HttpHeaders.class, request.getHttpHeaders());
contextDataMap.put(UriInfo.class, request.getUri());
contextDataMap.put(Request.class, new RequestImpl(request, response));
contextDataMap.put(ResteasyAsynchronousContext.class, request.getAsyncContext());
ResourceContext resourceContext = new ResourceContext()
{
@Override
public <T> T getResource(Class<T> resourceClass)
{
return providerFactory.injectedInstance(resourceClass, request, response);
}
@Override
public <T> T initResource(T resource)
{
providerFactory.injectProperties(resource, request, response);
return resource;
}
};
contextDataMap.put(ResourceContext.class, resourceContext);
contextDataMap.putAll(defaultContextObjects);
contextDataMap.put(Cleanables.class, new Cleanables());
contextDataMap.put(PostResourceMethodInvokers.class, new PostResourceMethodInvokers());
}
public Response internalInvocation(HttpRequest request, HttpResponse response, Object entity)
{
// be extra careful in the clean up process. Only pop if there was an
// equivalent push.
ResteasyProviderFactory.addContextDataLevel();
boolean pushedBody = false;
try
{
MessageBodyParameterInjector.pushBody(entity);
pushedBody = true;
ResourceInvoker invoker = getInvoker(request);
if (invoker != null)
{
pushContextObjects(request, response);
return execute(request, response, invoker);
}
// this should never happen, since getInvoker should throw an exception
// if invoker is null
return null;
}
finally
{
ResteasyProviderFactory.removeContextDataLevel();
if (pushedBody)
{
MessageBodyParameterInjector.popBody();
}
}
}
public void clearContextData()
{
Map<Class<?>, Object> map = ResteasyProviderFactory.getContextDataMap(false);
Cleanables cleanables = map != null ? (Cleanables) map.get(Cleanables.class) : null;
if (cleanables != null)
{
for (Iterator<Cleanable> it = cleanables.getCleanables().iterator(); it.hasNext(); )
{
try
{
it.next().clean();
}
catch(Exception e)
{
// Empty
}
}
ResteasyProviderFactory.clearContextData();
}
// just in case there were internalDispatches that need to be cleaned up
MessageBodyParameterInjector.clearBodies();
}
/**
* Return a response wither from an invoke or exception handling.
*
* @param request http request
* @param response http response
* @param invoker resource invoker
* @return response
*/
public Response execute(HttpRequest request, HttpResponse response, ResourceInvoker invoker)
{
Response jaxrsResponse = null;
try
{
jaxrsResponse = invoker.invoke(request, response);
if (request.getAsyncContext().isSuspended())
{
/**
* Callback by the initial calling thread. This callback will probably do nothing in an asynchronous environment
* but will be used to simulate AsynchronousResponse in vanilla Servlet containers that do not support
* asychronous HTTP.
*
*/
request.getAsyncContext().getAsyncResponse().initialRequestThreadFinished();
jaxrsResponse = null; // we're handing response asynchronously
}
}
catch (Exception e)
{
//logger.error("invoke() failed mapping exception", e);
jaxrsResponse = new ExceptionHandler(providerFactory, unwrappedExceptions).handleException(request, e);
if (jaxrsResponse == null) throw new UnhandledException(e);
}
return jaxrsResponse;
}
/**
* Invoke and write response.
*
* @param request http request
* @param response http response
* @param invoker resource invoker
*/
public void invoke(HttpRequest request, HttpResponse response, ResourceInvoker invoker)
{
Response jaxrsResponse = null;
try
{
jaxrsResponse = invoker.invoke(request, response);
if (request.getAsyncContext().isSuspended())
{
/**
* Callback by the initial calling thread. This callback will probably do nothing in an asynchronous environment
* but will be used to simulate AsynchronousResponse in vanilla Servlet containers that do not support
* asychronous HTTP.
*
*/
request.getAsyncContext().getAsyncResponse().initialRequestThreadFinished();
jaxrsResponse = null; // we're handing response asynchronously
}
}
catch (Exception e)
{
//logger.error("invoke() failed mapping exception", e);
invoker.getMethodStatisticsLogger().incFailureCnt();
writeException(request, response, e, t->{});
return;
}
if (jaxrsResponse != null) writeResponse(request, response, jaxrsResponse);
}
@Deprecated
public void asynchronousDelivery(HttpRequest request, HttpResponse response, Response jaxrsResponse) throws IOException
{
asynchronousDelivery(request, response, jaxrsResponse, t -> {});
}
public void asynchronousDelivery(HttpRequest request, HttpResponse response, Response jaxrsResponse, Consumer<Throwable> onComplete) throws IOException
{
if (jaxrsResponse == null) return;
try
{
pushContextObjects(request, response);
ServerResponseWriter.writeNomapResponse((BuiltResponse) jaxrsResponse, request, response, providerFactory, onComplete);
}
finally
{
ResteasyProviderFactory.removeContextDataLevel();
}
}
public void unhandledAsynchronousException(HttpResponse response, Throwable ex) {
LogMessages.LOGGER.unhandledAsynchronousException(ex);
// unhandled exceptions need to be processed as they can't be thrown back to the servlet container
if (!response.isCommitted()) {
try
{
response.reset();
response.sendError(500);
}
catch (IOException e)
{
}
}
}
@Deprecated
public void asynchronousExceptionDelivery(HttpRequest request, HttpResponse response, Throwable exception)
{
asynchronousExceptionDelivery(request, response, exception, t -> {});
}
public void asynchronousExceptionDelivery(HttpRequest request, HttpResponse response, Throwable exception, Consumer<Throwable> onComplete)
{
try
{
pushContextObjects(request, response);
writeException(request, response, exception, t -> {
if(t != null)
unhandledAsynchronousException(response, t);
onComplete.accept(null);
ResteasyProviderFactory.removeContextDataLevel();
});
}
catch (Throwable ex)
{
unhandledAsynchronousException(response, ex);
onComplete.accept(ex);
}
}
protected void writeResponse(HttpRequest request, HttpResponse response, Response jaxrsResponse)
{
try
{
ServerResponseWriter.writeNomapResponse((BuiltResponse) jaxrsResponse, request, response, providerFactory,
t -> {
if(t != null)
writeException(request, response, t, t2 -> {});
});
}
catch (Exception e)
{
//logger.error("writeResponse() failed mapping exception", e);
writeException(request, response, e, t -> {});
}
}
public void addHttpPreprocessor(HttpRequestPreprocessor httpPreprocessor)
{
requestPreprocessors.add(httpPreprocessor);
}
}