b55a7bb2ffddf40b714606aca87a2deaa5261561
[policy/common.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2018 Samsung Electronics Co., Ltd.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.common.endpoints.http.client.internal;
23
24 import com.fasterxml.jackson.annotation.JsonIgnore;
25
26 import java.security.KeyManagementException;
27 import java.security.NoSuchAlgorithmException;
28 import java.security.SecureRandom;
29 import java.security.cert.CertificateException;
30 import java.security.cert.X509Certificate;
31 import java.util.Map;
32 import java.util.Map.Entry;
33
34 import javax.net.ssl.SSLContext;
35 import javax.net.ssl.TrustManager;
36 import javax.net.ssl.X509TrustManager;
37 import javax.ws.rs.client.Client;
38 import javax.ws.rs.client.ClientBuilder;
39 import javax.ws.rs.client.Entity;
40 import javax.ws.rs.client.Invocation.Builder;
41 import javax.ws.rs.core.Response;
42
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.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 /**
50  * Http Client implementation using a Jersey Client.
51  */
52 public class JerseyClient implements HttpClient {
53
54     /**
55      * Logger.
56      */
57     private static Logger logger = LoggerFactory.getLogger(JerseyClient.class);
58
59     protected final String name;
60     protected final boolean https;
61     protected final boolean selfSignedCerts;
62     protected final String hostname;
63     protected final int port;
64     protected final String basePath;
65     protected final String userName;
66     protected final String password;
67
68     protected final Client client;
69     protected final String baseUrl;
70
71     protected boolean alive = true;
72
73     /**
74      * Constructor.
75      * 
76      * <p>name the name https is it https or not selfSignedCerts are there self signed certs hostname
77      * the hostname port port being used basePath base context userName user password password
78      * 
79      * @param busTopicParams Input parameters object
80      * @throws KeyManagementException key exception
81      * @throws NoSuchAlgorithmException no algorithm exception
82      */
83     public JerseyClient(BusTopicParams busTopicParams) throws KeyManagementException, NoSuchAlgorithmException {
84
85         super();
86
87         if (busTopicParams.isClientNameInvalid()) {
88             throw new IllegalArgumentException("Name must be provided");
89         }
90
91         if (busTopicParams.isHostnameInvalid()) {
92             throw new IllegalArgumentException("Hostname must be provided");
93         }
94
95         if (busTopicParams.isPortInvalid()) {
96             throw new IllegalArgumentException("Invalid Port provided: " + busTopicParams.getPort());
97         }
98
99         this.name = busTopicParams.getClientName();
100         this.https = busTopicParams.isUseHttps();
101         this.hostname = busTopicParams.getHostname();
102         this.port = busTopicParams.getPort();
103         this.basePath = busTopicParams.getBasePath();
104         this.userName = busTopicParams.getUserName();
105         this.password = busTopicParams.getPassword();
106         this.selfSignedCerts = busTopicParams.isAllowSelfSignedCerts();
107
108         StringBuilder tmpBaseUrl = new StringBuilder();
109         if (this.https) {
110             tmpBaseUrl.append("https://");
111             ClientBuilder clientBuilder;
112             SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
113             if (this.selfSignedCerts) {
114                 sslContext.init(null, new TrustManager[] {new X509TrustManager() {
115                     @Override
116                     public void checkClientTrusted(X509Certificate[] chain, String authType)
117                             throws CertificateException {
118                         // always trusted
119                     }
120
121                     @Override
122                     public void checkServerTrusted(X509Certificate[] chain, String authType)
123                             throws CertificateException {
124                         // always trusted
125                     }
126
127                     @Override
128                     public X509Certificate[] getAcceptedIssuers() {
129                         return new X509Certificate[0];
130                     }
131
132                 } }, new SecureRandom());
133                 clientBuilder =
134                         ClientBuilder.newBuilder().sslContext(sslContext).hostnameVerifier((host, session) -> true);
135             } else {
136                 sslContext.init(null, null, null);
137                 clientBuilder = ClientBuilder.newBuilder().sslContext(sslContext);
138             }
139             this.client = clientBuilder.build();
140         } else {
141             tmpBaseUrl.append("http://");
142             this.client = ClientBuilder.newClient();
143         }
144
145         if (this.userName != null && !this.userName.isEmpty() && this.password != null && !this.password.isEmpty()) {
146             HttpAuthenticationFeature authFeature = HttpAuthenticationFeature.basic(userName, password);
147             this.client.register(authFeature);
148         }
149
150         this.baseUrl = tmpBaseUrl.append(this.hostname).append(":").append(this.port).append("/")
151                 .append((this.basePath == null) ? "" : this.basePath).toString();
152     }
153
154     @Override
155     public Response get(String path) {
156         if (path != null && !path.isEmpty()) {
157             return this.client.target(this.baseUrl).path(path).request().get();
158         } else {
159             return this.client.target(this.baseUrl).request().get();
160         }
161     }
162
163     @Override
164     public Response get() {
165         return this.client.target(this.baseUrl).request().get();
166     }
167
168     @Override
169     public Response put(String path, Entity<?> entity, Map<String, Object> headers) {
170         return getBuilder(path, headers).put(entity);
171     }
172
173     @Override
174     public Response post(String path, Entity<?> entity, Map<String, Object> headers) {
175         return getBuilder(path, headers).post(entity);
176     }
177
178     @Override
179     public Response delete(String path, Map<String, Object> headers) {
180         return getBuilder(path, headers).delete();
181     }
182
183     @Override
184     public boolean start() {
185         return alive;
186     }
187
188     @Override
189     public boolean stop() {
190         return !alive;
191     }
192
193     @Override
194     public void shutdown() {
195         synchronized (this) {
196             alive = false;
197         }
198
199         try {
200             this.client.close();
201         } catch (Exception e) {
202             logger.warn("{}: cannot close because of {}", this, e.getMessage(), e);
203         }
204     }
205
206     @Override
207     public synchronized boolean isAlive() {
208         return this.alive;
209     }
210
211     @Override
212     public String getName() {
213         return name;
214     }
215
216     @Override
217     public boolean isHttps() {
218         return https;
219     }
220
221     @Override
222     public boolean isSelfSignedCerts() {
223         return selfSignedCerts;
224     }
225
226     @Override
227     public String getHostname() {
228         return hostname;
229     }
230
231     @Override
232     public int getPort() {
233         return port;
234     }
235
236     @Override
237     public String getBasePath() {
238         return basePath;
239     }
240
241     @Override
242     public String getUserName() {
243         return userName;
244     }
245
246     @JsonIgnore
247     @Override
248     public String getPassword() {
249         return password;
250     }
251
252     @Override
253     public String getBaseUrl() {
254         return baseUrl;
255     }
256
257     @Override
258     public String toString() {
259         StringBuilder builder = new StringBuilder();
260         builder.append("JerseyClient [name=");
261         builder.append(name);
262         builder.append(", https=");
263         builder.append(https);
264         builder.append(", selfSignedCerts=");
265         builder.append(selfSignedCerts);
266         builder.append(", hostname=");
267         builder.append(hostname);
268         builder.append(", port=");
269         builder.append(port);
270         builder.append(", basePath=");
271         builder.append(basePath);
272         builder.append(", userName=");
273         builder.append(userName);
274         builder.append(", password=");
275         builder.append(password);
276         builder.append(", client=");
277         builder.append(client);
278         builder.append(", baseUrl=");
279         builder.append(baseUrl);
280         builder.append(", alive=");
281         builder.append(alive);
282         builder.append("]");
283         return builder.toString();
284     }
285
286     private Builder getBuilder(String path, Map<String, Object> headers) {
287         Builder builder = this.client.target(this.baseUrl).path(path).request();
288         for (Entry<String, Object> header : headers.entrySet()) {
289             builder.header(header.getKey(), header.getValue());
290         }
291         return builder;
292     }
293
294
295 }