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 com.fasterxml.jackson.annotation.JsonIgnore;
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 {
59 private static Logger logger = LoggerFactory.getLogger(JerseyClient.class);
61 protected static final String JERSEY_DEFAULT_SERIALIZATION_PROVIDER =
62 "org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJsonProvider";
64 protected final String name;
65 protected final boolean https;
66 protected final boolean selfSignedCerts;
67 protected final String hostname;
68 protected final int port;
69 protected final String basePath;
70 protected final String userName;
71 protected final String password;
73 protected final Client client;
74 protected final String baseUrl;
76 protected boolean alive = true;
81 * <p>name the name https is it https or not selfSignedCerts are there self signed certs
82 * hostname the hostname port port being used basePath base context userName user
85 * @param busTopicParams Input parameters object
86 * @throws KeyManagementException key exception
87 * @throws NoSuchAlgorithmException no algorithm exception
88 * @throws ClassNotFoundException if the serialization provider cannot be found
90 public JerseyClient(BusTopicParams busTopicParams)
91 throws KeyManagementException, NoSuchAlgorithmException, ClassNotFoundException {
93 if (busTopicParams.isClientNameInvalid()) {
94 throw new IllegalArgumentException("Name must be provided");
97 if (busTopicParams.isHostnameInvalid()) {
98 throw new IllegalArgumentException("Hostname must be provided");
101 if (busTopicParams.isPortInvalid()) {
102 throw new IllegalArgumentException("Invalid Port provided: " + busTopicParams.getPort());
105 this.name = busTopicParams.getClientName();
106 this.https = busTopicParams.isUseHttps();
107 this.hostname = busTopicParams.getHostname();
108 this.port = busTopicParams.getPort();
109 this.basePath = busTopicParams.getBasePath();
110 this.userName = busTopicParams.getUserName();
111 this.password = busTopicParams.getPassword();
112 this.selfSignedCerts = busTopicParams.isAllowSelfSignedCerts();
113 this.client = detmClient();
115 if (!StringUtils.isBlank(this.userName) && !StringUtils.isBlank(this.password)) {
116 HttpAuthenticationFeature authFeature = HttpAuthenticationFeature.basic(userName, password);
117 this.client.register(authFeature);
120 this.client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true");
122 registerSerProviders(busTopicParams.getSerializationProvider());
124 this.baseUrl = (this.https ? "https://" : "http://") + this.hostname + ":" + this.port + "/"
125 + (this.basePath == null ? "" : this.basePath);
128 private Client detmClient() throws NoSuchAlgorithmException, KeyManagementException {
130 ClientBuilder clientBuilder;
131 SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
132 if (this.selfSignedCerts) {
133 sslContext.init(null, NetworkUtil.getAlwaysTrustingManager(), new SecureRandom());
135 // This falls under self signed certs which is used for non-production testing environments where
136 // the hostname in the cert is unlikely to be crafted properly. We always return true for the
137 // hostname verifier. This causes a sonar vuln but we ignore it as it could cause problems in some
138 // testing environments.
140 ClientBuilder.newBuilder().sslContext(sslContext).hostnameVerifier(
141 (host, session) -> true); //NOSONAR
143 sslContext.init(null, null, null);
144 clientBuilder = ClientBuilder.newBuilder().sslContext(sslContext);
146 return clientBuilder.build();
149 return ClientBuilder.newClient();
154 * Registers the serialization provider(s) with the client.
156 * @param serializationProvider comma-separated list of serialization providers
157 * @throws ClassNotFoundException if the serialization provider cannot be found
159 private void registerSerProviders(String serializationProvider) throws ClassNotFoundException {
160 String providers = (StringUtils.isBlank(serializationProvider)
161 ? JERSEY_DEFAULT_SERIALIZATION_PROVIDER : serializationProvider);
162 for (String prov : providers.split(",")) {
163 this.client.register(Class.forName(prov));
168 public WebTarget getWebTarget() {
169 return this.client.target(this.baseUrl);
173 public Response get(String path) {
174 if (!StringUtils.isBlank(path)) {
175 return getWebTarget().path(path).request().get();
177 return getWebTarget().request().get();
182 public Response get() {
183 return getWebTarget().request().get();
187 public Future<Response> get(InvocationCallback<Response> callback, String path, Map<String, Object> headers) {
188 Map<String, Object> headers2 = (headers != null ? headers : Collections.emptyMap());
190 if (!StringUtils.isBlank(path)) {
191 return getBuilder(path, headers2).async().get(callback);
193 return get(callback, headers2);
198 public Future<Response> get(InvocationCallback<Response> callback, Map<String, Object> headers) {
199 Builder builder = getWebTarget().request();
200 if (headers != null) {
201 headers.forEach(builder::header);
203 return builder.async().get(callback);
207 public Response put(String path, Entity<?> entity, Map<String, Object> headers) {
208 return getBuilder(path, headers).put(entity);
212 public Future<Response> put(InvocationCallback<Response> callback, String path, Entity<?> entity,
213 Map<String, Object> headers) {
214 return getBuilder(path, headers).async().put(entity, callback);
218 public Response post(String path, Entity<?> entity, Map<String, Object> headers) {
219 return getBuilder(path, headers).post(entity);
223 public Future<Response> post(InvocationCallback<Response> callback, String path, Entity<?> entity,
224 Map<String, Object> headers) {
225 return getBuilder(path, headers).async().post(entity, callback);
229 public Response delete(String path, Map<String, Object> headers) {
230 return getBuilder(path, headers).delete();
234 public Future<Response> delete(InvocationCallback<Response> callback, String path, Map<String, Object> headers) {
235 return getBuilder(path, headers).async().delete(callback);
239 public boolean start() {
244 public boolean stop() {
249 public void shutdown() {
250 synchronized (this) {
256 } catch (Exception e) {
257 logger.warn("{}: cannot close because of {}", this, e.getMessage(), e);
262 public synchronized boolean isAlive() {
267 public String getName() {
272 public boolean isHttps() {
277 public boolean isSelfSignedCerts() {
278 return selfSignedCerts;
282 public String getHostname() {
287 public int getPort() {
292 public String getBasePath() {
297 public String getUserName() {
304 public String getPassword() {
309 public String getBaseUrl() {
314 public String toString() {
315 StringBuilder 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 Builder builder = getWebTarget().path(path).request();
344 for (Entry<String, Object> header : headers.entrySet()) {
345 builder.header(header.getKey(), header.getValue());