c227071c3aaacd61e87179422249b04e9706c14d
[policy/common.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * policy-endpoints
4  * ================================================================================
5  * Copyright (C) 2017-2018 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
32 import javax.net.ssl.SSLContext;
33 import javax.net.ssl.TrustManager;
34 import javax.net.ssl.X509TrustManager;
35 import javax.ws.rs.client.Client;
36 import javax.ws.rs.client.ClientBuilder;
37 import javax.ws.rs.core.Response;
38
39 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
40 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
41 import org.onap.policy.common.endpoints.http.client.HttpClient;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 public class JerseyClient implements HttpClient {
46
47     /**
48      * Logger.
49      */
50     private static Logger logger = LoggerFactory.getLogger(JerseyClient.class);
51
52     protected final String name;
53     protected final boolean https;
54     protected final boolean selfSignedCerts;
55     protected final String hostname;
56     protected final int port;
57     protected final String basePath;
58     protected final String userName;
59     protected final String password;
60
61     protected final Client client;
62     protected final String baseUrl;
63
64     protected boolean alive = true;
65
66     /**
67      * Constructor.
68      * 
69      * name the name
70      * https is it https or not
71      * selfSignedCerts are there self signed certs
72      * hostname the hostname
73      * port port being used
74      * basePath base context
75      * userName user
76      * password password
77      * @param busTopicParams Input parameters object
78      * @throws KeyManagementException key exception
79      * @throws NoSuchAlgorithmException no algorithm exception
80      */
81     public JerseyClient(BusTopicParams busTopicParams) throws KeyManagementException, NoSuchAlgorithmException {
82
83         super();
84
85         if (busTopicParams.isClientNameInvalid()) {
86             throw new IllegalArgumentException("Name must be provided");
87         }
88
89         if (busTopicParams.isHostnameInvalid()) {
90             throw new IllegalArgumentException("Hostname must be provided");
91         }
92
93         if (busTopicParams.isPortInvalid()) {
94             throw new IllegalArgumentException("Invalid Port provided: " + busTopicParams.getPort());
95         }
96
97         this.name = busTopicParams.getClientName();
98         this.https = busTopicParams.isUseHttps();
99         this.hostname = busTopicParams.getHostname();
100         this.port = busTopicParams.getPort();
101         this.basePath = busTopicParams.getBasePath();
102         this.userName = busTopicParams.getUserName();
103         this.password = busTopicParams.getPassword();
104         this.selfSignedCerts = busTopicParams.isAllowSelfSignedCerts();
105
106         StringBuilder tmpBaseUrl = new StringBuilder();
107         if (this.https) {
108             tmpBaseUrl.append("https://");
109             ClientBuilder clientBuilder;
110             SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
111             if (this.selfSignedCerts) {
112                 sslContext.init(null, new TrustManager[] {new X509TrustManager() {
113                     @Override
114                     public void checkClientTrusted(X509Certificate[] chain, String authType)
115                             throws CertificateException {
116                         // always trusted
117                     }
118
119                     @Override
120                     public void checkServerTrusted(X509Certificate[] chain, String authType)
121                             throws CertificateException {
122                         // always trusted
123                     }
124
125                     @Override
126                     public X509Certificate[] getAcceptedIssuers() {
127                         return new X509Certificate[0];
128                     }
129
130                 }}, new SecureRandom());
131                 clientBuilder =
132                         ClientBuilder.newBuilder().sslContext(sslContext).hostnameVerifier((host, session) -> true);
133             } else {
134                 sslContext.init(null, null, null);
135                 clientBuilder = ClientBuilder.newBuilder().sslContext(sslContext);
136             }
137             this.client = clientBuilder.build();
138         } else {
139             tmpBaseUrl.append("http://");
140             this.client = ClientBuilder.newClient();
141         }
142
143         if (this.userName != null && !this.userName.isEmpty() && this.password != null && !this.password.isEmpty()) {
144             HttpAuthenticationFeature authFeature = HttpAuthenticationFeature.basic(userName, password);
145             this.client.register(authFeature);
146         }
147
148         this.baseUrl = tmpBaseUrl.append(this.hostname).append(":").append(this.port).append("/")
149                 .append((this.basePath == null) ? "" : this.basePath).toString();
150     }
151
152     @Override
153     public Response get(String path) {
154         if (path != null && !path.isEmpty()) {
155             return this.client.target(this.baseUrl).path(path).request().get();
156         } else {
157             return this.client.target(this.baseUrl).request().get();
158         }
159     }
160
161     @Override
162     public Response get() {
163         return this.client.target(this.baseUrl).request().get();
164     }
165
166
167     @Override
168     public boolean start() {
169         return alive;
170     }
171
172     @Override
173     public boolean stop() {
174         return !alive;
175     }
176
177     @Override
178     public void shutdown() {
179         synchronized (this) {
180             alive = false;
181         }
182
183         try {
184             this.client.close();
185         } catch (Exception e) {
186             logger.warn("{}: cannot close because of {}", this, e.getMessage(), e);
187         }
188     }
189
190     @Override
191     public synchronized boolean isAlive() {
192         return this.alive;
193     }
194
195     @Override
196     public String getName() {
197         return name;
198     }
199
200     @Override
201     public boolean isHttps() {
202         return https;
203     }
204
205     @Override
206     public boolean isSelfSignedCerts() {
207         return selfSignedCerts;
208     }
209
210     @Override
211     public String getHostname() {
212         return hostname;
213     }
214
215     @Override
216     public int getPort() {
217         return port;
218     }
219
220     @Override
221     public String getBasePath() {
222         return basePath;
223     }
224
225     @Override
226     public String getUserName() {
227         return userName;
228     }
229
230     @JsonIgnore
231     @Override
232     public String getPassword() {
233         return password;
234     }
235
236     @Override
237     public String getBaseUrl() {
238         return baseUrl;
239     }
240
241     @Override
242     public String toString() {
243         StringBuilder builder = new StringBuilder();
244         builder.append("JerseyClient [name=");
245         builder.append(name);
246         builder.append(", https=");
247         builder.append(https);
248         builder.append(", selfSignedCerts=");
249         builder.append(selfSignedCerts);
250         builder.append(", hostname=");
251         builder.append(hostname);
252         builder.append(", port=");
253         builder.append(port);
254         builder.append(", basePath=");
255         builder.append(basePath);
256         builder.append(", userName=");
257         builder.append(userName);
258         builder.append(", password=");
259         builder.append(password);
260         builder.append(", client=");
261         builder.append(client);
262         builder.append(", baseUrl=");
263         builder.append(baseUrl);
264         builder.append(", alive=");
265         builder.append(alive);
266         builder.append("]");
267         return builder.toString();
268     }
269
270 }