753994a6b85abb729f45c5f1253688004f039bee
[policy/common.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2017-2021 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.google.re2j.Pattern;
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 lombok.Getter;
42 import lombok.ToString;
43 import org.apache.commons.lang3.StringUtils;
44 import org.glassfish.jersey.client.ClientProperties;
45 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
46 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
47 import org.onap.policy.common.endpoints.http.client.HttpClient;
48 import org.onap.policy.common.utils.network.NetworkUtil;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 /**
53  * Http Client implementation using a Jersey Client.
54  */
55 @Getter
56 @ToString
57 public class JerseyClient implements HttpClient {
58     private static final Pattern COMMA_PAT = Pattern.compile(",");
59
60     /**
61      * Logger.
62      */
63     private static Logger logger = LoggerFactory.getLogger(JerseyClient.class);
64
65     protected static final String JERSEY_DEFAULT_SERIALIZATION_PROVIDER =
66                     "org.onap.policy.common.gson.GsonMessageBodyHandler";
67
68     protected final String name;
69     protected final boolean https;
70     protected final boolean selfSignedCerts;
71     protected final String hostname;
72     protected final int port;
73     protected final String basePath;
74     protected final String userName;
75     protected final String password;
76
77     protected final Client client;
78     protected final String baseUrl;
79
80     protected boolean alive = true;
81
82     /**
83      * Constructor.
84      *
85      * <p>name the name https is it https or not selfSignedCerts are there self signed certs
86      * hostname the hostname port port being used basePath base context userName user
87      * password password
88      *
89      * @param busTopicParams Input parameters object
90      * @throws KeyManagementException key exception
91      * @throws NoSuchAlgorithmException no algorithm exception
92      * @throws ClassNotFoundException if the serialization provider cannot be found
93      */
94     public JerseyClient(BusTopicParams busTopicParams)
95                     throws KeyManagementException, NoSuchAlgorithmException, ClassNotFoundException {
96
97         if (busTopicParams.isClientNameInvalid()) {
98             throw new IllegalArgumentException("Name must be provided");
99         }
100
101         if (busTopicParams.isHostnameInvalid()) {
102             throw new IllegalArgumentException("Hostname must be provided");
103         }
104
105         if (busTopicParams.isPortInvalid()) {
106             throw new IllegalArgumentException("Invalid Port provided: " + busTopicParams.getPort());
107         }
108
109         this.name = busTopicParams.getClientName();
110         this.https = busTopicParams.isUseHttps();
111         this.hostname = busTopicParams.getHostname();
112         this.port = busTopicParams.getPort();
113         this.basePath = busTopicParams.getBasePath();
114         this.userName = busTopicParams.getUserName();
115         this.password = busTopicParams.getPassword();
116         this.selfSignedCerts = busTopicParams.isAllowSelfSignedCerts();
117         this.client = detmClient();
118
119         if (!StringUtils.isBlank(this.userName) && !StringUtils.isBlank(this.password)) {
120             var authFeature = HttpAuthenticationFeature.basic(userName, password);
121             this.client.register(authFeature);
122         }
123
124         this.client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true");
125
126         registerSerProviders(busTopicParams.getSerializationProvider());
127
128         this.baseUrl = (this.https ? "https://" : "http://") + this.hostname + ":" + this.port + "/"
129                         + (this.basePath == null ? "" : this.basePath);
130     }
131
132     private Client detmClient() throws NoSuchAlgorithmException, KeyManagementException {
133         if (this.https) {
134             ClientBuilder clientBuilder;
135             var sslContext = SSLContext.getInstance("TLSv1.2");
136             if (this.selfSignedCerts) {
137                 sslContext.init(null, NetworkUtil.getAlwaysTrustingManager(), new SecureRandom());
138
139                 // This falls under self signed certs which is used for non-production testing environments where
140                 // the hostname in the cert is unlikely to be crafted properly.  We always return true for the
141                 // hostname verifier.  This causes a sonar vuln but we ignore it as it could cause problems in some
142                 // testing environments.
143                 clientBuilder =
144                         ClientBuilder.newBuilder().sslContext(sslContext).hostnameVerifier(
145                             (host, session) -> true); //NOSONAR
146             } else {
147                 sslContext.init(null, null, null);
148                 clientBuilder = ClientBuilder.newBuilder().sslContext(sslContext);
149             }
150             return clientBuilder.build();
151
152         } else {
153             return ClientBuilder.newClient();
154         }
155     }
156
157     /**
158      * Registers the serialization provider(s) with the client.
159      *
160      * @param serializationProvider comma-separated list of serialization providers
161      * @throws ClassNotFoundException if the serialization provider cannot be found
162      */
163     private void registerSerProviders(String serializationProvider) throws ClassNotFoundException {
164         String providers = (StringUtils.isBlank(serializationProvider)
165                         ? JERSEY_DEFAULT_SERIALIZATION_PROVIDER : serializationProvider);
166         for (String prov : COMMA_PAT.split(providers)) {
167             this.client.register(Class.forName(prov));
168         }
169     }
170
171     @Override
172     public WebTarget getWebTarget() {
173         return this.client.target(this.baseUrl);
174     }
175
176     @Override
177     public Response get(String path) {
178         if (!StringUtils.isBlank(path)) {
179             return getWebTarget().path(path).request().get();
180         } else {
181             return getWebTarget().request().get();
182         }
183     }
184
185     @Override
186     public Response get() {
187         return getWebTarget().request().get();
188     }
189
190     @Override
191     public Future<Response> get(InvocationCallback<Response> callback, String path, Map<String, Object> headers) {
192         Map<String, Object> headers2 = (headers != null ? headers : Collections.emptyMap());
193
194         if (!StringUtils.isBlank(path)) {
195             return getBuilder(path, headers2).async().get(callback);
196         } else {
197             return get(callback, headers2);
198         }
199     }
200
201     @Override
202     public Future<Response> get(InvocationCallback<Response> callback, Map<String, Object> headers) {
203         var builder = getWebTarget().request();
204         if (headers != null) {
205             headers.forEach(builder::header);
206         }
207         return builder.async().get(callback);
208     }
209
210     @Override
211     public Response put(String path, Entity<?> entity, Map<String, Object> headers) {
212         return getBuilder(path, headers).put(entity);
213     }
214
215     @Override
216     public Future<Response> put(InvocationCallback<Response> callback, String path, Entity<?> entity,
217                     Map<String, Object> headers) {
218         return getBuilder(path, headers).async().put(entity, callback);
219     }
220
221     @Override
222     public Response post(String path, Entity<?> entity, Map<String, Object> headers) {
223         return getBuilder(path, headers).post(entity);
224     }
225
226     @Override
227     public Future<Response> post(InvocationCallback<Response> callback, String path, Entity<?> entity,
228                     Map<String, Object> headers) {
229         return getBuilder(path, headers).async().post(entity, callback);
230     }
231
232     @Override
233     public Response delete(String path, Map<String, Object> headers) {
234         return getBuilder(path, headers).delete();
235     }
236
237     @Override
238     public Future<Response> delete(InvocationCallback<Response> callback, String path, Map<String, Object> headers) {
239         return getBuilder(path, headers).async().delete(callback);
240     }
241
242     @Override
243     public boolean start() {
244         return alive;
245     }
246
247     @Override
248     public boolean stop() {
249         return !alive;
250     }
251
252     @Override
253     public void shutdown() {
254         synchronized (this) {
255             alive = false;
256         }
257
258         try {
259             this.client.close();
260         } catch (Exception e) {
261             logger.warn("{}: cannot close because of {}", this, e.getMessage(), e);
262         }
263     }
264
265     @Override
266     public synchronized boolean isAlive() {
267         return this.alive;
268     }
269
270     private Builder getBuilder(String path, Map<String, Object> headers) {
271         var builder = getWebTarget().path(path).request();
272         for (Entry<String, Object> header : headers.entrySet()) {
273             builder.header(header.getKey(), header.getValue());
274         }
275         return builder;
276     }
277
278
279 }