1ff3672df957c4ce87ac7349bfe85ed3200ff1b3
[so.git] / adapters / etsi-sol003-adapter / etsi-sol003-pkgm / etsi-sol003-pkgm-adapter / src / main / java / org / onap / so / adapters / etsisol003adapter / pkgm / 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.etsisol003adapter.pkgm.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.etsi.sol003.adapter.common.configuration.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 import com.google.gson.Gson;
60
61 /**
62  * Configures the HttpRestServiceProvider to make REST calls to the ETSI Catalog Manager
63  * 
64  * @author gareth.roper@est.tech
65  */
66
67 @Configuration
68 public class EtsiCatalogServiceProviderConfiguration extends AbstractServiceProviderConfiguration {
69
70     public static final String ETSI_CATALOG_REST_TEMPLATE_BEAN = "etsiCatalogRestTemplate";
71
72     public static final String ETSI_CATALOG_SERVICE_PROVIDER_BEAN = "etsiCatalogServiceProvider";
73
74     private final static Logger LOGGER = LoggerFactory.getLogger(EtsiCatalogServiceProviderConfiguration.class);
75
76     private final HttpClientConnectionConfiguration clientConnectionConfiguration;
77
78     @Value("${etsi-catalog-manager.http.client.ssl.trust-store:#{null}}")
79     private Resource trustStore;
80     @Value("${etsi-catalog-manager.http.client.ssl.trust-store-password:#{null}}")
81     private String trustStorePassword;
82
83     @Autowired
84     public EtsiCatalogServiceProviderConfiguration(
85             final HttpClientConnectionConfiguration clientConnectionConfiguration) {
86         this.clientConnectionConfiguration = clientConnectionConfiguration;
87     }
88
89     @Bean
90     @Qualifier(ETSI_CATALOG_REST_TEMPLATE_BEAN)
91     public RestTemplate etsiCatalogRestTemplate() {
92         final RestTemplate restTemplate = new RestTemplate();
93         restTemplate.getInterceptors().add(new SOSpringClientFilter());
94         restTemplate.getInterceptors().add((new SpringClientPayloadFilter()));
95         return restTemplate;
96     }
97
98     @Bean
99     @Qualifier(ETSI_CATALOG_SERVICE_PROVIDER_BEAN)
100     public HttpRestServiceProvider etsiCatalogHttpRestServiceProvider(
101             @Qualifier(ETSI_CATALOG_REST_TEMPLATE_BEAN) final RestTemplate restTemplate) {
102         setGsonMessageConverter(restTemplate);
103
104         final HttpClientBuilder httpClientBuilder = getHttpClientBuilder();
105         if (trustStore != null) {
106             try {
107                 LOGGER.debug("Setting up HttpComponentsClientHttpRequestFactory with SSL Context");
108                 LOGGER.debug("Setting client trust-store: {}", trustStore.getURL());
109                 LOGGER.debug("Creating SSLConnectionSocketFactory with AllowAllHostsVerifier ... ");
110                 final SSLContext sslContext = new SSLContextBuilder()
111                         .loadTrustMaterial(trustStore.getURL(), trustStorePassword.toCharArray()).build();
112                 final SSLConnectionSocketFactory sslConnectionSocketFactory =
113                         new SSLConnectionSocketFactory(sslContext, AllowAllHostsVerifier.INSTANCE);
114                 httpClientBuilder.setSSLSocketFactory(sslConnectionSocketFactory);
115                 final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
116                         .<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE)
117                         .register("https", sslConnectionSocketFactory).build();
118
119                 httpClientBuilder.setConnectionManager(getConnectionManager(socketFactoryRegistry));
120             } catch (final KeyManagementException | NoSuchAlgorithmException | KeyStoreException | CertificateException
121                     | IOException exception) {
122                 LOGGER.error("Error reading truststore, TLS connection will fail.", exception);
123             }
124
125         } else {
126             LOGGER.debug("Setting connection manager without SSL ConnectionSocketFactory ...");
127             httpClientBuilder.setConnectionManager(getConnectionManager());
128         }
129
130         final HttpComponentsClientHttpRequestFactory factory =
131                 new HttpComponentsClientHttpRequestFactory(httpClientBuilder.build());
132         restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(factory));
133
134         return new HttpRestServiceProviderImpl(restTemplate, new BasicHttpHeadersProvider().getHttpHeaders());
135     }
136
137     private PoolingHttpClientConnectionManager getConnectionManager(
138             final Registry<ConnectionSocketFactory> socketFactoryRegistry) {
139         return new PoolingHttpClientConnectionManager(socketFactoryRegistry, null, null, null,
140                 clientConnectionConfiguration.getTimeToLiveInMins(), TimeUnit.MINUTES);
141     }
142
143     private PoolingHttpClientConnectionManager getConnectionManager() {
144         return new PoolingHttpClientConnectionManager(clientConnectionConfiguration.getTimeToLiveInMins(),
145                 TimeUnit.MINUTES);
146     }
147
148     private HttpClientBuilder getHttpClientBuilder() {
149         return HttpClientBuilder.create().setMaxConnPerRoute(clientConnectionConfiguration.getMaxConnectionsPerRoute())
150                 .setMaxConnTotal(clientConnectionConfiguration.getMaxConnections())
151                 .setDefaultRequestConfig(getRequestConfig());
152     }
153
154     private RequestConfig getRequestConfig() {
155         return RequestConfig.custom().setSocketTimeout(clientConnectionConfiguration.getSocketTimeOutInMiliSeconds())
156                 .setConnectTimeout(clientConnectionConfiguration.getConnectionTimeOutInMilliSeconds()).build();
157     }
158
159     private static final class AllowAllHostsVerifier implements HostnameVerifier {
160
161         private static final AllowAllHostsVerifier INSTANCE = new AllowAllHostsVerifier();
162
163         @Override
164         public boolean verify(final String hostname, final SSLSession session) {
165             LOGGER.debug("Skipping hostname verification ...");
166             return true;
167         }
168
169     }
170
171     @Override
172     protected Gson getGson() {
173         return new JSON().getGson();
174     }
175
176 }