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;
42 import lombok.ToString;
43 import org.apache.commons.lang3.StringUtils;
44 import org.glassfish.jersey.client.ClientProperties;
45 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
46 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
47 import org.onap.policy.common.endpoints.http.client.HttpClient;
48 import org.onap.policy.common.utils.network.NetworkUtil;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
53 * Http Client implementation using a Jersey Client.
57 public class JerseyClient implements HttpClient {
58 private static final Pattern COMMA_PAT = Pattern.compile(",");
63 private static Logger logger = LoggerFactory.getLogger(JerseyClient.class);
65 protected static final String JERSEY_DEFAULT_SERIALIZATION_PROVIDER =
66 "org.onap.policy.common.gson.GsonMessageBodyHandler";
68 protected final String name;
69 protected final boolean https;
70 protected final boolean selfSignedCerts;
71 protected final String hostname;
72 protected final int port;
73 protected final String basePath;
74 protected final String userName;
75 protected final String password;
77 protected final Client client;
78 protected final String baseUrl;
80 protected boolean alive = true;
85 * <p>name the name https is it https or not selfSignedCerts are there self signed certs
86 * hostname the hostname port port being used basePath base context userName user
89 * @param busTopicParams Input parameters object
90 * @throws KeyManagementException key exception
91 * @throws NoSuchAlgorithmException no algorithm exception
92 * @throws ClassNotFoundException if the serialization provider cannot be found
94 public JerseyClient(BusTopicParams busTopicParams)
95 throws KeyManagementException, NoSuchAlgorithmException, ClassNotFoundException {
97 if (busTopicParams.isClientNameInvalid()) {
98 throw new IllegalArgumentException("Name must be provided");
101 if (busTopicParams.isHostnameInvalid()) {
102 throw new IllegalArgumentException("Hostname must be provided");
105 if (busTopicParams.isPortInvalid()) {
106 throw new IllegalArgumentException("Invalid Port provided: " + busTopicParams.getPort());
109 this.name = busTopicParams.getClientName();
110 this.https = busTopicParams.isUseHttps();
111 this.hostname = busTopicParams.getHostname();
112 this.port = busTopicParams.getPort();
113 this.basePath = busTopicParams.getBasePath();
114 this.userName = busTopicParams.getUserName();
115 this.password = busTopicParams.getPassword();
116 this.selfSignedCerts = busTopicParams.isAllowSelfSignedCerts();
117 this.client = detmClient();
119 if (!StringUtils.isBlank(this.userName) && !StringUtils.isBlank(this.password)) {
120 var authFeature = HttpAuthenticationFeature.basic(userName, password);
121 this.client.register(authFeature);
124 this.client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true");
126 registerSerProviders(busTopicParams.getSerializationProvider());
128 this.baseUrl = (this.https ? "https://" : "http://") + this.hostname + ":" + this.port + "/"
129 + (this.basePath == null ? "" : this.basePath);
132 private Client detmClient() throws NoSuchAlgorithmException, KeyManagementException {
134 ClientBuilder clientBuilder;
135 var sslContext = SSLContext.getInstance("TLSv1.2");
136 if (this.selfSignedCerts) {
137 sslContext.init(null, NetworkUtil.getAlwaysTrustingManager(), new SecureRandom());
139 // This falls under self signed certs which is used for non-production testing environments where
140 // the hostname in the cert is unlikely to be crafted properly. We always return true for the
141 // hostname verifier. This causes a sonar vuln but we ignore it as it could cause problems in some
142 // testing environments.
144 ClientBuilder.newBuilder().sslContext(sslContext).hostnameVerifier(
145 (host, session) -> true); //NOSONAR
147 sslContext.init(null, null, null);
148 clientBuilder = ClientBuilder.newBuilder().sslContext(sslContext);
150 return clientBuilder.build();
153 return ClientBuilder.newClient();
158 * Registers the serialization provider(s) with the client.
160 * @param serializationProvider comma-separated list of serialization providers
161 * @throws ClassNotFoundException if the serialization provider cannot be found
163 private void registerSerProviders(String serializationProvider) throws ClassNotFoundException {
164 String providers = (StringUtils.isBlank(serializationProvider)
165 ? JERSEY_DEFAULT_SERIALIZATION_PROVIDER : serializationProvider);
166 for (String prov : COMMA_PAT.split(providers)) {
167 this.client.register(Class.forName(prov));
172 public WebTarget getWebTarget() {
173 return this.client.target(this.baseUrl);
177 public Response get(String path) {
178 if (!StringUtils.isBlank(path)) {
179 return getWebTarget().path(path).request().get();
181 return getWebTarget().request().get();
186 public Response get() {
187 return getWebTarget().request().get();
191 public Future<Response> get(InvocationCallback<Response> callback, String path, Map<String, Object> headers) {
192 Map<String, Object> headers2 = (headers != null ? headers : Collections.emptyMap());
194 if (!StringUtils.isBlank(path)) {
195 return getBuilder(path, headers2).async().get(callback);
197 return get(callback, headers2);
202 public Future<Response> get(InvocationCallback<Response> callback, Map<String, Object> headers) {
203 var builder = getWebTarget().request();
204 if (headers != null) {
205 headers.forEach(builder::header);
207 return builder.async().get(callback);
211 public Response put(String path, Entity<?> entity, Map<String, Object> headers) {
212 return getBuilder(path, headers).put(entity);
216 public Future<Response> put(InvocationCallback<Response> callback, String path, Entity<?> entity,
217 Map<String, Object> headers) {
218 return getBuilder(path, headers).async().put(entity, callback);
222 public Response post(String path, Entity<?> entity, Map<String, Object> headers) {
223 return getBuilder(path, headers).post(entity);
227 public Future<Response> post(InvocationCallback<Response> callback, String path, Entity<?> entity,
228 Map<String, Object> headers) {
229 return getBuilder(path, headers).async().post(entity, callback);
233 public Response delete(String path, Map<String, Object> headers) {
234 return getBuilder(path, headers).delete();
238 public Future<Response> delete(InvocationCallback<Response> callback, String path, Map<String, Object> headers) {
239 return getBuilder(path, headers).async().delete(callback);
243 public boolean start() {
248 public boolean stop() {
253 public void shutdown() {
254 synchronized (this) {
260 } catch (Exception e) {
261 logger.warn("{}: cannot close because of {}", this, e.getMessage(), e);
266 public synchronized boolean isAlive() {
270 private Builder getBuilder(String path, Map<String, Object> headers) {
271 var builder = getWebTarget().path(path).request();
272 for (Entry<String, Object> header : headers.entrySet()) {
273 builder.header(header.getKey(), header.getValue());