Fixed MSB Registration Failure
[holmes/common.git] / holmes-actions / src / main / java / org / onap / holmes / common / utils / JerseyClient.java
1 /**
2  * Copyright 2020 ZTE Corporation.
3  * <p>
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  * <p>
8  * http://www.apache.org/licenses/LICENSE-2.0
9  * <p>
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.onap.holmes.common.utils;
18
19 import org.glassfish.jersey.client.ClientConfig;
20 import org.jvnet.hk2.annotations.Service;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
23
24 import javax.annotation.PostConstruct;
25 import javax.net.ssl.SSLContext;
26 import javax.net.ssl.TrustManager;
27 import javax.net.ssl.X509TrustManager;
28 import javax.ws.rs.client.Client;
29 import javax.ws.rs.client.ClientBuilder;
30 import java.security.KeyManagementException;
31 import java.security.NoSuchAlgorithmException;
32 import java.security.cert.X509Certificate;
33
34 @Service
35 public class JerseyClient {
36     private static Logger logger = LoggerFactory.getLogger(JerseyClient.class);
37     public static final String PROTOCOL_HTTP = "http";
38     public static final String PROTOCOL_HTTPS = "https";
39     private SSLContext sslcontext = null;
40
41     @PostConstruct
42     private void init() {
43         try {
44             sslcontext = SSLContext.getInstance("TLS");
45             sslcontext.init(null, new TrustManager[]{new X509TrustManager() {
46                 public void checkClientTrusted(X509Certificate[] arg0, String arg1) {
47                 }
48
49                 public void checkServerTrusted(X509Certificate[] arg0, String arg1) {
50                 }
51
52                 public X509Certificate[] getAcceptedIssuers() {
53                     return new X509Certificate[0];
54                 }
55             }}, new java.security.SecureRandom());
56         } catch (NoSuchAlgorithmException | KeyManagementException e) {
57             logger.error("Failed to initialize the SSLContext instance!", e);
58         }
59     }
60
61     public Client httpClient() {
62         return ClientBuilder.newClient(new ClientConfig());
63     }
64
65     public Client httpsClient() {
66         return ClientBuilder.newBuilder()
67                 .sslContext(sslcontext)
68                 .hostnameVerifier((s1, s2) -> true)
69                 .build();
70     }
71
72     public Client client(boolean isHttps) {
73         return isHttps ? httpsClient() : httpClient();
74     }
75 }