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