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