d577dc4bc7999e9ed34878ef9195f9d5f63a4e50
[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.springframework.beans.factory.annotation.Autowired;
50 import org.springframework.beans.factory.annotation.Qualifier;
51 import org.springframework.boot.web.client.RestTemplateBuilder;
52 import org.springframework.http.HttpStatus;
53 import org.springframework.http.MediaType;
54 import org.springframework.http.RequestEntity;
55 import org.springframework.http.ResponseEntity;
56 import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
57 import org.springframework.stereotype.Component;
58 import org.springframework.web.client.HttpStatusCodeException;
59 import org.springframework.web.client.RestTemplate;
60
61 /**
62  * Finds policies from policy manager.
63  */
64 @Component
65 @Qualifier("PolicyFinderServiceImpl")
66 public class PolicyFinderServiceImpl implements PolicyFinder {
67     private static Logger log = Logger.getLogger(PolicyFinderServiceImpl.class.getName());
68
69     @Autowired PolicyManagerProps policManProps;
70     @Autowired @Qualifier("policyMgrRestTempBuilder") RestTemplateBuilder policyMgrRestTempBuilder;
71     @Autowired PolicyManagerAuthorizationInterceptor authInt;
72     RestTemplate restTemplate;
73
74     /**
75      * Find policy with the given name from policy manager.
76      */
77     @Override
78     public Map<String, Object> findPolicy(String policyName) throws Exception {
79         Object response = getConfig(policyName).getResponse();
80         if (response instanceof List) {
81             @SuppressWarnings("unchecked")
82             List<Map<String, Object>> policyList = (List<Map<String, Object>>) response;
83             return ((!policyList.isEmpty()) ? policyList.get(0) : null);
84         } else {
85             return null;
86         }
87     }
88
89     protected boolean shouldUsePolicyV2 () {
90         String version = policManProps.getVersion();
91         log.info("Policy Manager Version - " + version );
92
93         try {
94             int vnum = Integer.parseInt(version);
95             if ( vnum <= 1 ) {
96                 return false;
97             }
98         } catch ( Exception e ) {
99             return true;
100         }
101        
102         return true;
103     }
104
105     GetConfigResponse getConfig(String policyName) throws Exception {
106
107         Object request;
108         if ( shouldUsePolicyV2() ) {
109            GetConfigRequestV2 req = new GetConfigRequestV2();
110
111            req.setOnapName("SDNC");
112            req.setOnapComponent("CCSDK");
113            req.setOnapInstance("CCSDK-ms-neng");
114            req.setRequestId( UUID.randomUUID().toString() );
115            req.setAction("naming");
116
117            Map<String,Object> resource = new HashMap<>();
118            resource.put("policy-id", policyName);
119            req.setResource(resource);
120
121            request = req;
122         } else {
123            GetConfigRequest getConfigRequest = new GetConfigRequest();
124
125            getConfigRequest.setPolicyName(policyName);
126
127            request = getConfigRequest;
128         }
129
130         ObjectMapper reqmapper = new ObjectMapper();
131         String reqStr = reqmapper.writeValueAsString(request);
132         log.info("Request  - " + reqStr);
133
134         return (makeOutboundCall( policyName, request, GetConfigResponse.class));
135     }
136
137     <T, R> GetConfigResponse makeOutboundCall( String policyName, T request, Class<R> response) throws Exception {
138         log.info("Policy Manager  - " + policManProps.getUrl());
139
140         RequestEntity<T> re = RequestEntity.post(new URI(policManProps.getUrl()))
141                         .accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON).body(request);
142         try {
143             ResponseEntity<Object> resp = getRestTemplate().exchange(re, Object.class);
144             if (HttpStatus.OK.equals(resp.getStatusCode())) {
145                 ObjectMapper objectmapper = new ObjectMapper();
146                 String bodyStr = objectmapper.writeValueAsString(resp.getBody());
147                 return handleResponse( bodyStr );
148             }
149         } catch (HttpStatusCodeException e) {
150             handleError(e);
151         }
152         throw new NengException("Error while retrieving policy " + policyName +" from policy manager.");
153     }
154
155     GetConfigResponse handleResponse ( String body ) throws Exception {
156         log.info(body);
157
158         ObjectMapper objectmapper = new ObjectMapper();
159         GetConfigResponse getConfigResp = new GetConfigResponse();
160         try {
161             Map<Object, Object> respObj = objectmapper.readValue( body, new TypeReference<Map<Object, Object>>() {});
162             List<Map<Object, Object>> respList = transformConfigObjectV2(objectmapper, respObj);
163             getConfigResp.setResponse(respList);
164         } catch ( Exception e ) {
165             List<Map<Object, Object>> respObj = objectmapper.readValue( body, new TypeReference<List<Map<Object, Object>>>() {});
166             transformConfigObject(objectmapper, respObj);
167             getConfigResp.setResponse(respObj);
168         }
169         return getConfigResp;
170     }
171
172     void handleError(HttpStatusCodeException e) throws Exception {
173         String respString = e.getResponseBodyAsString();
174         log.info(respString);
175         if (e.getStatusText() != null) {
176             log.info(e.getStatusText());
177         }
178         if (e.getResponseHeaders() != null && e.getResponseHeaders().toSingleValueMap() != null) {
179             log.info(e.getResponseHeaders().toSingleValueMap().toString());
180         }
181         if (HttpStatus.NOT_FOUND.equals(e.getStatusCode()) && (respString != null && respString.contains(""))) {
182             throw new NengException("Policy not found in policy manager.");
183         }
184         throw new NengException("Error while retrieving policy from policy manager.");
185     }
186
187     /**
188      * Transforms the policy-V2 response in a form compatible with V1.
189      */
190     List<Map<Object,Object>>  transformConfigObjectV2(ObjectMapper objectmapper, Map<Object, Object> respObj) throws Exception {
191         List<Map<Object,Object>> policyList = new ArrayList<>();
192
193         Object policies = respObj.get("policies");
194         if (policies != null && policies instanceof Map<?, ?> ) {
195             Map<Object, Object> policiesMap = (Map<Object,Object>)policies;
196             if ( policiesMap.size() > 0 ) {
197                 Object policy = policiesMap.entrySet().iterator().next().getValue();
198                 if ( policy != null && policy instanceof Map<?, ?> ) {
199                     Map<Object, Object> thePolicyMap = (Map<Object,Object>)policy;
200                     Object properties = thePolicyMap.get("properties");
201                     if ( properties != null && properties instanceof Map<?, ?> ) {
202                         Map<Object, Object> propertiesMap = (Map<Object,Object>)properties;
203
204                         Map<Object,Object> top = new HashMap<>();
205                         Map<Object,Object> config = new HashMap<>();
206                         top.put("config", config );
207                         config.put("content", propertiesMap );
208                         policyList.add(top);
209                     } 
210                 } 
211             } 
212         }
213         return policyList;
214     }
215
216
217     /**
218      * Transforms the 'config' element (which is received as a JSON string) to a map like a JSON object.
219      */
220     void transformConfigObject(ObjectMapper objectmapper, List<Map<Object, Object>> respObj) throws Exception {
221         Object configElement = respObj.get(0).get("config");
222         if (configElement instanceof String) {
223             Map<Object, Object> obj = objectmapper.readValue(configElement.toString(),
224                             new TypeReference<Map<Object, Object>>() {});
225             respObj.get(0).put("config", obj);
226         }
227     }
228
229     RestTemplate getRestTemplate() throws Exception {
230         if (restTemplate != null) {
231             return restTemplate;
232         }
233         TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
234         SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
235                         .loadTrustMaterial(null, acceptingTrustStrategy).build();
236         HostnameVerifier verifier = (String arg0, SSLSession arg1) -> true;
237         SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, verifier);
238         CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
239         HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
240         requestFactory.setHttpClient(httpClient);
241         restTemplate = new RestTemplate(requestFactory);
242         restTemplate.getInterceptors().add(getAuthInt());
243         return restTemplate;
244     }
245
246     RestTemplateBuilder getPolicyMgrRestTempBuilder() {
247         return policyMgrRestTempBuilder;
248     }
249
250     void setPolicyMgrRestTempBuilder(RestTemplateBuilder policyMgrRestTempBuilder) {
251         this.policyMgrRestTempBuilder = policyMgrRestTempBuilder;
252     }
253
254     PolicyManagerAuthorizationInterceptor getAuthInt() {
255         return authInt;
256     }
257
258     void setAuthInt(PolicyManagerAuthorizationInterceptor authInt) {
259         this.authInt = authInt;
260     }
261 }