2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2019 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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
22 package org.onap.policy.common.endpoints.http.client.internal;
24 import com.fasterxml.jackson.annotation.JsonIgnore;
25 import java.security.KeyManagementException;
26 import java.security.NoSuchAlgorithmException;
27 import java.security.SecureRandom;
29 import java.util.Map.Entry;
30 import javax.net.ssl.SSLContext;
31 import javax.ws.rs.client.Client;
32 import javax.ws.rs.client.ClientBuilder;
33 import javax.ws.rs.client.Entity;
34 import javax.ws.rs.client.Invocation.Builder;
35 import javax.ws.rs.core.Response;
36 import org.glassfish.jersey.client.ClientProperties;
37 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
38 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
39 import org.onap.policy.common.endpoints.http.client.HttpClient;
40 import org.onap.policy.common.gson.annotation.GsonJsonIgnore;
41 import org.onap.policy.common.utils.network.NetworkUtil;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
46 * Http Client implementation using a Jersey Client.
48 public class JerseyClient implements HttpClient {
53 private static Logger logger = LoggerFactory.getLogger(JerseyClient.class);
55 protected static final String JERSEY_DEFAULT_SERIALIZATION_PROVIDER =
56 "com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider";
58 protected final String name;
59 protected final boolean https;
60 protected final boolean selfSignedCerts;
61 protected final String hostname;
62 protected final int port;
63 protected final String basePath;
64 protected final String userName;
65 protected final String password;
67 protected final Client client;
68 protected final String baseUrl;
70 protected boolean alive = true;
75 * <p>name the name https is it https or not selfSignedCerts are there self signed certs
76 * hostname the hostname port port being used basePath base context userName user
79 * @param busTopicParams Input parameters object
80 * @throws KeyManagementException key exception
81 * @throws NoSuchAlgorithmException no algorithm exception
82 * @throws ClassNotFoundException if the serialization provider cannot be found
84 public JerseyClient(BusTopicParams busTopicParams)
85 throws KeyManagementException, NoSuchAlgorithmException, ClassNotFoundException {
89 if (busTopicParams.isClientNameInvalid()) {
90 throw new IllegalArgumentException("Name must be provided");
93 if (busTopicParams.isHostnameInvalid()) {
94 throw new IllegalArgumentException("Hostname must be provided");
97 if (busTopicParams.isPortInvalid()) {
98 throw new IllegalArgumentException("Invalid Port provided: " + busTopicParams.getPort());
101 this.name = busTopicParams.getClientName();
102 this.https = busTopicParams.isUseHttps();
103 this.hostname = busTopicParams.getHostname();
104 this.port = busTopicParams.getPort();
105 this.basePath = busTopicParams.getBasePath();
106 this.userName = busTopicParams.getUserName();
107 this.password = busTopicParams.getPassword();
108 this.selfSignedCerts = busTopicParams.isAllowSelfSignedCerts();
110 StringBuilder tmpBaseUrl = new StringBuilder();
112 tmpBaseUrl.append("https://");
113 ClientBuilder clientBuilder;
114 SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
115 if (this.selfSignedCerts) {
116 sslContext.init(null, NetworkUtil.getAlwaysTrustingManager(), new SecureRandom());
118 ClientBuilder.newBuilder().sslContext(sslContext).hostnameVerifier((host, session) -> true);
120 sslContext.init(null, null, null);
121 clientBuilder = ClientBuilder.newBuilder().sslContext(sslContext);
123 this.client = clientBuilder.build();
125 tmpBaseUrl.append("http://");
126 this.client = ClientBuilder.newClient();
129 if (this.userName != null && !this.userName.isEmpty() && this.password != null && !this.password.isEmpty()) {
130 HttpAuthenticationFeature authFeature = HttpAuthenticationFeature.basic(userName, password);
131 this.client.register(authFeature);
134 registerSerProviders(busTopicParams.getSerializationProvider());
136 this.client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true");
138 this.baseUrl = tmpBaseUrl.append(this.hostname).append(":").append(this.port).append("/")
139 .append((this.basePath == null) ? "" : this.basePath).toString();
143 * Registers the serialization provider(s) with the client.
145 * @param serializationProvider comma-separated list of serialization providers
146 * @throws ClassNotFoundException if the serialization provider cannot be found
148 private void registerSerProviders(String serializationProvider) throws ClassNotFoundException {
149 String providers = (serializationProvider == null || serializationProvider.isEmpty()
150 ? JERSEY_DEFAULT_SERIALIZATION_PROVIDER : serializationProvider);
151 for (String prov : providers.split(",")) {
152 this.client.register(Class.forName(prov));
157 public Response get(String path) {
158 if (path != null && !path.isEmpty()) {
159 return this.client.target(this.baseUrl).path(path).request().get();
161 return this.client.target(this.baseUrl).request().get();
166 public Response get() {
167 return this.client.target(this.baseUrl).request().get();
171 public Response put(String path, Entity<?> entity, Map<String, Object> headers) {
172 return getBuilder(path, headers).put(entity);
176 public Response post(String path, Entity<?> entity, Map<String, Object> headers) {
177 return getBuilder(path, headers).post(entity);
181 public Response delete(String path, Map<String, Object> headers) {
182 return getBuilder(path, headers).delete();
186 public boolean start() {
191 public boolean stop() {
196 public void shutdown() {
197 synchronized (this) {
203 } catch (Exception e) {
204 logger.warn("{}: cannot close because of {}", this, e.getMessage(), e);
209 public synchronized boolean isAlive() {
214 public String getName() {
219 public boolean isHttps() {
224 public boolean isSelfSignedCerts() {
225 return selfSignedCerts;
229 public String getHostname() {
234 public int getPort() {
239 public String getBasePath() {
244 public String getUserName() {
251 public String getPassword() {
256 public String getBaseUrl() {
261 public String toString() {
262 StringBuilder builder = new StringBuilder();
263 builder.append("JerseyClient [name=");
264 builder.append(name);
265 builder.append(", https=");
266 builder.append(https);
267 builder.append(", selfSignedCerts=");
268 builder.append(selfSignedCerts);
269 builder.append(", hostname=");
270 builder.append(hostname);
271 builder.append(", port=");
272 builder.append(port);
273 builder.append(", basePath=");
274 builder.append(basePath);
275 builder.append(", userName=");
276 builder.append(userName);
277 builder.append(", password=");
278 builder.append(password);
279 builder.append(", client=");
280 builder.append(client);
281 builder.append(", baseUrl=");
282 builder.append(baseUrl);
283 builder.append(", alive=");
284 builder.append(alive);
286 return builder.toString();
289 private Builder getBuilder(String path, Map<String, Object> headers) {
290 Builder builder = this.client.target(this.baseUrl).path(path).request();
291 for (Entry<String, Object> header : headers.entrySet()) {
292 builder.header(header.getKey(), header.getValue());