1ed3ec9ff2d30702df2787015974fe760732d66c
[so.git] / adapters / etsi-sol003-adapter / etsi-sol003-lcm / etsi-sol003-lcm-adapter / src / main / java / org / onap / so / adapters / etsisol003adapter / lcm / extclients / vnfm / VnfmServiceProviderConfiguration.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.lcm.extclients.vnfm;
22
23 import java.io.IOException;
24 import java.security.KeyManagementException;
25 import java.security.KeyStore;
26 import java.security.KeyStoreException;
27 import java.security.NoSuchAlgorithmException;
28 import java.security.UnrecoverableKeyException;
29 import java.security.cert.CertificateException;
30 import java.util.Map;
31 import java.util.UUID;
32 import java.util.concurrent.ConcurrentHashMap;
33 import javax.net.ssl.SSLContext;
34 import org.apache.commons.lang3.StringUtils;
35 import org.apache.http.client.HttpClient;
36 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
37 import org.apache.http.impl.client.HttpClients;
38 import org.apache.http.ssl.SSLContextBuilder;
39 import org.onap.aai.domain.yang.EsrSystemInfo;
40 import org.onap.aai.domain.yang.EsrVnfm;
41 import org.onap.so.adapters.etsi.sol003.adapter.common.configuration.AbstractServiceProviderConfiguration;
42 import org.onap.so.adapters.etsisol003adapter.lcm.v1.JSON;
43 import org.onap.so.configuration.rest.BasicHttpHeadersProvider;
44 import org.onap.so.rest.service.HttpRestServiceProvider;
45 import org.onap.so.rest.service.HttpRestServiceProviderImpl;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48 import org.springframework.beans.factory.annotation.Autowired;
49 import org.springframework.beans.factory.annotation.Qualifier;
50 import org.springframework.beans.factory.annotation.Value;
51 import org.springframework.context.annotation.Configuration;
52 import org.springframework.core.io.Resource;
53 import org.springframework.http.client.BufferingClientHttpRequestFactory;
54 import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
55 import org.springframework.security.oauth2.client.OAuth2RestTemplate;
56 import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails;
57 import org.springframework.web.client.RestTemplate;
58 import com.google.gson.Gson;
59
60 /**
61  * Configures the HttpRestServiceProvider for REST call to a VNFM.
62  */
63 @Configuration
64 public class VnfmServiceProviderConfiguration extends AbstractServiceProviderConfiguration {
65
66     private static final Logger logger = LoggerFactory.getLogger(VnfmServiceProviderConfiguration.class);
67     private final Map<String, HttpRestServiceProvider> mapOfVnfmIdToHttpRestServiceProvider = new ConcurrentHashMap<>();
68
69     @Value("${http.client.ssl.trust-store:#{null}}")
70     private Resource trustStore;
71     @Value("${http.client.ssl.trust-store-password:#{null}}")
72     private String trustStorePassword;
73
74     @Value("${server.ssl.key-store:#{null}}")
75     private Resource keyStoreResource;
76     @Value("${server.ssl.key--store-password:#{null}}")
77     private String keyStorePassword;
78
79     /**
80      * This property is only intended to be temporary until the AAI schema is updated to support setting the endpoint
81      */
82     @Value("${vnfmadapter.temp.vnfm.oauth.endpoint:#{null}}")
83     private String oauthEndpoint;
84
85     @Qualifier(VnfmRestTemplateConfiguration.SOL003_LCM_REST_TEMPLATE)
86     @Autowired
87     private RestTemplate defaultRestTemplate;
88
89     public HttpRestServiceProvider getHttpRestServiceProvider(final EsrVnfm vnfm) {
90         if (!mapOfVnfmIdToHttpRestServiceProvider.containsKey(vnfm.getVnfmId())) {
91             mapOfVnfmIdToHttpRestServiceProvider.put(vnfm.getVnfmId(), createHttpRestServiceProvider(vnfm));
92         }
93         return mapOfVnfmIdToHttpRestServiceProvider.get(vnfm.getVnfmId());
94     }
95
96     private HttpRestServiceProvider createHttpRestServiceProvider(final EsrVnfm vnfm) {
97         final RestTemplate restTemplate = createRestTemplate(vnfm);
98         setGsonMessageConverter(restTemplate);
99         if (trustStore != null) {
100             setTrustStore(restTemplate);
101         }
102         return new HttpRestServiceProviderImpl(restTemplate, new BasicHttpHeadersProvider().getHttpHeaders());
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 setTrustStore(final RestTemplate restTemplate) {
131         SSLContext sslContext;
132         try {
133             if (keyStoreResource != null) {
134                 final KeyStore keystore = KeyStore.getInstance("pkcs12");
135                 keystore.load(keyStoreResource.getInputStream(), keyStorePassword.toCharArray());
136                 sslContext =
137                         new SSLContextBuilder().loadTrustMaterial(trustStore.getURL(), trustStorePassword.toCharArray())
138                                 .loadKeyMaterial(keystore, keyStorePassword.toCharArray()).build();
139             } else {
140                 sslContext = new SSLContextBuilder()
141                         .loadTrustMaterial(trustStore.getURL(), trustStorePassword.toCharArray()).build();
142             }
143             logger.info("Setting truststore: {}", trustStore.getURL());
144             final SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext);
145             final HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
146             final HttpComponentsClientHttpRequestFactory factory =
147                     new HttpComponentsClientHttpRequestFactory(httpClient);
148             restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(factory));
149         } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException | CertificateException
150                 | IOException | UnrecoverableKeyException exception) {
151             logger.error("Error reading truststore, TLS connection to VNFM will fail.", exception);
152         }
153     }
154
155     @Override
156     protected Gson getGson() {
157         return new JSON().getGson();
158     }
159
160 }