2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2021 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 com.google.re2j.Pattern;
26 import java.security.KeyManagementException;
27 import java.security.NoSuchAlgorithmException;
28 import java.security.SecureRandom;
29 import java.util.Collections;
31 import java.util.Map.Entry;
32 import java.util.concurrent.Future;
33 import javax.net.ssl.SSLContext;
34 import javax.ws.rs.client.Client;
35 import javax.ws.rs.client.ClientBuilder;
36 import javax.ws.rs.client.Entity;
37 import javax.ws.rs.client.Invocation.Builder;
38 import javax.ws.rs.client.InvocationCallback;
39 import javax.ws.rs.client.WebTarget;
40 import javax.ws.rs.core.Response;
41 import org.apache.commons.lang3.StringUtils;
42 import org.glassfish.jersey.client.ClientProperties;
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.onap.policy.common.gson.annotation.GsonJsonIgnore;
47 import org.onap.policy.common.utils.network.NetworkUtil;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
52 * Http Client implementation using a Jersey Client.
54 public class JerseyClient implements HttpClient {
55 private static final Pattern COMMA_PAT = Pattern.compile(",");
60 private static Logger logger = LoggerFactory.getLogger(JerseyClient.class);
62 protected static final String JERSEY_DEFAULT_SERIALIZATION_PROVIDER =
63 "org.onap.policy.common.gson.GsonMessageBodyHandler";
65 protected final String name;
66 protected final boolean https;
67 protected final boolean selfSignedCerts;
68 protected final String hostname;
69 protected final int port;
70 protected final String basePath;
71 protected final String userName;
72 protected final String password;
74 protected final Client client;
75 protected final String baseUrl;
77 protected boolean alive = true;
82 * <p>name the name https is it https or not selfSignedCerts are there self signed certs
83 * hostname the hostname port port being used basePath base context userName user
86 * @param busTopicParams Input parameters object
87 * @throws KeyManagementException key exception
88 * @throws NoSuchAlgorithmException no algorithm exception
89 * @throws ClassNotFoundException if the serialization provider cannot be found
91 public JerseyClient(BusTopicParams busTopicParams)
92 throws KeyManagementException, NoSuchAlgorithmException, ClassNotFoundException {
94 if (busTopicParams.isClientNameInvalid()) {
95 throw new IllegalArgumentException("Name must be provided");
98 if (busTopicParams.isHostnameInvalid()) {
99 throw new IllegalArgumentException("Hostname must be provided");
102 if (busTopicParams.isPortInvalid()) {
103 throw new IllegalArgumentException("Invalid Port provided: " + busTopicParams.getPort());
106 this.name = busTopicParams.getClientName();
107 this.https = busTopicParams.isUseHttps();
108 this.hostname = busTopicParams.getHostname();
109 this.port = busTopicParams.getPort();
110 this.basePath = busTopicParams.getBasePath();
111 this.userName = busTopicParams.getUserName();
112 this.password = busTopicParams.getPassword();
113 this.selfSignedCerts = busTopicParams.isAllowSelfSignedCerts();
114 this.client = detmClient();
116 if (!StringUtils.isBlank(this.userName) && !StringUtils.isBlank(this.password)) {
117 var authFeature = HttpAuthenticationFeature.basic(userName, password);
118 this.client.register(authFeature);
121 this.client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true");
123 registerSerProviders(busTopicParams.getSerializationProvider());
125 this.baseUrl = (this.https ? "https://" : "http://") + this.hostname + ":" + this.port + "/"
126 + (this.basePath == null ? "" : this.basePath);
129 private Client detmClient() throws NoSuchAlgorithmException, KeyManagementException {
131 ClientBuilder clientBuilder;
132 var sslContext = SSLContext.getInstance("TLSv1.2");
133 if (this.selfSignedCerts) {
134 sslContext.init(null, NetworkUtil.getAlwaysTrustingManager(), new SecureRandom());
136 // This falls under self signed certs which is used for non-production testing environments where
137 // the hostname in the cert is unlikely to be crafted properly. We always return true for the
138 // hostname verifier. This causes a sonar vuln but we ignore it as it could cause problems in some
139 // testing environments.
141 ClientBuilder.newBuilder().sslContext(sslContext).hostnameVerifier(
142 (host, session) -> true); //NOSONAR
144 sslContext.init(null, null, null);
145 clientBuilder = ClientBuilder.newBuilder().sslContext(sslContext);
147 return clientBuilder.build();
150 return ClientBuilder.newClient();
155 * Registers the serialization provider(s) with the client.
157 * @param serializationProvider comma-separated list of serialization providers
158 * @throws ClassNotFoundException if the serialization provider cannot be found
160 private void registerSerProviders(String serializationProvider) throws ClassNotFoundException {
161 String providers = (StringUtils.isBlank(serializationProvider)
162 ? JERSEY_DEFAULT_SERIALIZATION_PROVIDER : serializationProvider);
163 for (String prov : COMMA_PAT.split(providers)) {
164 this.client.register(Class.forName(prov));
169 public WebTarget getWebTarget() {
170 return this.client.target(this.baseUrl);
174 public Response get(String path) {
175 if (!StringUtils.isBlank(path)) {
176 return getWebTarget().path(path).request().get();
178 return getWebTarget().request().get();
183 public Response get() {
184 return getWebTarget().request().get();
188 public Future<Response> get(InvocationCallback<Response> callback, String path, Map<String, Object> headers) {
189 Map<String, Object> headers2 = (headers != null ? headers : Collections.emptyMap());
191 if (!StringUtils.isBlank(path)) {
192 return getBuilder(path, headers2).async().get(callback);
194 return get(callback, headers2);
199 public Future<Response> get(InvocationCallback<Response> callback, Map<String, Object> headers) {
200 var builder = getWebTarget().request();
201 if (headers != null) {
202 headers.forEach(builder::header);
204 return builder.async().get(callback);
208 public Response put(String path, Entity<?> entity, Map<String, Object> headers) {
209 return getBuilder(path, headers).put(entity);
213 public Future<Response> put(InvocationCallback<Response> callback, String path, Entity<?> entity,
214 Map<String, Object> headers) {
215 return getBuilder(path, headers).async().put(entity, callback);
219 public Response post(String path, Entity<?> entity, Map<String, Object> headers) {
220 return getBuilder(path, headers).post(entity);
224 public Future<Response> post(InvocationCallback<Response> callback, String path, Entity<?> entity,
225 Map<String, Object> headers) {
226 return getBuilder(path, headers).async().post(entity, callback);
230 public Response delete(String path, Map<String, Object> headers) {
231 return getBuilder(path, headers).delete();
235 public Future<Response> delete(InvocationCallback<Response> callback, String path, Map<String, Object> headers) {
236 return getBuilder(path, headers).async().delete(callback);
240 public boolean start() {
245 public boolean stop() {
250 public void shutdown() {
251 synchronized (this) {
257 } catch (Exception e) {
258 logger.warn("{}: cannot close because of {}", this, e.getMessage(), e);
263 public synchronized boolean isAlive() {
268 public String getName() {
273 public boolean isHttps() {
278 public boolean isSelfSignedCerts() {
279 return selfSignedCerts;
283 public String getHostname() {
288 public int getPort() {
293 public String getBasePath() {
298 public String getUserName() {
304 public String getPassword() {
309 public String getBaseUrl() {
314 public String toString() {
315 var builder = new StringBuilder();
316 builder.append("JerseyClient [name=");
317 builder.append(name);
318 builder.append(", https=");
319 builder.append(https);
320 builder.append(", selfSignedCerts=");
321 builder.append(selfSignedCerts);
322 builder.append(", hostname=");
323 builder.append(hostname);
324 builder.append(", port=");
325 builder.append(port);
326 builder.append(", basePath=");
327 builder.append(basePath);
328 builder.append(", userName=");
329 builder.append(userName);
330 builder.append(", password=");
331 builder.append(password);
332 builder.append(", client=");
333 builder.append(client);
334 builder.append(", baseUrl=");
335 builder.append(baseUrl);
336 builder.append(", alive=");
337 builder.append(alive);
339 return builder.toString();
342 private Builder getBuilder(String path, Map<String, Object> headers) {
343 var builder = getWebTarget().path(path).request();
344 for (Entry<String, Object> header : headers.entrySet()) {
345 builder.header(header.getKey(), header.getValue());