Added oparent to sdc main
[sdc.git] / common-app-api / src / main / java / org / openecomp / sdc / common / http / client / api / HttpRequestHandler.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.common.http.client.api;
22
23 import com.google.common.annotations.VisibleForTesting;
24 import org.apache.commons.io.IOUtils;
25 import org.apache.http.HttpEntity;
26 import org.apache.http.client.methods.CloseableHttpResponse;
27 import org.apache.http.util.EntityUtils;
28 import org.openecomp.sdc.common.api.Constants;
29 import org.openecomp.sdc.common.datastructure.FunctionalInterfaces.FunctionThrows;
30 import org.openecomp.sdc.common.http.config.HttpClientConfig;
31
32 import java.io.InputStream;
33 import java.util.Map;
34 import java.util.Properties;
35 import java.util.concurrent.ConcurrentHashMap;
36
37 public class HttpRequestHandler {
38     private static HttpRequestHandler handlerInstance = new HttpRequestHandler();
39     private static final String HTTPS_PREFIX = "https://";
40     private static final String HTTP_PREFIX = "http://";
41     
42     private Map<HttpClientConfigImmutable, HttpClient> clients = new ConcurrentHashMap<>();
43     private HttpClientFactory clientFactory;
44     
45     private FunctionThrows<CloseableHttpResponse, HttpResponse<byte[]>, Exception> byteResponseBuilder = (CloseableHttpResponse httpResponse) -> {
46         HttpEntity entity = httpResponse.getEntity();
47         byte[] response = null;
48         if (entity != null) {
49             InputStream content = entity.getContent();
50             if (content != null) {
51                 response = IOUtils.toByteArray(content);
52             }
53         }
54         return new HttpResponse<>(response, 
55                 httpResponse.getStatusLine().getStatusCode(), 
56                 httpResponse.getStatusLine().getReasonPhrase());
57     };
58
59     private FunctionThrows<CloseableHttpResponse, HttpResponse<String>, Exception> stringResponseBuilder = (CloseableHttpResponse httpResponse) -> {
60         HttpEntity entity = httpResponse.getEntity();
61         String response = null;
62         if (entity != null) {
63             response = EntityUtils.toString(entity);
64         }
65         return new HttpResponse<>(response, 
66                 httpResponse.getStatusLine().getStatusCode(),
67                 httpResponse.getStatusLine().getReasonPhrase());
68     };
69
70     private HttpRequestHandler() {
71         HttpConnectionMngFactory connectionMngFactory = new HttpConnectionMngFactory();
72         clientFactory = new HttpClientFactory(connectionMngFactory);
73     }
74     
75     public static HttpRequestHandler get() {
76         return handlerInstance;
77     }
78
79     public HttpResponse<String> get(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException {
80         HttpClient client = getOrCreateClient(url, config);
81         return client.<String>get(url, headers, stringResponseBuilder);
82     }
83
84     public HttpResponse<byte []> getAsByteArray(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException {
85         HttpClient client = getOrCreateClient(url, config);
86         return client.<byte[]>get(url, headers, byteResponseBuilder);
87     }
88
89     public HttpResponse<String> put(String url, Properties headers, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException {
90         HttpClient client = getOrCreateClient(url, config);
91         return client.<String>put(url, headers, entity, stringResponseBuilder);
92     }
93
94     public HttpResponse<String> post(String url, Properties headers, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException {
95         HttpClient client = getOrCreateClient(url, config);
96         return client.<String>post(url, headers, entity, stringResponseBuilder);
97     }
98
99     public HttpResponse<String> patch(String url, Properties headers, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException {
100         HttpClient client = getOrCreateClient(url, config);
101         return client.<String>patch(url, headers, entity, stringResponseBuilder);
102     }
103
104     public HttpResponse<String> delete(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException {
105         HttpClient client = getOrCreateClient(url, config != null ? config : HttpRequest.defaultConfig);
106         return client.<String>delete(url, headers, stringResponseBuilder);
107     }
108     
109     public void destroy() {
110         clients.forEach((k, v) -> v.close());
111         clients.clear();
112     }
113     
114     private HttpClient getOrCreateClient(String url, HttpClientConfig config) throws HttpExecuteException {
115         String protocol = getProtocol(url);
116         HttpClientConfigImmutable httpClientConfigImmutable = HttpClientConfigImmutable.getOrCreate(config);
117         return clients.computeIfAbsent(httpClientConfigImmutable, k -> createClient(protocol, httpClientConfigImmutable));
118     }
119
120     private HttpClient createClient(String protocol, HttpClientConfigImmutable config) {
121         return clientFactory.createClient(protocol, config);
122     }
123
124     @VisibleForTesting
125     public static void setTestInstance(HttpRequestHandler handlerInstance) {
126         HttpRequestHandler.handlerInstance = handlerInstance;
127     }
128
129     private String getProtocol(String url) throws HttpExecuteException {
130         if (url.startsWith(HTTPS_PREFIX)) {
131             return Constants.HTTPS;
132         }
133         else if (url.startsWith(HTTP_PREFIX)) {
134             return Constants.HTTP;
135         }
136         else {
137             throw new HttpExecuteException(String.format("Failed to create http client. Requested protocol is not supported \"%s\"", url));
138         }        
139     }
140 }