Support disabling host verification in naming service
[ccsdk/apps.git] / ms / neng / src / main / java / org / onap / ccsdk / apps / ms / neng / service / extinf / impl / PolicyFinderServiceImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : CCSDK.apps
4  * ================================================================================
5  * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright (C) 2018 IBM.
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.ccsdk.apps.ms.neng.service.extinf.impl;
24
25 import com.fasterxml.jackson.core.type.TypeReference;
26 import com.fasterxml.jackson.databind.ObjectMapper;
27 import java.net.URI;
28 import java.security.cert.X509Certificate;
29 import java.util.ArrayList;
30 import java.util.HashMap;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.UUID;
34 import java.util.logging.Logger;
35 import javax.net.ssl.HostnameVerifier;
36 import javax.net.ssl.SSLContext;
37 import javax.net.ssl.SSLSession;
38 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
39 import org.apache.http.conn.ssl.TrustStrategy;
40 import org.apache.http.impl.client.CloseableHttpClient;
41 import org.apache.http.impl.client.HttpClients;
42 import org.onap.ccsdk.apps.ms.neng.core.exceptions.NengException;
43 import org.onap.ccsdk.apps.ms.neng.core.policy.PolicyFinder;
44 import org.onap.ccsdk.apps.ms.neng.core.resource.model.GetConfigRequest;
45 import org.onap.ccsdk.apps.ms.neng.core.resource.model.GetConfigRequestV2;
46 import org.onap.ccsdk.apps.ms.neng.core.resource.model.GetConfigResponse;
47 import org.onap.ccsdk.apps.ms.neng.core.rs.interceptors.PolicyManagerAuthorizationInterceptor;
48 import org.onap.ccsdk.apps.ms.neng.extinf.props.PolicyManagerProps;
49 import org.onap.ccsdk.sli.core.utils.common.AcceptIpAddressHostNameVerifier;
50 import org.springframework.beans.factory.annotation.Autowired;
51 import org.springframework.beans.factory.annotation.Qualifier;
52 import org.springframework.boot.web.client.RestTemplateBuilder;
53 import org.springframework.http.HttpStatus;
54 import org.springframework.http.MediaType;
55 import org.springframework.http.RequestEntity;
56 import org.springframework.http.ResponseEntity;
57 import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
58 import org.springframework.stereotype.Component;
59 import org.springframework.web.client.HttpStatusCodeException;
60 import org.springframework.web.client.RestTemplate;
61
62 /**
63  * Finds policies from policy manager.
64  */
65 @Component
66 @Qualifier("PolicyFinderServiceImpl")
67 public class PolicyFinderServiceImpl implements PolicyFinder {
68     private static Logger log = Logger.getLogger(PolicyFinderServiceImpl.class.getName());
69
70     @Autowired PolicyManagerProps policManProps;
71     @Autowired @Qualifier("policyMgrRestTempBuilder") RestTemplateBuilder policyMgrRestTempBuilder;
72     @Autowired PolicyManagerAuthorizationInterceptor authInt;
73     RestTemplate restTemplate;
74
75     /**
76      * Find policy with the given name from policy manager.
77      */
78     @Override
79     public Map<String, Object> findPolicy(String policyName) throws Exception {
80         Object response = getConfig(policyName).getResponse();
81         if (response instanceof List) {
82             @SuppressWarnings("unchecked")
83             List<Map<String, Object>> policyList = (List<Map<String, Object>>) response;
84             return ((!policyList.isEmpty()) ? policyList.get(0) : null);
85         } else {
86             return null;
87         }
88     }
89
90     protected boolean shouldUsePolicyV2 () {
91         String version = policManProps.getVersion();
92         log.info("Policy Manager Version - " + version );
93
94         try {
95             int vnum = Integer.parseInt(version);
96             if ( vnum <= 1 ) {
97                 return false;
98             }
99         } catch ( Exception e ) {
100             return true;
101         }
102        
103         return true;
104     }
105
106     GetConfigResponse getConfig(String policyName) throws Exception {
107
108         Object request;
109         if ( shouldUsePolicyV2() ) {
110            GetConfigRequestV2 req = new GetConfigRequestV2();
111
112            req.setOnapName("SDNC");
113            req.setOnapComponent("CCSDK");
114            req.setOnapInstance("CCSDK-ms-neng");
115            req.setRequestId( UUID.randomUUID().toString() );
116            req.setAction("naming");
117
118            Map<String,Object> resource = new HashMap<>();
119            resource.put("policy-id", policyName);
120            req.setResource(resource);
121
122            request = req;
123         } else {
124            GetConfigRequest getConfigRequest = new GetConfigRequest();
125
126            getConfigRequest.setPolicyName(policyName);
127
128            request = getConfigRequest;
129         }
130
131         ObjectMapper reqmapper = new ObjectMapper();
132         String reqStr = reqmapper.writeValueAsString(request);
133         log.info("Request  - " + reqStr);
134
135         return (makeOutboundCall( policyName, request, GetConfigResponse.class));
136     }
137
138     <T, R> GetConfigResponse makeOutboundCall( String policyName, T request, Class<R> response) throws Exception {
139         log.info("Policy Manager  - " + policManProps.getUrl());
140
141         RequestEntity<T> re = RequestEntity.post(new URI(policManProps.getUrl()))
142                         .accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON).body(request);
143         try {
144             ResponseEntity<Object> resp = getRestTemplate(policManProps.getDisableHostVerification()).exchange(re, Object.class);
145             if (HttpStatus.OK.equals(resp.getStatusCode())) {
146                 ObjectMapper objectmapper = new ObjectMapper();
147                 String bodyStr = objectmapper.writeValueAsString(resp.getBody());
148                 return handleResponse( bodyStr );
149             }
150         } catch (HttpStatusCodeException e) {
151             handleError(e);
152         }
153         throw new NengException("Error while retrieving policy " + policyName +" from policy manager.");
154     }
155
156     GetConfigResponse handleResponse ( String body ) throws Exception {
157         log.info(body);
158
159         ObjectMapper objectmapper = new ObjectMapper();
160         GetConfigResponse getConfigResp = new GetConfigResponse();
161         try {
162             Map<Object, Object> respObj = objectmapper.readValue( body, new TypeReference<Map<Object, Object>>() {});
163             List<Map<Object, Object>> respList = transformConfigObjectV2(objectmapper, respObj);
164             getConfigResp.setResponse(respList);
165         } catch ( Exception e ) {
166             List<Map<Object, Object>> respObj = objectmapper.readValue( body, new TypeReference<List<Map<Object, Object>>>() {});
167             transformConfigObject(objectmapper, respObj);
168             getConfigResp.setResponse(respObj);
169         }
170         return getConfigResp;
171     }
172
173     void handleError(HttpStatusCodeException e) throws Exception {
174         String respString = e.getResponseBodyAsString();
175         log.info(respString);
176         if (e.getStatusText() != null) {
177             log.info(e.getStatusText());
178         }
179         if (e.getResponseHeaders() != null && e.getResponseHeaders().toSingleValueMap() != null) {
180             log.info(e.getResponseHeaders().toSingleValueMap().toString());
181         }
182         if (HttpStatus.NOT_FOUND.equals(e.getStatusCode()) && (respString != null && respString.contains(""))) {
183             throw new NengException("Policy not found in policy manager.");
184         }
185         throw new NengException("Error while retrieving policy from policy manager.");
186     }
187
188     /**
189      * Transforms the policy-V2 response in a form compatible with V1.
190      */
191     List<Map<Object,Object>>  transformConfigObjectV2(ObjectMapper objectmapper, Map<Object, Object> respObj) throws Exception {
192         List<Map<Object,Object>> policyList = new ArrayList<>();
193
194         Object policies = respObj.get("policies");
195         if (policies != null && policies instanceof Map<?, ?> ) {
196             Map<Object, Object> policiesMap = (Map<Object,Object>)policies;
197             if ( policiesMap.size() > 0 ) {
198                 Object policy = policiesMap.entrySet().iterator().next().getValue();
199                 if ( policy != null && policy instanceof Map<?, ?> ) {
200                     Map<Object, Object> thePolicyMap = (Map<Object,Object>)policy;
201                     Object properties = thePolicyMap.get("properties");
202                     if ( properties != null && properties instanceof Map<?, ?> ) {
203                         Map<Object, Object> propertiesMap = (Map<Object,Object>)properties;
204
205                         Map<Object,Object> top = new HashMap<>();
206                         Map<Object,Object> config = new HashMap<>();
207                         top.put("config", config );
208                         config.put("content", propertiesMap );
209                         policyList.add(top);
210                     } 
211                 } 
212             } 
213         }
214         return policyList;
215     }
216
217
218     /**
219      * Transforms the 'config' element (which is received as a JSON string) to a map like a JSON object.
220      */
221     void transformConfigObject(ObjectMapper objectmapper, List<Map<Object, Object>> respObj) throws Exception {
222         Object configElement = respObj.get(0).get("config");
223         if (configElement instanceof String) {
224             Map<Object, Object> obj = objectmapper.readValue(configElement.toString(),
225                             new TypeReference<Map<Object, Object>>() {});
226             respObj.get(0).put("config", obj);
227         }
228     }
229
230     RestTemplate getRestTemplate(Boolean disableHostVerification) throws Exception {
231         if (restTemplate != null) {
232             return restTemplate;
233         }
234         TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
235         SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
236                         .loadTrustMaterial(null, acceptingTrustStrategy).build();
237         HostnameVerifier verifier = new AcceptIpAddressHostNameVerifier(disableHostVerification);
238         SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, verifier);
239         CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
240         HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
241         requestFactory.setHttpClient(httpClient);
242         restTemplate = new RestTemplate(requestFactory);
243         restTemplate.getInterceptors().add(getAuthInt());
244         return restTemplate;
245     }
246
247     RestTemplateBuilder getPolicyMgrRestTempBuilder() {
248         return policyMgrRestTempBuilder;
249     }
250
251     void setPolicyMgrRestTempBuilder(RestTemplateBuilder policyMgrRestTempBuilder) {
252         this.policyMgrRestTempBuilder = policyMgrRestTempBuilder;
253     }
254
255     PolicyManagerAuthorizationInterceptor getAuthInt() {
256         return authInt;
257     }
258
259     void setAuthInt(PolicyManagerAuthorizationInterceptor authInt) {
260         this.authInt = authInt;
261     }
262 }