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