f4f0705cb5b7cd8cbd5fb61f577151b9bf45444a
[policy/common.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2018 Samsung Electronics Co., Ltd.
7  * Modifications Copyright (C) 2019 Nordix Foundation.
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.common.endpoints.http.client.internal;
24
25 import java.security.KeyManagementException;
26 import java.security.NoSuchAlgorithmException;
27 import java.security.SecureRandom;
28 import java.util.Collections;
29 import java.util.Map;
30 import java.util.Map.Entry;
31 import java.util.concurrent.Future;
32 import javax.net.ssl.SSLContext;
33 import javax.ws.rs.client.Client;
34 import javax.ws.rs.client.ClientBuilder;
35 import javax.ws.rs.client.Entity;
36 import javax.ws.rs.client.Invocation.Builder;
37 import javax.ws.rs.client.InvocationCallback;
38 import javax.ws.rs.client.WebTarget;
39 import javax.ws.rs.core.Response;
40 import org.apache.commons.lang3.StringUtils;
41 import org.glassfish.jersey.client.ClientProperties;
42 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
43 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
44 import org.onap.policy.common.endpoints.http.client.HttpClient;
45 import org.onap.policy.common.gson.annotation.GsonJsonIgnore;
46 import org.onap.policy.common.utils.network.NetworkUtil;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 /**
51  * Http Client implementation using a Jersey Client.
52  */
53 public class JerseyClient implements HttpClient {
54
55     /**
56      * Logger.
57      */
58     private static Logger logger = LoggerFactory.getLogger(JerseyClient.class);
59
60     protected static final String JERSEY_DEFAULT_SERIALIZATION_PROVIDER =
61                     "org.onap.policy.common.gson.GsonMessageBodyHandler";
62
63     protected final String name;
64     protected final boolean https;
65     protected final boolean selfSignedCerts;
66     protected final String hostname;
67     protected final int port;
68     protected final String basePath;
69     protected final String userName;
70     protected final String password;
71
72     protected final Client client;
73     protected final String baseUrl;
74
75     protected boolean alive = true;
76
77     /**
78      * Constructor.
79      *
80      * <p>name the name https is it https or not selfSignedCerts are there self signed certs
81      * hostname the hostname port port being used basePath base context userName user
82      * password password
83      *
84      * @param busTopicParams Input parameters object
85      * @throws KeyManagementException key exception
86      * @throws NoSuchAlgorithmException no algorithm exception
87      * @throws ClassNotFoundException if the serialization provider cannot be found
88      */
89     public JerseyClient(BusTopicParams busTopicParams)
90                     throws KeyManagementException, NoSuchAlgorithmException, ClassNotFoundException {
91
92         if (busTopicParams.isClientNameInvalid()) {
93             throw new IllegalArgumentException("Name must be provided");
94         }
95
96         if (busTopicParams.isHostnameInvalid()) {
97             throw new IllegalArgumentException("Hostname must be provided");
98         }
99
100         if (busTopicParams.isPortInvalid()) {
101             throw new IllegalArgumentException("Invalid Port provided: " + busTopicParams.getPort());
102         }
103
104         this.name = busTopicParams.getClientName();
105         this.https = busTopicParams.isUseHttps();
106         this.hostname = busTopicParams.getHostname();
107         this.port = busTopicParams.getPort();
108         this.basePath = busTopicParams.getBasePath();
109         this.userName = busTopicParams.getUserName();
110         this.password = busTopicParams.getPassword();
111         this.selfSignedCerts = busTopicParams.isAllowSelfSignedCerts();
112         this.client = detmClient();
113
114         if (!StringUtils.isBlank(this.userName) && !StringUtils.isBlank(this.password)) {
115             HttpAuthenticationFeature authFeature = HttpAuthenticationFeature.basic(userName, password);
116             this.client.register(authFeature);
117         }
118
119         this.client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true");
120
121         registerSerProviders(busTopicParams.getSerializationProvider());
122
123         this.baseUrl = (this.https ? "https://" : "http://") + this.hostname + ":" + this.port + "/"
124                         + (this.basePath == null ? "" : this.basePath);
125     }
126
127     private Client detmClient() throws NoSuchAlgorithmException, KeyManagementException {
128         if (this.https) {
129             ClientBuilder clientBuilder;
130             SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
131             if (this.selfSignedCerts) {
132                 sslContext.init(null, NetworkUtil.getAlwaysTrustingManager(), new SecureRandom());
133
134                 // This falls under self signed certs which is used for non-production testing environments where
135                 // the hostname in the cert is unlikely to be crafted properly.  We always return true for the
136                 // hostname verifier.  This causes a sonar vuln but we ignore it as it could cause problems in some
137                 // testing environments.
138                 clientBuilder =
139                         ClientBuilder.newBuilder().sslContext(sslContext).hostnameVerifier(
140                             (host, session) -> true); //NOSONAR
141             } else {
142                 sslContext.init(null, null, null);
143                 clientBuilder = ClientBuilder.newBuilder().sslContext(sslContext);
144             }
145             return clientBuilder.build();
146
147         } else {
148             return ClientBuilder.newClient();
149         }
150     }
151
152     /**
153      * Registers the serialization provider(s) with the client.
154      *
155      * @param serializationProvider comma-separated list of serialization providers
156      * @throws ClassNotFoundException if the serialization provider cannot be found
157      */
158     private void registerSerProviders(String serializationProvider) throws ClassNotFoundException {
159         String providers = (StringUtils.isBlank(serializationProvider)
160                         ? JERSEY_DEFAULT_SERIALIZATION_PROVIDER : serializationProvider);
161         for (String prov : providers.split(",")) {
162             this.client.register(Class.forName(prov));
163         }
164     }
165
166     @Override
167     public WebTarget getWebTarget() {
168         return this.client.target(this.baseUrl);
169     }
170
171     @Override
172     public Response get(String path) {
173         if (!StringUtils.isBlank(path)) {
174             return getWebTarget().path(path).request().get();
175         } else {
176             return getWebTarget().request().get();
177         }
178     }
179
180     @Override
181     public Response get() {
182         return getWebTarget().request().get();
183     }
184
185     @Override
186     public Future<Response> get(InvocationCallback<Response> callback, String path, Map<String, Object> headers) {
187         Map<String, Object> headers2 = (headers != null ? headers : Collections.emptyMap());
188
189         if (!StringUtils.isBlank(path)) {
190             return getBuilder(path, headers2).async().get(callback);
191         } else {
192             return get(callback, headers2);
193         }
194     }
195
196     @Override
197     public Future<Response> get(InvocationCallback<Response> callback, Map<String, Object> headers) {
198         Builder builder = getWebTarget().request();
199         if (headers != null) {
200             headers.forEach(builder::header);
201         }
202         return builder.async().get(callback);
203     }
204
205     @Override
206     public Response put(String path, Entity<?> entity, Map<String, Object> headers) {
207         return getBuilder(path, headers).put(entity);
208     }
209
210     @Override
211     public Future<Response> put(InvocationCallback<Response> callback, String path, Entity<?> entity,
212                     Map<String, Object> headers) {
213         return getBuilder(path, headers).async().put(entity, callback);
214     }
215
216     @Override
217     public Response post(String path, Entity<?> entity, Map<String, Object> headers) {
218         return getBuilder(path, headers).post(entity);
219     }
220
221     @Override
222     public Future<Response> post(InvocationCallback<Response> callback, String path, Entity<?> entity,
223                     Map<String, Object> headers) {
224         return getBuilder(path, headers).async().post(entity, callback);
225     }
226
227     @Override
228     public Response delete(String path, Map<String, Object> headers) {
229         return getBuilder(path, headers).delete();
230     }
231
232     @Override
233     public Future<Response> delete(InvocationCallback<Response> callback, String path, Map<String, Object> headers) {
234         return getBuilder(path, headers).async().delete(callback);
235     }
236
237     @Override
238     public boolean start() {
239         return alive;
240     }
241
242     @Override
243     public boolean stop() {
244         return !alive;
245     }
246
247     @Override
248     public void shutdown() {
249         synchronized (this) {
250             alive = false;
251         }
252
253         try {
254             this.client.close();
255         } catch (Exception e) {
256             logger.warn("{}: cannot close because of {}", this, e.getMessage(), e);
257         }
258     }
259
260     @Override
261     public synchronized boolean isAlive() {
262         return this.alive;
263     }
264
265     @Override
266     public String getName() {
267         return name;
268     }
269
270     @Override
271     public boolean isHttps() {
272         return https;
273     }
274
275     @Override
276     public boolean isSelfSignedCerts() {
277         return selfSignedCerts;
278     }
279
280     @Override
281     public String getHostname() {
282         return hostname;
283     }
284
285     @Override
286     public int getPort() {
287         return port;
288     }
289
290     @Override
291     public String getBasePath() {
292         return basePath;
293     }
294
295     @Override
296     public String getUserName() {
297         return userName;
298     }
299
300     @GsonJsonIgnore
301     @Override
302     public String getPassword() {
303         return password;
304     }
305
306     @Override
307     public String getBaseUrl() {
308         return baseUrl;
309     }
310
311     @Override
312     public String toString() {
313         StringBuilder builder = new StringBuilder();
314         builder.append("JerseyClient [name=");
315         builder.append(name);
316         builder.append(", https=");
317         builder.append(https);
318         builder.append(", selfSignedCerts=");
319         builder.append(selfSignedCerts);
320         builder.append(", hostname=");
321         builder.append(hostname);
322         builder.append(", port=");
323         builder.append(port);
324         builder.append(", basePath=");
325         builder.append(basePath);
326         builder.append(", userName=");
327         builder.append(userName);
328         builder.append(", password=");
329         builder.append(password);
330         builder.append(", client=");
331         builder.append(client);
332         builder.append(", baseUrl=");
333         builder.append(baseUrl);
334         builder.append(", alive=");
335         builder.append(alive);
336         builder.append("]");
337         return builder.toString();
338     }
339
340     private Builder getBuilder(String path, Map<String, Object> headers) {
341         Builder builder = getWebTarget().path(path).request();
342         for (Entry<String, Object> header : headers.entrySet()) {
343             builder.header(header.getKey(), header.getValue());
344         }
345         return builder;
346     }
347
348
349 }