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