9463561572169f75c0c6cd85e7402343db65e441
[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 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 public class JerseyClient implements HttpClient {
50
51     /**
52      * Logger.
53      */
54     private static Logger logger = LoggerFactory.getLogger(JerseyClient.class);
55
56     protected final String name;
57     protected final boolean https;
58     protected final boolean selfSignedCerts;
59     protected final String hostname;
60     protected final int port;
61     protected final String basePath;
62     protected final String userName;
63     protected final String password;
64
65     protected final Client client;
66     protected final String baseUrl;
67
68     protected boolean alive = true;
69
70     /**
71      * Constructor.
72      * 
73      * <p>name the name https is it https or not selfSignedCerts are there self signed certs hostname
74      * the hostname port port being used basePath base context userName user password password
75      * 
76      * @param busTopicParams Input parameters object
77      * @throws KeyManagementException key exception
78      * @throws NoSuchAlgorithmException no algorithm exception
79      */
80     public JerseyClient(BusTopicParams busTopicParams) throws KeyManagementException, NoSuchAlgorithmException {
81
82         super();
83
84         if (busTopicParams.isClientNameInvalid()) {
85             throw new IllegalArgumentException("Name must be provided");
86         }
87
88         if (busTopicParams.isHostnameInvalid()) {
89             throw new IllegalArgumentException("Hostname must be provided");
90         }
91
92         if (busTopicParams.isPortInvalid()) {
93             throw new IllegalArgumentException("Invalid Port provided: " + busTopicParams.getPort());
94         }
95
96         this.name = busTopicParams.getClientName();
97         this.https = busTopicParams.isUseHttps();
98         this.hostname = busTopicParams.getHostname();
99         this.port = busTopicParams.getPort();
100         this.basePath = busTopicParams.getBasePath();
101         this.userName = busTopicParams.getUserName();
102         this.password = busTopicParams.getPassword();
103         this.selfSignedCerts = busTopicParams.isAllowSelfSignedCerts();
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     @Override
166     public Response put(String path, Entity<?> entity, Map<String, Object> headers) {
167         Builder builder = this.client.target(this.baseUrl).path(path).request();
168         for (Entry<String, Object> header : headers.entrySet()) {
169             builder.header(header.getKey(), header.getValue());
170         }
171         return builder.put(entity);
172     }
173
174     @Override
175     public boolean start() {
176         return alive;
177     }
178
179     @Override
180     public boolean stop() {
181         return !alive;
182     }
183
184     @Override
185     public void shutdown() {
186         synchronized (this) {
187             alive = false;
188         }
189
190         try {
191             this.client.close();
192         } catch (Exception e) {
193             logger.warn("{}: cannot close because of {}", this, e.getMessage(), e);
194         }
195     }
196
197     @Override
198     public synchronized boolean isAlive() {
199         return this.alive;
200     }
201
202     @Override
203     public String getName() {
204         return name;
205     }
206
207     @Override
208     public boolean isHttps() {
209         return https;
210     }
211
212     @Override
213     public boolean isSelfSignedCerts() {
214         return selfSignedCerts;
215     }
216
217     @Override
218     public String getHostname() {
219         return hostname;
220     }
221
222     @Override
223     public int getPort() {
224         return port;
225     }
226
227     @Override
228     public String getBasePath() {
229         return basePath;
230     }
231
232     @Override
233     public String getUserName() {
234         return userName;
235     }
236
237     @JsonIgnore
238     @Override
239     public String getPassword() {
240         return password;
241     }
242
243     @Override
244     public String getBaseUrl() {
245         return baseUrl;
246     }
247
248     @Override
249     public String toString() {
250         StringBuilder builder = new StringBuilder();
251         builder.append("JerseyClient [name=");
252         builder.append(name);
253         builder.append(", https=");
254         builder.append(https);
255         builder.append(", selfSignedCerts=");
256         builder.append(selfSignedCerts);
257         builder.append(", hostname=");
258         builder.append(hostname);
259         builder.append(", port=");
260         builder.append(port);
261         builder.append(", basePath=");
262         builder.append(basePath);
263         builder.append(", userName=");
264         builder.append(userName);
265         builder.append(", password=");
266         builder.append(password);
267         builder.append(", client=");
268         builder.append(client);
269         builder.append(", baseUrl=");
270         builder.append(baseUrl);
271         builder.append(", alive=");
272         builder.append(alive);
273         builder.append("]");
274         return builder.toString();
275     }
276
277 }