forked from resteasy/resteasy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ManualClosingApacheHttpClient43Engine.java
740 lines (656 loc) · 23.2 KB
/
ManualClosingApacheHttpClient43Engine.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
package org.jboss.resteasy.client.jaxrs.engines;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.Configurable;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.jboss.resteasy.client.jaxrs.i18n.LogMessages;
import org.jboss.resteasy.client.jaxrs.i18n.Messages;
import org.jboss.resteasy.client.jaxrs.internal.ClientInvocation;
import org.jboss.resteasy.client.jaxrs.internal.ClientResponse;
import org.jboss.resteasy.client.jaxrs.internal.FinalizedClientResponse;
import org.jboss.resteasy.core.ResourceCleaner;
import org.jboss.resteasy.spi.config.ConfigurationFactory;
import org.jboss.resteasy.util.CaseInsensitiveMap;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import jakarta.ws.rs.ProcessingException;
import jakarta.ws.rs.client.Invocation;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.management.ManagementFactory;
import java.lang.ref.Cleaner;
import java.nio.file.Path;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* An Apache HTTP engine for use with the new Builder Config style.
*/
public class ManualClosingApacheHttpClient43Engine implements ApacheHttpClientEngine
{
private static class CleanupAction implements Runnable {
private final AtomicBoolean closed;
private final CloseableHttpClient client;
private CleanupAction(final AtomicBoolean closed, final CloseableHttpClient client) {
this.closed = closed;
this.client = client;
}
@Override
public void run() {
if (closed.compareAndSet(false, true)) {
if (client != null) {
LogMessages.LOGGER.closingForYou(this.getClass());
try {
client.close();
} catch (Exception e) {
LogMessages.LOGGER.debugf(e, "Failed to close client %s", client);
}
}
}
}
}
static final String FILE_UPLOAD_IN_MEMORY_THRESHOLD_PROPERTY =
"org.jboss.resteasy.client.jaxrs.engines.fileUploadInMemoryThreshold";
/**
* Used to build temp file prefix.
*/
private static final String processId;
static
{
try {
processId = AccessController.doPrivileged(new PrivilegedExceptionAction<String>() {
@Override
public String run() throws Exception
{ return ManagementFactory.getRuntimeMXBean().getName().replaceAll("[^0-9a-zA-Z]", ""); }
});
} catch (PrivilegedActionException pae)
{ throw new RuntimeException(pae); }
}
protected final HttpClient httpClient;
protected final AtomicBoolean closed;
private final Cleaner.Cleanable cleanable;
protected final boolean allowClosingHttpClient;
protected HttpContextProvider httpContextProvider;
protected SSLContext sslContext;
protected HostnameVerifier hostnameVerifier;
protected int responseBufferSize = 8192;
protected HttpHost defaultProxy = null;
protected boolean chunked = false;
protected boolean followRedirects = false;
/**
* For uploading File's over JAX-RS framework, this property, together with {@link #fileUploadMemoryUnit},
* defines the maximum File size allowed in memory. If fileSize exceeds this size, it will be stored to
* {@link #fileUploadTempFileDir}. <br>
* <br>
* Defaults to 1 MB
*/
protected int fileUploadInMemoryThresholdLimit = 1;
/**
* The unit for {@link #fileUploadInMemoryThresholdLimit}. <br>
* <br>
* Defaults to MB.
*
* @see MemoryUnit
*/
protected MemoryUnit fileUploadMemoryUnit = MemoryUnit.MB;
/**
* Temp directory to write output request stream to. Any file to be uploaded has to be written out to the
* output request stream to be sent to the service and when the File is too huge the output request stream is
* written out to the disk rather than to memory. <br>
* <br>
* Defaults to JVM temp directory.
*/
protected Path fileUploadTempFileDir = getTempDir();
public ManualClosingApacheHttpClient43Engine()
{
this(null, null, true, null);
}
public ManualClosingApacheHttpClient43Engine(final HttpHost defaultProxy)
{
this(null, null, true, defaultProxy);
}
public ManualClosingApacheHttpClient43Engine(final HttpClient httpClient)
{
this(httpClient, null, true, null);
}
public ManualClosingApacheHttpClient43Engine(final HttpClient httpClient, final boolean closeHttpClient)
{
this(httpClient, null, closeHttpClient, null);
}
public ManualClosingApacheHttpClient43Engine(final HttpClient httpClient,
final HttpContextProvider httpContextProvider)
{
this(httpClient, httpContextProvider, true, null);
}
private ManualClosingApacheHttpClient43Engine(final HttpClient httpClient,
final HttpContextProvider httpContextProvider, final boolean closeHttpClient, final HttpHost defaultProxy)
{
this.httpClient = httpClient != null ? httpClient : createDefaultHttpClient();
if (closeHttpClient && !(this.httpClient instanceof CloseableHttpClient))
{
throw new IllegalArgumentException(
"httpClient must be a CloseableHttpClient instance in order for allowing engine to close it!");
}
this.httpContextProvider = httpContextProvider;
this.allowClosingHttpClient = closeHttpClient;
closed = new AtomicBoolean(false);
this.cleanable = createCleanable(this, closeHttpClient, closed, this.httpClient);
this.defaultProxy = defaultProxy;
try
{
int threshold = Integer.parseInt(ConfigurationFactory.getInstance().getConfiguration()
.getOptionalValue(FILE_UPLOAD_IN_MEMORY_THRESHOLD_PROPERTY, String.class)
.orElse("1"));
if (threshold > -1)
{
this.fileUploadInMemoryThresholdLimit = threshold;
}
LogMessages.LOGGER.debugf("Negative threshold, %s, specified. Using default value", threshold);
}
catch (Exception e)
{
LogMessages.LOGGER.debug("Exception caught parsing memory threshold. Using default value.", e);
}
}
/**
* Response stream is wrapped in a BufferedInputStream. Default is 8192. Value of 0 will not wrap it.
* Value of -1 will use a SelfExpandingBufferedInputStream
*
* @return response buffer size
*/
public int getResponseBufferSize()
{
return responseBufferSize;
}
/**
* Response stream is wrapped in a BufferedInputStream. Default is 8192. Value of 0 will not wrap it.
* Value of -1 will use a SelfExpandingBufferedInputStream
*
* @param responseBufferSize response buffer size
*/
public void setResponseBufferSize(int responseBufferSize)
{
this.responseBufferSize = responseBufferSize;
}
/**
* Based on memory unit
* @return threshold limit
*/
public int getFileUploadInMemoryThresholdLimit()
{
return fileUploadInMemoryThresholdLimit;
}
public void setFileUploadInMemoryThresholdLimit(int fileUploadInMemoryThresholdLimit)
{
this.fileUploadInMemoryThresholdLimit = fileUploadInMemoryThresholdLimit;
}
public MemoryUnit getFileUploadMemoryUnit()
{
return fileUploadMemoryUnit;
}
public void setFileUploadMemoryUnit(MemoryUnit fileUploadMemoryUnit)
{
this.fileUploadMemoryUnit = fileUploadMemoryUnit;
}
public File getFileUploadTempFileDir()
{
return fileUploadTempFileDir.toFile();
}
public void setFileUploadTempFileDir(File fileUploadTempFileDir)
{
this.fileUploadTempFileDir = fileUploadTempFileDir.toPath();
}
public HttpClient getHttpClient()
{
return httpClient;
}
@Override
public SSLContext getSslContext()
{
return sslContext;
}
public void setSslContext(SSLContext sslContext)
{
this.sslContext = sslContext;
}
@Override
public HostnameVerifier getHostnameVerifier()
{
return hostnameVerifier;
}
public void setHostnameVerifier(HostnameVerifier hostnameVerifier)
{
this.hostnameVerifier = hostnameVerifier;
}
public static CaseInsensitiveMap<String> extractHeaders(HttpResponse response)
{
final CaseInsensitiveMap<String> headers = new CaseInsensitiveMap<String>();
for (Header header : response.getAllHeaders())
{
headers.add(header.getName(), header.getValue());
}
return headers;
}
protected InputStream createBufferedStream(InputStream is)
{
if (responseBufferSize == 0)
{
return is;
}
if (responseBufferSize < 0)
{
return new SelfExpandingBufferredInputStream(is);
}
return new BufferedInputStream(is, responseBufferSize);
}
@Override
public Response invoke(Invocation inv)
{
ClientInvocation request = (ClientInvocation)inv;
String uri = request.getUri().toString();
final HttpRequestBase httpMethod = createHttpMethod(uri, request.getMethod());
final HttpResponse res;
try
{
loadHttpMethod(request, httpMethod);
if (System.getSecurityManager() == null) {
res = httpClient.execute(httpMethod,
((httpContextProvider == null)? null : httpContextProvider.getContext()));
} else {
try {
res = AccessController.doPrivileged(new PrivilegedExceptionAction<HttpResponse>() {
@Override
public HttpResponse run() throws Exception {
return httpClient.execute(httpMethod,
((httpContextProvider == null)? null : httpContextProvider.getContext()));
}
});
} catch (PrivilegedActionException pae) {
throw new RuntimeException(pae);
}
}
}
catch (Exception e)
{
LogMessages.LOGGER.clientSendProcessingFailure(e);
throw new ProcessingException(Messages.MESSAGES.unableToInvokeRequest(e.toString()), e);
}
finally
{
cleanUpAfterExecute(httpMethod);
}
ClientResponse response = new FinalizedClientResponse(request.getClientConfiguration(), request.getTracingLogger())
{
InputStream stream;
InputStream hc4Stream;
@Override
protected void setInputStream(InputStream is)
{
stream = is;
resetEntity();
}
public InputStream getInputStream()
{
if (stream == null)
{
HttpEntity entity = res.getEntity();
if (entity == null)
return null;
try
{
hc4Stream = entity.getContent();
stream = createBufferedStream(hc4Stream);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
return stream;
}
@Override
public void releaseConnection() throws IOException
{
releaseConnection(true);
}
@Override
public void releaseConnection(boolean consumeInputStream) throws IOException
{
if (consumeInputStream)
{
// Apache Client 4 is stupid, You have to get the InputStream and close it if there is an entity
// otherwise the connection is never released. There is, of course, no close() method on response
// to make this easier.
try
{
// Another stupid thing...TCK is testing a specific exception from stream.close()
// so, we let it propagate up.
if (stream != null)
{
stream.close();
}
else
{
InputStream is = getInputStream();
if (is != null)
{
is.close();
}
}
}
finally
{
// just in case the input stream was entirely replaced and not wrapped, we need
// to close the apache client input stream.
if (hc4Stream != null)
{
try
{
hc4Stream.close();
}
catch (IOException ignored)
{
}
}
else
{
try
{
HttpEntity entity = res.getEntity();
if (entity != null)
entity.getContent().close();
}
catch (IOException ignored)
{
}
}
}
}
else if (res instanceof CloseableHttpResponse)
{
try
{
((CloseableHttpResponse) res).close();
}
catch (IOException e)
{
LogMessages.LOGGER.warn(Messages.MESSAGES.couldNotCloseHttpResponse(), e);
}
}
}
};
response.setProperties(request.getMutableProperties());
response.setStatus(res.getStatusLine().getStatusCode());
response.setReasonPhrase(res.getStatusLine().getReasonPhrase());
response.setHeaders(extractHeaders(res));
response.setClientConfiguration(request.getClientConfiguration());
return response;
}
protected HttpRequestBase createHttpMethod(String url, String restVerb)
{
if ("GET".equals(restVerb))
{
return new HttpGet(url);
}
else if ("POST".equals(restVerb))
{
return new HttpPost(url);
}
else
{
final String verb = restVerb;
return new HttpPost(url)
{
@Override
public String getMethod()
{
return verb;
}
};
}
}
protected void loadHttpMethod(final ClientInvocation request, HttpRequestBase httpMethod) throws Exception
{
if (isFollowRedirects())
{
setRedirectRequired(request, httpMethod);
}
else
{
setRedirectNotRequired(request, httpMethod);
}
if (request.getEntity() != null)
{
if (httpMethod instanceof HttpGet)
throw new ProcessingException(Messages.MESSAGES.getRequestCannotHaveBody());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
request.getDelegatingOutputStream().setDelegate(baos);
try
{
HttpEntity entity = buildEntity(request);
HttpPost post = (HttpPost) httpMethod;
commitHeaders(request, httpMethod);
post.setEntity(entity);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
else // no body
{
commitHeaders(request, httpMethod);
}
}
protected void commitHeaders(ClientInvocation request, HttpRequestBase httpMethod)
{
MultivaluedMap<String, String> headers = request.getHeaders().asMap();
for (Map.Entry<String, List<String>> header : headers.entrySet())
{
List<String> values = header.getValue();
for (String value : values)
{
httpMethod.addHeader(header.getKey(), value);
}
}
}
public boolean isChunked()
{
return chunked;
}
public void setChunked(boolean chunked)
{
this.chunked = chunked;
}
@Override
public boolean isFollowRedirects()
{
return followRedirects;
}
@Override
public void setFollowRedirects(boolean followRedirects)
{
this.followRedirects = followRedirects;
}
/**
* If passed httpMethod is of type HttpPost then obtain its entity. If the entity has an enclosing File then
* delete it by invoking this method after the request has completed. The entity will have an enclosing File
* only if it was too huge to fit into memory.
*
* @param httpMethod - the httpMethod to clean up.
*/
protected void cleanUpAfterExecute(final HttpRequestBase httpMethod)
{
}
/**
* Build the HttpEntity to be sent to the Service as part of (POST) request. Creates a off-memory
* {@link FileEntity} or a regular in-memory {@link ByteArrayEntity} depending on if the request
* OutputStream fit into memory when built by calling.
*
* @param request -
* @return - the built HttpEntity
* @throws IOException -
*/
protected HttpEntity buildEntity(final ClientInvocation request) throws IOException
{
AbstractHttpEntity entityToBuild = null;
try (EntityOutputStream entityStream = writeRequestBodyToOutputStream(request)) {
MediaType mediaType = request.getHeaders().getMediaType();
entityToBuild = entityStream.toEntity();
if (mediaType != null) {
entityToBuild
.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, mediaType.toString()));
}
if (request.isChunked()) {
entityToBuild.setChunked(true);
}
}
return entityToBuild;
}
/**
* Creates the request OutputStream, to be sent to the end Service invoked, as a
* <a href="http://commons.apache.org/io/api-release/org/apache/commons/io/output/DeferredFileOutputStream.html"
* >DeferredFileOutputStream</a>.
*
*
* @param request -
* @return - DeferredFileOutputStream with the ClientRequest written out per HTTP specification.
* @throws IOException -
*/
private EntityOutputStream writeRequestBodyToOutputStream(final ClientInvocation request) throws IOException
{
try (EntityOutputStream entityStream = new EntityOutputStream(
this.fileUploadInMemoryThresholdLimit * getMemoryUnitMultiplier(), this.fileUploadTempFileDir, this::getTempfilePrefix)) {
request.getDelegatingOutputStream().setDelegate(entityStream);
request.writeRequestBody(request.getEntityStream());
return entityStream;
}
}
/**
* Use context information, which will include node name, to avoid conflicts in case of multiple VMS using same
* temp directory location.
*
* @return -
*/
protected String getTempfilePrefix()
{
return processId;
}
/**
* @return - the constant to multiply {@link #fileUploadInMemoryThresholdLimit} with based on
* {@link #fileUploadMemoryUnit} enumeration value.
*/
private int getMemoryUnitMultiplier()
{
switch (this.fileUploadMemoryUnit)
{
case BY :
return 1;
case KB :
return 1024;
case MB :
return 1024 * 1024;
case GB :
return 1024 * 1024 * 1024;
}
return 1;
}
protected HttpClient createDefaultHttpClient()
{
final HttpClientBuilder builder = HttpClientBuilder.create();
RequestConfig.Builder requestBuilder = RequestConfig.custom();
if (defaultProxy != null)
{
requestBuilder.setProxy(defaultProxy);
}
builder.disableContentCompression();
builder.setDefaultRequestConfig(requestBuilder.build());
return builder.build();
}
public HttpHost getDefaultProxy()
{
Configurable clientConfiguration = (Configurable) httpClient;
return clientConfiguration.getConfig().getProxy();
}
protected void setRedirectRequired(final ClientInvocation request, final HttpRequestBase httpMethod)
{
RequestConfig.Builder requestBuilder = RequestConfig.copy(getCurrentConfiguration(request, httpMethod));
requestBuilder.setRedirectsEnabled(true);
httpMethod.setConfig(requestBuilder.build());
}
protected void setRedirectNotRequired(final ClientInvocation request, final HttpRequestBase httpMethod)
{
RequestConfig.Builder requestBuilder = RequestConfig.copy(getCurrentConfiguration(request, httpMethod));
requestBuilder.setRedirectsEnabled(false);
httpMethod.setConfig(requestBuilder.build());
}
private RequestConfig getCurrentConfiguration(final ClientInvocation request, final HttpRequestBase httpMethod)
{
RequestConfig baseConfig;
if (httpMethod != null && httpMethod.getConfig() != null)
{
baseConfig = httpMethod.getConfig();
}
else
{
ManualClosingApacheHttpClient43Engine engine = ((ManualClosingApacheHttpClient43Engine) request.getClient().httpEngine());
baseConfig = ((Configurable) engine.getHttpClient()).getConfig();
if (baseConfig == null)
{
Configurable clientConfiguration = (Configurable) httpClient;
baseConfig = clientConfiguration.getConfig();
}
}
return baseConfig;
}
public boolean isClosed()
{
return closed.get();
}
@Override
public void close() {
cleanable.clean();
}
private static Cleaner.Cleanable createCleanable(final ManualClosingApacheHttpClient43Engine engine, final boolean allowClose,
final AtomicBoolean closed, final HttpClient client) {
if (allowClose && client instanceof CloseableHttpClient) {
return ResourceCleaner.register(engine, new CleanupAction(closed, (CloseableHttpClient) client));
}
return () -> closed.set(true);
}
private static Path getTempDir() {
if (System.getSecurityManager() == null) {
final Optional<String> value = ConfigurationFactory.getInstance().getConfiguration().getOptionalValue("java.io.tmpdir", String.class);
return value.map(Path::of).orElseGet(() -> Path.of(System.getProperty("java.io.tmpdir")));
}
return AccessController.doPrivileged((PrivilegedAction<Path>) () -> {
final Optional<String> value = ConfigurationFactory.getInstance().getConfiguration().getOptionalValue("java.io.tmpdir", String.class);
return value.map(Path::of).orElseGet(() -> Path.of(System.getProperty("java.io.tmpdir")));
});
}
}