2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
6 * Modifications Copyright (C) 2018 Samsung Electronics Co., Ltd.
7 * Modifications Copyright (C) 2019 Nordix Foundation.
8 * ================================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
20 * ============LICENSE_END=========================================================
23 package org.onap.policy.common.endpoints.http.client.internal;
25 import java.security.KeyManagementException;
26 import java.security.NoSuchAlgorithmException;
27 import java.security.SecureRandom;
28 import java.util.Collections;
30 import java.util.Map.Entry;
31 import java.util.concurrent.Future;
32 import javax.net.ssl.SSLContext;
33 import javax.ws.rs.client.Client;
34 import javax.ws.rs.client.ClientBuilder;
35 import javax.ws.rs.client.Entity;
36 import javax.ws.rs.client.Invocation.Builder;
37 import javax.ws.rs.client.InvocationCallback;
38 import javax.ws.rs.client.WebTarget;
39 import javax.ws.rs.core.Response;
40 import org.apache.commons.lang3.StringUtils;
41 import org.glassfish.jersey.client.ClientProperties;
42 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
43 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
44 import org.onap.policy.common.endpoints.http.client.HttpClient;
45 import org.onap.policy.common.gson.annotation.GsonJsonIgnore;
46 import org.onap.policy.common.utils.network.NetworkUtil;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
51 * Http Client implementation using a Jersey Client.
53 public class JerseyClient implements HttpClient {
58 private static Logger logger = LoggerFactory.getLogger(JerseyClient.class);
60 protected static final String JERSEY_DEFAULT_SERIALIZATION_PROVIDER =
61 "org.onap.policy.common.gson.GsonMessageBodyHandler";
63 protected final String name;
64 protected final boolean https;
65 protected final boolean selfSignedCerts;
66 protected final String hostname;
67 protected final int port;
68 protected final String basePath;
69 protected final String userName;
70 protected final String password;
72 protected final Client client;
73 protected final String baseUrl;
75 protected boolean alive = true;
80 * <p>name the name https is it https or not selfSignedCerts are there self signed certs
81 * hostname the hostname port port being used basePath base context userName user
84 * @param busTopicParams Input parameters object
85 * @throws KeyManagementException key exception
86 * @throws NoSuchAlgorithmException no algorithm exception
87 * @throws ClassNotFoundException if the serialization provider cannot be found
89 public JerseyClient(BusTopicParams busTopicParams)
90 throws KeyManagementException, NoSuchAlgorithmException, ClassNotFoundException {
92 if (busTopicParams.isClientNameInvalid()) {
93 throw new IllegalArgumentException("Name must be provided");
96 if (busTopicParams.isHostnameInvalid()) {
97 throw new IllegalArgumentException("Hostname must be provided");
100 if (busTopicParams.isPortInvalid()) {
101 throw new IllegalArgumentException("Invalid Port provided: " + busTopicParams.getPort());
104 this.name = busTopicParams.getClientName();
105 this.https = busTopicParams.isUseHttps();
106 this.hostname = busTopicParams.getHostname();
107 this.port = busTopicParams.getPort();
108 this.basePath = busTopicParams.getBasePath();
109 this.userName = busTopicParams.getUserName();
110 this.password = busTopicParams.getPassword();
111 this.selfSignedCerts = busTopicParams.isAllowSelfSignedCerts();
112 this.client = detmClient();
114 if (!StringUtils.isBlank(this.userName) && !StringUtils.isBlank(this.password)) {
115 HttpAuthenticationFeature authFeature = HttpAuthenticationFeature.basic(userName, password);
116 this.client.register(authFeature);
119 this.client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true");
121 registerSerProviders(busTopicParams.getSerializationProvider());
123 this.baseUrl = (this.https ? "https://" : "http://") + this.hostname + ":" + this.port + "/"
124 + (this.basePath == null ? "" : this.basePath);
127 private Client detmClient() throws NoSuchAlgorithmException, KeyManagementException {
129 ClientBuilder clientBuilder;
130 SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
131 if (this.selfSignedCerts) {
132 sslContext.init(null, NetworkUtil.getAlwaysTrustingManager(), new SecureRandom());
134 // This falls under self signed certs which is used for non-production testing environments where
135 // the hostname in the cert is unlikely to be crafted properly. We always return true for the
136 // hostname verifier. This causes a sonar vuln but we ignore it as it could cause problems in some
137 // testing environments.
139 ClientBuilder.newBuilder().sslContext(sslContext).hostnameVerifier(
140 (host, session) -> true); //NOSONAR
142 sslContext.init(null, null, null);
143 clientBuilder = ClientBuilder.newBuilder().sslContext(sslContext);
145 return clientBuilder.build();
148 return ClientBuilder.newClient();
153 * Registers the serialization provider(s) with the client.
155 * @param serializationProvider comma-separated list of serialization providers
156 * @throws ClassNotFoundException if the serialization provider cannot be found
158 private void registerSerProviders(String serializationProvider) throws ClassNotFoundException {
159 String providers = (StringUtils.isBlank(serializationProvider)
160 ? JERSEY_DEFAULT_SERIALIZATION_PROVIDER : serializationProvider);
161 for (String prov : providers.split(",")) {
162 this.client.register(Class.forName(prov));
167 public WebTarget getWebTarget() {
168 return this.client.target(this.baseUrl);
172 public Response get(String path) {
173 if (!StringUtils.isBlank(path)) {
174 return getWebTarget().path(path).request().get();
176 return getWebTarget().request().get();
181 public Response get() {
182 return getWebTarget().request().get();
186 public Future<Response> get(InvocationCallback<Response> callback, String path, Map<String, Object> headers) {
187 Map<String, Object> headers2 = (headers != null ? headers : Collections.emptyMap());
189 if (!StringUtils.isBlank(path)) {
190 return getBuilder(path, headers2).async().get(callback);
192 return get(callback, headers2);
197 public Future<Response> get(InvocationCallback<Response> callback, Map<String, Object> headers) {
198 Builder builder = getWebTarget().request();
199 if (headers != null) {
200 headers.forEach(builder::header);
202 return builder.async().get(callback);
206 public Response put(String path, Entity<?> entity, Map<String, Object> headers) {
207 return getBuilder(path, headers).put(entity);
211 public Future<Response> put(InvocationCallback<Response> callback, String path, Entity<?> entity,
212 Map<String, Object> headers) {
213 return getBuilder(path, headers).async().put(entity, callback);
217 public Response post(String path, Entity<?> entity, Map<String, Object> headers) {
218 return getBuilder(path, headers).post(entity);
222 public Future<Response> post(InvocationCallback<Response> callback, String path, Entity<?> entity,
223 Map<String, Object> headers) {
224 return getBuilder(path, headers).async().post(entity, callback);
228 public Response delete(String path, Map<String, Object> headers) {
229 return getBuilder(path, headers).delete();
233 public Future<Response> delete(InvocationCallback<Response> callback, String path, Map<String, Object> headers) {
234 return getBuilder(path, headers).async().delete(callback);
238 public boolean start() {
243 public boolean stop() {
248 public void shutdown() {
249 synchronized (this) {
255 } catch (Exception e) {
256 logger.warn("{}: cannot close because of {}", this, e.getMessage(), e);
261 public synchronized boolean isAlive() {
266 public String getName() {
271 public boolean isHttps() {
276 public boolean isSelfSignedCerts() {
277 return selfSignedCerts;
281 public String getHostname() {
286 public int getPort() {
291 public String getBasePath() {
296 public String getUserName() {
302 public String getPassword() {
307 public String getBaseUrl() {
312 public String toString() {
313 StringBuilder builder = new StringBuilder();
314 builder.append("JerseyClient [name=");
315 builder.append(name);
316 builder.append(", https=");
317 builder.append(https);
318 builder.append(", selfSignedCerts=");
319 builder.append(selfSignedCerts);
320 builder.append(", hostname=");
321 builder.append(hostname);
322 builder.append(", port=");
323 builder.append(port);
324 builder.append(", basePath=");
325 builder.append(basePath);
326 builder.append(", userName=");
327 builder.append(userName);
328 builder.append(", password=");
329 builder.append(password);
330 builder.append(", client=");
331 builder.append(client);
332 builder.append(", baseUrl=");
333 builder.append(baseUrl);
334 builder.append(", alive=");
335 builder.append(alive);
337 return builder.toString();
340 private Builder getBuilder(String path, Map<String, Object> headers) {
341 Builder builder = getWebTarget().path(path).request();
342 for (Entry<String, Object> header : headers.entrySet()) {
343 builder.header(header.getKey(), header.getValue());