001package ca.uhn.fhir.test.utilities;
002
003/*-
004 * #%L
005 * HAPI FHIR Test Utilities
006 * %%
007 * Copyright (C) 2014 - 2023 Smile CDR, Inc.
008 * %%
009 * Licensed under the Apache License, Version 2.0 (the "License");
010 * you may not use this file except in compliance with the License.
011 * You may obtain a copy of the License at
012 *
013 *      http://www.apache.org/licenses/LICENSE-2.0
014 *
015 * Unless required by applicable law or agreed to in writing, software
016 * distributed under the License is distributed on an "AS IS" BASIS,
017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
018 * See the License for the specific language governing permissions and
019 * limitations under the License.
020 * #L%
021 */
022
023import org.apache.http.client.methods.CloseableHttpResponse;
024import org.apache.http.client.methods.HttpUriRequest;
025import org.apache.http.impl.client.CloseableHttpClient;
026import org.apache.http.impl.client.HttpClientBuilder;
027import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
028import org.junit.jupiter.api.extension.AfterEachCallback;
029import org.junit.jupiter.api.extension.BeforeEachCallback;
030import org.junit.jupiter.api.extension.ExtensionContext;
031
032import java.io.IOException;
033import java.util.concurrent.TimeUnit;
034
035// TODO KHS merge with HttpClientHelper
036public class HttpClientExtension implements BeforeEachCallback, AfterEachCallback {
037        private CloseableHttpClient myClient;
038
039        public CloseableHttpClient getClient() {
040                return myClient;
041        }
042
043        @Override
044        public void afterEach(ExtensionContext theExtensionContext) throws Exception {
045                myClient.close();
046        }
047
048        @Override
049        public void beforeEach(ExtensionContext theExtensionContext) throws Exception {
050                PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS);
051                connectionManager.setMaxTotal(99);
052                connectionManager.setDefaultMaxPerRoute(99);
053                myClient = HttpClientBuilder
054                        .create()
055                        .setConnectionManager(connectionManager)
056                        .setMaxConnPerRoute(99)
057                        .build();
058        }
059
060        public CloseableHttpResponse execute(HttpUriRequest theRequest) throws IOException {
061                return myClient.execute(theRequest);
062        }
063}