2 * ============LICENSE_START=======================================================
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
13 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
23 package org.onap.ccsdk.apps.ms.neng.service.extinf.impl;
25 import com.fasterxml.jackson.core.type.TypeReference;
26 import com.fasterxml.jackson.databind.ObjectMapper;
28 import java.security.cert.X509Certificate;
29 import java.util.ArrayList;
30 import java.util.HashMap;
31 import java.util.List;
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;
39 import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
40 import org.apache.hc.client5.http.impl.classic.HttpClients;
41 import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
42 import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
43 import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
44 import org.apache.hc.core5.ssl.TrustStrategy;
45 import org.onap.ccsdk.apps.ms.neng.core.exceptions.NengException;
46 import org.onap.ccsdk.apps.ms.neng.core.policy.PolicyFinder;
47 import org.onap.ccsdk.apps.ms.neng.core.resource.model.GetConfigRequest;
48 import org.onap.ccsdk.apps.ms.neng.core.resource.model.GetConfigRequestV2;
49 import org.onap.ccsdk.apps.ms.neng.core.resource.model.GetConfigResponse;
50 import org.onap.ccsdk.apps.ms.neng.core.rs.interceptors.PolicyManagerAuthorizationInterceptor;
51 import org.onap.ccsdk.apps.ms.neng.extinf.props.PolicyManagerProps;
52 import org.onap.ccsdk.sli.core.utils.common.AcceptIpAddressHostNameVerifier;
53 import org.springframework.beans.factory.annotation.Autowired;
54 import org.springframework.beans.factory.annotation.Qualifier;
55 import org.springframework.boot.web.client.RestTemplateBuilder;
56 import org.springframework.http.HttpStatus;
57 import org.springframework.http.MediaType;
58 import org.springframework.http.RequestEntity;
59 import org.springframework.http.ResponseEntity;
60 import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
61 import org.springframework.stereotype.Component;
62 import org.springframework.web.client.HttpStatusCodeException;
63 import org.springframework.web.client.RestTemplate;
66 * Finds policies from policy manager.
69 @Qualifier("PolicyFinderServiceImpl")
70 public class PolicyFinderServiceImpl implements PolicyFinder {
71 private static Logger log = Logger.getLogger(PolicyFinderServiceImpl.class.getName());
73 @Autowired PolicyManagerProps policManProps;
74 @Autowired @Qualifier("policyMgrRestTempBuilder") RestTemplateBuilder policyMgrRestTempBuilder;
75 @Autowired PolicyManagerAuthorizationInterceptor authInt;
76 RestTemplate restTemplate;
79 * Find policy with the given name from policy manager.
82 public Map<String, Object> findPolicy(String policyName) throws Exception {
83 Object response = getConfig(policyName).getResponse();
84 if (response instanceof List) {
85 @SuppressWarnings("unchecked")
86 List<Map<String, Object>> policyList = (List<Map<String, Object>>) response;
87 return ((!policyList.isEmpty()) ? policyList.get(0) : null);
93 protected boolean shouldUsePolicyV2 () {
94 String version = policManProps.getVersion();
95 log.info("Policy Manager Version - " + version );
98 int vnum = Integer.parseInt(version);
102 } catch ( Exception e ) {
109 GetConfigResponse getConfig(String policyName) throws Exception {
112 if ( shouldUsePolicyV2() ) {
113 GetConfigRequestV2 req = new GetConfigRequestV2();
115 req.setOnapName("SDNC");
116 req.setOnapComponent("CCSDK");
117 req.setOnapInstance("CCSDK-ms-neng");
118 req.setRequestId( UUID.randomUUID().toString() );
119 req.setAction("naming");
121 Map<String,Object> resource = new HashMap<>();
122 resource.put("policy-id", policyName);
123 req.setResource(resource);
127 GetConfigRequest getConfigRequest = new GetConfigRequest();
129 getConfigRequest.setPolicyName(policyName);
131 request = getConfigRequest;
134 ObjectMapper reqmapper = new ObjectMapper();
135 String reqStr = reqmapper.writeValueAsString(request);
136 log.info("Request - " + reqStr);
138 return (makeOutboundCall( policyName, request, GetConfigResponse.class));
141 <T, R> GetConfigResponse makeOutboundCall( String policyName, T request, Class<R> response) throws Exception {
142 log.info("Policy Manager - " + policManProps.getUrl());
144 RequestEntity<T> re = RequestEntity.post(new URI(policManProps.getUrl()))
145 .accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON).body(request);
147 ResponseEntity<Object> resp = getRestTemplate(policManProps.getDisableHostVerification()).exchange(re, Object.class);
148 if (HttpStatus.OK.equals(resp.getStatusCode())) {
149 ObjectMapper objectmapper = new ObjectMapper();
150 String bodyStr = objectmapper.writeValueAsString(resp.getBody());
151 return handleResponse( bodyStr );
153 } catch (HttpStatusCodeException e) {
156 throw new NengException("Error while retrieving policy " + policyName +" from policy manager.");
159 GetConfigResponse handleResponse ( String body ) throws Exception {
162 ObjectMapper objectmapper = new ObjectMapper();
163 GetConfigResponse getConfigResp = new GetConfigResponse();
165 Map<Object, Object> respObj = objectmapper.readValue( body, new TypeReference<Map<Object, Object>>() {});
166 List<Map<Object, Object>> respList = transformConfigObjectV2(objectmapper, respObj);
167 getConfigResp.setResponse(respList);
168 } catch ( Exception e ) {
169 List<Map<Object, Object>> respObj = objectmapper.readValue( body, new TypeReference<List<Map<Object, Object>>>() {});
170 transformConfigObject(objectmapper, respObj);
171 getConfigResp.setResponse(respObj);
173 return getConfigResp;
176 void handleError(HttpStatusCodeException e) throws Exception {
177 String respString = e.getResponseBodyAsString();
178 log.info(respString);
179 if (e.getStatusText() != null) {
180 log.info(e.getStatusText());
182 if (e.getResponseHeaders() != null && e.getResponseHeaders().toSingleValueMap() != null) {
183 log.info(e.getResponseHeaders().toSingleValueMap().toString());
185 if (HttpStatus.NOT_FOUND.equals(e.getStatusCode()) && (respString != null && respString.contains(""))) {
186 throw new NengException("Policy not found in policy manager.");
188 throw new NengException("Error while retrieving policy from policy manager.");
192 * Transforms the policy-V2 response in a form compatible with V1.
194 List<Map<Object,Object>> transformConfigObjectV2(ObjectMapper objectmapper, Map<Object, Object> respObj) throws Exception {
195 List<Map<Object,Object>> policyList = new ArrayList<>();
197 Object policies = respObj.get("policies");
198 if (policies != null && policies instanceof Map<?, ?> ) {
199 Map<Object, Object> policiesMap = (Map<Object,Object>)policies;
200 if ( policiesMap.size() > 0 ) {
201 Object policy = policiesMap.entrySet().iterator().next().getValue();
202 if ( policy != null && policy instanceof Map<?, ?> ) {
203 Map<Object, Object> thePolicyMap = (Map<Object,Object>)policy;
204 Object properties = thePolicyMap.get("properties");
205 if ( properties != null && properties instanceof Map<?, ?> ) {
206 Map<Object, Object> propertiesMap = (Map<Object,Object>)properties;
208 Map<Object,Object> top = new HashMap<>();
209 Map<Object,Object> config = new HashMap<>();
210 top.put("config", config );
211 config.put("content", propertiesMap );
222 * Transforms the 'config' element (which is received as a JSON string) to a map like a JSON object.
224 void transformConfigObject(ObjectMapper objectmapper, List<Map<Object, Object>> respObj) throws Exception {
225 Object configElement = respObj.get(0).get("config");
226 if (configElement instanceof String) {
227 Map<Object, Object> obj = objectmapper.readValue(configElement.toString(),
228 new TypeReference<Map<Object, Object>>() {});
229 respObj.get(0).put("config", obj);
233 RestTemplate getRestTemplate(Boolean disableHostVerification) throws Exception {
234 if (restTemplate != null) {
238 TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
239 SSLContext sslContext = org.apache.hc.core5.ssl.SSLContexts.custom()
240 .loadTrustMaterial(null, acceptingTrustStrategy).build();
241 HostnameVerifier verifier = new AcceptIpAddressHostNameVerifier(disableHostVerification);
242 SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, verifier);
244 PoolingHttpClientConnectionManager connectionManager = PoolingHttpClientConnectionManagerBuilder.create().setSSLSocketFactory(csf).build();
245 CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();
246 HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
248 requestFactory.setHttpClient(httpClient);
249 restTemplate = new RestTemplate(requestFactory);
250 restTemplate.getInterceptors().add(getAuthInt());
254 RestTemplateBuilder getPolicyMgrRestTempBuilder() {
255 return policyMgrRestTempBuilder;
258 void setPolicyMgrRestTempBuilder(RestTemplateBuilder policyMgrRestTempBuilder) {
259 this.policyMgrRestTempBuilder = policyMgrRestTempBuilder;
262 PolicyManagerAuthorizationInterceptor getAuthInt() {
266 void setAuthInt(PolicyManagerAuthorizationInterceptor authInt) {
267 this.authInt = authInt;