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.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;
62 * Finds policies from policy manager.
65 @Qualifier("PolicyFinderServiceImpl")
66 public class PolicyFinderServiceImpl implements PolicyFinder {
67 private static Logger log = Logger.getLogger(PolicyFinderServiceImpl.class.getName());
69 @Autowired PolicyManagerProps policManProps;
70 @Autowired @Qualifier("policyMgrRestTempBuilder") RestTemplateBuilder policyMgrRestTempBuilder;
71 @Autowired PolicyManagerAuthorizationInterceptor authInt;
72 RestTemplate restTemplate;
75 * Find policy with the given name from policy manager.
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);
89 protected boolean shouldUsePolicyV2 () {
90 String version = policManProps.getVersion();
91 log.info("Policy Manager Version - " + version );
94 int vnum = Integer.parseInt(version);
98 } catch ( Exception e ) {
105 GetConfigResponse getConfig(String policyName) throws Exception {
108 if ( shouldUsePolicyV2() ) {
109 GetConfigRequestV2 req = new GetConfigRequestV2();
111 req.setOnapName("SDNC");
112 req.setOnapComponent("CCSDK");
113 req.setOnapInstance("CCSDK-ms-neng");
114 req.setRequestId( UUID.randomUUID().toString() );
115 req.setAction("naming");
117 Map<String,Object> resource = new HashMap<>();
118 resource.put("policy-id", policyName);
119 req.setResource(resource);
123 GetConfigRequest getConfigRequest = new GetConfigRequest();
125 getConfigRequest.setPolicyName(policyName);
127 request = getConfigRequest;
130 ObjectMapper reqmapper = new ObjectMapper();
131 String reqStr = reqmapper.writeValueAsString(request);
132 log.info("Request - " + reqStr);
134 return (makeOutboundCall( policyName, request, GetConfigResponse.class));
137 <T, R> GetConfigResponse makeOutboundCall( String policyName, T request, Class<R> response) throws Exception {
138 log.info("Policy Manager - " + policManProps.getUrl());
140 RequestEntity<T> re = RequestEntity.post(new URI(policManProps.getUrl()))
141 .accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON).body(request);
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 );
149 } catch (HttpStatusCodeException e) {
152 throw new NengException("Error while retrieving policy " + policyName +" from policy manager.");
155 GetConfigResponse handleResponse ( String body ) throws Exception {
158 ObjectMapper objectmapper = new ObjectMapper();
159 GetConfigResponse getConfigResp = new GetConfigResponse();
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);
169 return getConfigResp;
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());
178 if (e.getResponseHeaders() != null && e.getResponseHeaders().toSingleValueMap() != null) {
179 log.info(e.getResponseHeaders().toSingleValueMap().toString());
181 if (HttpStatus.NOT_FOUND.equals(e.getStatusCode()) && (respString != null && respString.contains(""))) {
182 throw new NengException("Policy not found in policy manager.");
184 throw new NengException("Error while retrieving policy from policy manager.");
188 * Transforms the policy-V2 response in a form compatible with V1.
190 List<Map<Object,Object>> transformConfigObjectV2(ObjectMapper objectmapper, Map<Object, Object> respObj) throws Exception {
191 List<Map<Object,Object>> policyList = new ArrayList<>();
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;
204 Map<Object,Object> top = new HashMap<>();
205 Map<Object,Object> config = new HashMap<>();
206 top.put("config", config );
207 config.put("content", propertiesMap );
218 * Transforms the 'config' element (which is received as a JSON string) to a map like a JSON object.
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);
229 RestTemplate getRestTemplate() throws Exception {
230 if (restTemplate != null) {
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());
246 RestTemplateBuilder getPolicyMgrRestTempBuilder() {
247 return policyMgrRestTempBuilder;
250 void setPolicyMgrRestTempBuilder(RestTemplateBuilder policyMgrRestTempBuilder) {
251 this.policyMgrRestTempBuilder = policyMgrRestTempBuilder;
254 PolicyManagerAuthorizationInterceptor getAuthInt() {
258 void setAuthInt(PolicyManagerAuthorizationInterceptor authInt) {
259 this.authInt = authInt;