a604f9a6b976a4f5044e26ec7fdedf2bea06bd89
[so.git] /
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.vnfm;
22
23 import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE;
24 import com.google.gson.Gson;
25 import java.io.IOException;
26 import java.security.KeyManagementException;
27 import java.security.KeyStoreException;
28 import java.security.NoSuchAlgorithmException;
29 import java.security.cert.CertificateException;
30 import java.util.Iterator;
31 import java.util.ListIterator;
32 import java.util.Map;
33 import java.util.UUID;
34 import java.util.concurrent.ConcurrentHashMap;
35 import javax.net.ssl.SSLContext;
36 import org.apache.commons.lang3.StringUtils;
37 import org.apache.http.client.HttpClient;
38 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
39 import org.apache.http.impl.client.HttpClients;
40 import org.apache.http.ssl.SSLContextBuilder;
41 import org.onap.aai.domain.yang.EsrSystemInfo;
42 import org.onap.aai.domain.yang.EsrVnfm;
43 import org.onap.so.adapters.vnfmadapter.extclients.vnfm.lcn.JSON;
44 import org.onap.so.configuration.rest.BasicHttpHeadersProvider;
45 import org.onap.so.logging.jaxrs.filter.SpringClientFilter;
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.Configuration;
54 import org.springframework.core.io.Resource;
55 import org.springframework.http.client.ClientHttpRequestInterceptor;
56 import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
57 import org.springframework.http.converter.HttpMessageConverter;
58 import org.springframework.http.converter.json.GsonHttpMessageConverter;
59 import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
60 import org.springframework.security.oauth2.client.OAuth2RestTemplate;
61 import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails;
62 import org.springframework.web.client.RestTemplate;
63
64 /**
65  * Configures the HttpRestServiceProvider for REST call to a VNFM.
66  */
67 @Configuration
68 public class VnfmServiceProviderConfiguration {
69
70     private static final Logger logger = LoggerFactory.getLogger(VnfmServiceProviderConfiguration.class);
71     private Map<String, HttpRestServiceProvider> mapOfVnfmIdToHttpRestServiceProvider = new ConcurrentHashMap<>();
72
73     @Value("${http.client.ssl.trust-store:#{null}}")
74     private Resource trustStore;
75     @Value("${http.client.ssl.trust-store-password:#{null}}")
76     private String trustPassword;
77
78     /**
79      * This property is only intended to be temporary until the AAI schema is updated to support setting the endpoint
80      */
81     @Value("${vnfmadapter.temp.vnfm.oauth.endpoint:#{null}}")
82     private String oauthEndpoint;
83
84     @Qualifier(CONFIGURABLE_REST_TEMPLATE)
85     @Autowired()
86     private RestTemplate defaultRestTemplate;
87
88     public HttpRestServiceProvider getHttpRestServiceProvider(final EsrVnfm vnfm) {
89         if (!mapOfVnfmIdToHttpRestServiceProvider.containsKey(vnfm.getVnfmId())) {
90             mapOfVnfmIdToHttpRestServiceProvider.put(vnfm.getVnfmId(), createHttpRestServiceProvider(vnfm));
91         }
92         return mapOfVnfmIdToHttpRestServiceProvider.get(vnfm.getVnfmId());
93     }
94
95     private HttpRestServiceProvider createHttpRestServiceProvider(final EsrVnfm vnfm) {
96         final RestTemplate restTemplate = createRestTemplate(vnfm);
97         setGsonMessageConverter(restTemplate);
98         if (trustStore != null) {
99             setTrustStore(restTemplate);
100         }
101         removeSpringClientFilter(restTemplate);
102         return new HttpRestServiceProviderImpl(restTemplate, new BasicHttpHeadersProvider());
103     }
104
105     private RestTemplate createRestTemplate(final EsrVnfm vnfm) {
106         if (vnfm != null) {
107             for (final EsrSystemInfo esrSystemInfo : vnfm.getEsrSystemInfoList().getEsrSystemInfo()) {
108                 if (!StringUtils.isEmpty(esrSystemInfo.getUserName())
109                         && !StringUtils.isEmpty(esrSystemInfo.getPassword())) {
110                     return createOAuth2RestTemplate(esrSystemInfo);
111                 }
112             }
113         }
114         return defaultRestTemplate;
115     }
116
117     private OAuth2RestTemplate createOAuth2RestTemplate(final EsrSystemInfo esrSystemInfo) {
118         logger.debug("Getting OAuth2RestTemplate ...");
119         final ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails();
120         resourceDetails.setId(UUID.randomUUID().toString());
121         resourceDetails.setClientId(esrSystemInfo.getUserName());
122         resourceDetails.setClientSecret(esrSystemInfo.getPassword());
123         resourceDetails.setAccessTokenUri(
124                 oauthEndpoint == null ? esrSystemInfo.getServiceUrl().replace("vnflcm/v1", "oauth/token")
125                         : oauthEndpoint);
126         resourceDetails.setGrantType("client_credentials");
127         return new OAuth2RestTemplate(resourceDetails);
128     }
129
130     private void setGsonMessageConverter(final RestTemplate restTemplate) {
131         final Iterator<HttpMessageConverter<?>> iterator = restTemplate.getMessageConverters().iterator();
132         while (iterator.hasNext()) {
133             if (iterator.next() instanceof MappingJackson2HttpMessageConverter) {
134                 iterator.remove();
135             }
136         }
137         final Gson gson = new JSON().getGson();
138         restTemplate.getMessageConverters().add(new GsonHttpMessageConverter(gson));
139     }
140
141     private void setTrustStore(final RestTemplate restTemplate) {
142         SSLContext sslContext;
143         try {
144             sslContext =
145                     new SSLContextBuilder().loadTrustMaterial(trustStore.getURL(), trustPassword.toCharArray()).build();
146             logger.info("Setting truststore: {}", trustStore.getURL());
147             final SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext);
148             final HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
149             final HttpComponentsClientHttpRequestFactory factory =
150                     new HttpComponentsClientHttpRequestFactory(httpClient);
151             restTemplate.setRequestFactory(factory);
152         } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException | CertificateException
153                 | IOException exception) {
154             logger.error("Error reading truststore, TLS connection to VNFM will fail.", exception);
155         }
156     }
157
158     private void removeSpringClientFilter(final RestTemplate restTemplate) {
159         ListIterator<ClientHttpRequestInterceptor> interceptorIterator = restTemplate.getInterceptors().listIterator();
160         while (interceptorIterator.hasNext()) {
161             if (interceptorIterator.next() instanceof SpringClientFilter) {
162                 interceptorIterator.remove();
163             }
164         }
165     }
166
167 }