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;
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;
63 * Finds policies from policy manager.
66 @Qualifier("PolicyFinderServiceImpl")
67 public class PolicyFinderServiceImpl implements PolicyFinder {
68 private static Logger log = Logger.getLogger(PolicyFinderServiceImpl.class.getName());
70 @Autowired PolicyManagerProps policManProps;
71 @Autowired @Qualifier("policyMgrRestTempBuilder") RestTemplateBuilder policyMgrRestTempBuilder;
72 @Autowired PolicyManagerAuthorizationInterceptor authInt;
73 RestTemplate restTemplate;
76 * Find policy with the given name from policy manager.
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);
90 protected boolean shouldUsePolicyV2 () {
91 String version = policManProps.getVersion();
92 log.info("Policy Manager Version - " + version );
95 int vnum = Integer.parseInt(version);
99 } catch ( Exception e ) {
106 GetConfigResponse getConfig(String policyName) throws Exception {
109 if ( shouldUsePolicyV2() ) {
110 GetConfigRequestV2 req = new GetConfigRequestV2();
112 req.setOnapName("SDNC");
113 req.setOnapComponent("CCSDK");
114 req.setOnapInstance("CCSDK-ms-neng");
115 req.setRequestId( UUID.randomUUID().toString() );
116 req.setAction("naming");
118 Map<String,Object> resource = new HashMap<>();
119 resource.put("policy-id", policyName);
120 req.setResource(resource);
124 GetConfigRequest getConfigRequest = new GetConfigRequest();
126 getConfigRequest.setPolicyName(policyName);
128 request = getConfigRequest;
131 ObjectMapper reqmapper = new ObjectMapper();
132 String reqStr = reqmapper.writeValueAsString(request);
133 log.info("Request - " + reqStr);
135 return (makeOutboundCall( policyName, request, GetConfigResponse.class));
138 <T, R> GetConfigResponse makeOutboundCall( String policyName, T request, Class<R> response) throws Exception {
139 log.info("Policy Manager - " + policManProps.getUrl());
141 RequestEntity<T> re = RequestEntity.post(new URI(policManProps.getUrl()))
142 .accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON).body(request);
144 ResponseEntity<Object> resp = getRestTemplate().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 );
150 } catch (HttpStatusCodeException e) {
153 throw new NengException("Error while retrieving policy " + policyName +" from policy manager.");
156 GetConfigResponse handleResponse ( String body ) throws Exception {
159 ObjectMapper objectmapper = new ObjectMapper();
160 GetConfigResponse getConfigResp = new GetConfigResponse();
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);
170 return getConfigResp;
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());
179 if (e.getResponseHeaders() != null && e.getResponseHeaders().toSingleValueMap() != null) {
180 log.info(e.getResponseHeaders().toSingleValueMap().toString());
182 if (HttpStatus.NOT_FOUND.equals(e.getStatusCode()) && (respString != null && respString.contains(""))) {
183 throw new NengException("Policy not found in policy manager.");
185 throw new NengException("Error while retrieving policy from policy manager.");
189 * Transforms the policy-V2 response in a form compatible with V1.
191 List<Map<Object,Object>> transformConfigObjectV2(ObjectMapper objectmapper, Map<Object, Object> respObj) throws Exception {
192 List<Map<Object,Object>> policyList = new ArrayList<>();
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;
205 Map<Object,Object> top = new HashMap<>();
206 Map<Object,Object> config = new HashMap<>();
207 top.put("config", config );
208 config.put("content", propertiesMap );
219 * Transforms the 'config' element (which is received as a JSON string) to a map like a JSON object.
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);
230 RestTemplate getRestTemplate() throws Exception {
231 if (restTemplate != null) {
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();
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());
247 RestTemplateBuilder getPolicyMgrRestTempBuilder() {
248 return policyMgrRestTempBuilder;
251 void setPolicyMgrRestTempBuilder(RestTemplateBuilder policyMgrRestTempBuilder) {
252 this.policyMgrRestTempBuilder = policyMgrRestTempBuilder;
255 PolicyManagerAuthorizationInterceptor getAuthInt() {
259 void setAuthInt(PolicyManagerAuthorizationInterceptor authInt) {
260 this.authInt = authInt;