Add HTTPS support between SOL003 Adapter and ETSI
[so.git] / adapters / mso-vnfm-adapter / mso-vnfm-etsi-adapter / src / main / java / org / onap / so / adapters / vnfmadapter / extclients / etsicatalog / EtsiCatalogServiceProviderConfiguration.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019 Nordix Foundation.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.adapters.vnfmadapter.extclients.etsicatalog;
22
23 import java.io.IOException;
24 import java.security.KeyManagementException;
25 import java.security.KeyStoreException;
26 import java.security.NoSuchAlgorithmException;
27 import java.security.cert.CertificateException;
28 import java.util.concurrent.TimeUnit;
29 import javax.net.ssl.HostnameVerifier;
30 import javax.net.ssl.SSLContext;
31 import javax.net.ssl.SSLSession;
32 import org.apache.http.client.config.RequestConfig;
33 import org.apache.http.config.Registry;
34 import org.apache.http.config.RegistryBuilder;
35 import org.apache.http.conn.socket.ConnectionSocketFactory;
36 import org.apache.http.conn.socket.PlainConnectionSocketFactory;
37 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
38 import org.apache.http.impl.client.HttpClientBuilder;
39 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
40 import org.apache.http.ssl.SSLContextBuilder;
41 import org.onap.logging.filter.spring.SpringClientPayloadFilter;
42 import org.onap.so.adapters.vnfmadapter.extclients.AbstractServiceProviderConfiguration;
43 import org.onap.so.configuration.rest.BasicHttpHeadersProvider;
44 import org.onap.so.configuration.rest.HttpClientConnectionConfiguration;
45 import org.onap.so.logging.jaxrs.filter.SOSpringClientFilter;
46 import org.onap.so.rest.service.HttpRestServiceProvider;
47 import org.onap.so.rest.service.HttpRestServiceProviderImpl;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50 import org.springframework.beans.factory.annotation.Autowired;
51 import org.springframework.beans.factory.annotation.Qualifier;
52 import org.springframework.beans.factory.annotation.Value;
53 import org.springframework.context.annotation.Bean;
54 import org.springframework.context.annotation.Configuration;
55 import org.springframework.core.io.Resource;
56 import org.springframework.http.client.BufferingClientHttpRequestFactory;
57 import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
58 import org.springframework.web.client.RestTemplate;
59
60 /**
61  * Configures the HttpRestServiceProvider to make REST calls to the ETSI Catalog Manager
62  * 
63  * @author gareth.roper@est.tech
64  */
65
66 @Configuration
67 public class EtsiCatalogServiceProviderConfiguration extends AbstractServiceProviderConfiguration {
68
69     public static final String ETSI_CATALOG_REST_TEMPLATE_BEAN = "etsiCatalogRestTemplate";
70
71     public static final String ETSI_CATALOG_SERVICE_PROVIDER_BEAN = "etsiCatalogServiceProvider";
72
73     private final static Logger LOGGER = LoggerFactory.getLogger(EtsiCatalogServiceProviderConfiguration.class);
74
75     private final HttpClientConnectionConfiguration clientConnectionConfiguration;
76
77     @Value("${etsi-catalog-manager.http.client.ssl.trust-store:#{null}}")
78     private Resource trustStore;
79     @Value("${etsi-catalog-manager.http.client.ssl.trust-store-password:#{null}}")
80     private String trustStorePassword;
81
82     @Autowired
83     public EtsiCatalogServiceProviderConfiguration(
84             final HttpClientConnectionConfiguration clientConnectionConfiguration) {
85         this.clientConnectionConfiguration = clientConnectionConfiguration;
86     }
87
88     @Bean
89     @Qualifier(ETSI_CATALOG_REST_TEMPLATE_BEAN)
90     public RestTemplate etsiCatalogRestTemplate() {
91         final RestTemplate restTemplate = new RestTemplate();
92         restTemplate.getInterceptors().add(new SOSpringClientFilter());
93         restTemplate.getInterceptors().add((new SpringClientPayloadFilter()));
94         return restTemplate;
95     }
96
97     @Bean
98     @Qualifier(ETSI_CATALOG_SERVICE_PROVIDER_BEAN)
99     public HttpRestServiceProvider etsiCatalogHttpRestServiceProvider(
100             @Qualifier(ETSI_CATALOG_REST_TEMPLATE_BEAN) final RestTemplate restTemplate) {
101         setGsonMessageConverter(restTemplate);
102
103         final HttpClientBuilder httpClientBuilder = getHttpClientBuilder();
104         if (trustStore != null) {
105             try {
106                 LOGGER.debug("Setting up HttpComponentsClientHttpRequestFactory with SSL Context");
107                 LOGGER.debug("Setting client trust-store: {}", trustStore.getURL());
108                 LOGGER.debug("Creating SSLConnectionSocketFactory with AllowAllHostsVerifier ... ");
109                 final SSLContext sslContext = new SSLContextBuilder()
110                         .loadTrustMaterial(trustStore.getURL(), trustStorePassword.toCharArray()).build();
111                 final SSLConnectionSocketFactory sslConnectionSocketFactory =
112                         new SSLConnectionSocketFactory(sslContext, AllowAllHostsVerifier.INSTANCE);
113                 httpClientBuilder.setSSLSocketFactory(sslConnectionSocketFactory);
114                 final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
115                         .<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE)
116                         .register("https", sslConnectionSocketFactory).build();
117
118                 httpClientBuilder.setConnectionManager(getConnectionManager(socketFactoryRegistry));
119             } catch (final KeyManagementException | NoSuchAlgorithmException | KeyStoreException | CertificateException
120                     | IOException exception) {
121                 LOGGER.error("Error reading truststore, TLS connection will fail.", exception);
122             }
123
124         } else {
125             LOGGER.debug("Setting connection manager without SSL ConnectionSocketFactory ...");
126             httpClientBuilder.setConnectionManager(getConnectionManager());
127         }
128
129         final HttpComponentsClientHttpRequestFactory factory =
130                 new HttpComponentsClientHttpRequestFactory(httpClientBuilder.build());
131         restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(factory));
132
133         return new HttpRestServiceProviderImpl(restTemplate, new BasicHttpHeadersProvider().getHttpHeaders());
134     }
135
136     private PoolingHttpClientConnectionManager getConnectionManager(
137             final Registry<ConnectionSocketFactory> socketFactoryRegistry) {
138         return new PoolingHttpClientConnectionManager(socketFactoryRegistry, null, null, null,
139                 clientConnectionConfiguration.getTimeToLiveInMins(), TimeUnit.MINUTES);
140     }
141
142     private PoolingHttpClientConnectionManager getConnectionManager() {
143         return new PoolingHttpClientConnectionManager(clientConnectionConfiguration.getTimeToLiveInMins(),
144                 TimeUnit.MINUTES);
145     }
146
147     private HttpClientBuilder getHttpClientBuilder() {
148         return HttpClientBuilder.create().setMaxConnPerRoute(clientConnectionConfiguration.getMaxConnectionsPerRoute())
149                 .setMaxConnTotal(clientConnectionConfiguration.getMaxConnections())
150                 .setDefaultRequestConfig(getRequestConfig());
151     }
152
153     private RequestConfig getRequestConfig() {
154         return RequestConfig.custom().setSocketTimeout(clientConnectionConfiguration.getSocketTimeOutInMiliSeconds())
155                 .setConnectTimeout(clientConnectionConfiguration.getConnectionTimeOutInMilliSeconds()).build();
156     }
157
158     private static final class AllowAllHostsVerifier implements HostnameVerifier {
159
160         private static final AllowAllHostsVerifier INSTANCE = new AllowAllHostsVerifier();
161
162         @Override
163         public boolean verify(final String hostname, final SSLSession session) {
164             LOGGER.debug("Skipping hostname verification ...");
165             return true;
166         }
167
168     }
169
170 }