a19c915319b0cb25fef66ed2e10c17cf0bbdfb43
[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  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.ccsdk.apps.ms.neng.service.extinf.impl;
22
23 import com.fasterxml.jackson.core.type.TypeReference;
24 import com.fasterxml.jackson.databind.ObjectMapper;
25 import java.net.URI;
26 import java.security.cert.X509Certificate;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.logging.Logger;
30 import javax.net.ssl.SSLContext;
31 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
32 import org.apache.http.conn.ssl.TrustStrategy;
33 import org.apache.http.impl.client.CloseableHttpClient;
34 import org.apache.http.impl.client.HttpClients;
35 import org.onap.ccsdk.apps.ms.neng.core.exceptions.NengException;
36 import org.onap.ccsdk.apps.ms.neng.core.policy.PolicyFinder;
37 import org.onap.ccsdk.apps.ms.neng.core.resource.model.GetConfigRequest;
38 import org.onap.ccsdk.apps.ms.neng.core.resource.model.GetConfigResponse;
39 import org.onap.ccsdk.apps.ms.neng.core.rs.interceptors.PolicyManagerAuthorizationInterceptor;
40 import org.onap.ccsdk.apps.ms.neng.extinf.props.PolicyManagerProps;
41 import org.springframework.beans.factory.annotation.Autowired;
42 import org.springframework.beans.factory.annotation.Qualifier;
43 import org.springframework.boot.web.client.RestTemplateBuilder;
44 import org.springframework.http.HttpStatus;
45 import org.springframework.http.MediaType;
46 import org.springframework.http.RequestEntity;
47 import org.springframework.http.ResponseEntity;
48 import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
49 import org.springframework.stereotype.Component;
50 import org.springframework.web.client.HttpStatusCodeException;
51 import org.springframework.web.client.RestTemplate;
52
53 /**
54  * Finds policies from policy manager.
55  */
56 @Component
57 @Qualifier("PolicyFinderServiceImpl")
58 public class PolicyFinderServiceImpl implements PolicyFinder {
59     private static Logger log = Logger.getLogger(PolicyFinderServiceImpl.class.getName());
60
61     @Autowired PolicyManagerProps policManProps;
62     @Autowired
63     @Qualifier("policyMgrRestTempBuilder")
64     RestTemplateBuilder policyMgrRestTempBuilder;
65     @Autowired PolicyManagerAuthorizationInterceptor authInt;
66     RestTemplate restTemplate;
67
68     /**
69      * Find policy with the given name from policy manager.
70      */
71     @Override
72     public Map<String, Object> findPolicy(String policyName) throws Exception {
73         Object response = getConfig(policyName).getResponse();
74         if (response instanceof List) {
75             @SuppressWarnings("unchecked")
76             List<Map<String, Object>> policyList = (List<Map<String, Object>>)response;
77             return ((policyList != null && policyList.size() > 0) ? policyList.get(0) : null);
78         } else {
79             return null;
80         }
81     }
82
83     GetConfigResponse getConfig(String policyName) throws Exception {
84         GetConfigRequest getConfigRequest = new GetConfigRequest();
85         getConfigRequest.setPolicyName(policyName);
86         GetConfigResponse getConfigResponse = makeOutboundCall(getConfigRequest, GetConfigResponse.class);
87         return getConfigResponse;
88     }
89
90     <T, R> GetConfigResponse makeOutboundCall(T request, Class<R> response) throws Exception {
91         log.info("Policy Manager  - " + policManProps.getUrl());
92         RequestEntity<T> re = RequestEntity.post(new URI(policManProps.getUrl()))
93                         .accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON).body(request);
94         try {
95             ResponseEntity<Object> resp = getRestTemplate().exchange(re, Object.class);
96             if (HttpStatus.OK.equals(resp.getStatusCode())) {
97                 ObjectMapper objectmapper = new ObjectMapper();
98                 System.out.println(objectmapper.writeValueAsString(resp.getBody()));
99                 List<Map<Object, Object>> respObj = objectmapper.readValue(
100                                 objectmapper.writeValueAsString(resp.getBody()),
101                                 new TypeReference<List<Map<Object, Object>>>() {});
102                 transformConfigObject(objectmapper, respObj);
103                 GetConfigResponse getConfigResp = new GetConfigResponse();
104                 getConfigResp.setResponse(respObj);
105                 return getConfigResp;
106             }
107         } catch (HttpStatusCodeException e) {
108             handleError(e);
109         }
110         throw new NengException("Error while retrieving policy from policy manager.");
111     }
112
113     void handleError(HttpStatusCodeException e) throws Exception {
114         String respString = e.getResponseBodyAsString();
115         log.info(respString);
116         if (HttpStatus.NOT_FOUND.equals(e.getStatusCode()) && (respString != null && respString.contains(""))) {
117             throw new NengException("Policy not found in policy manager.");
118         }
119         throw new NengException("Error while retrieving policy from policy manager.");
120     }
121
122     /**
123      * Transforms the 'config' element (which is received as a JSON string) to a map like a JSON object.
124      */
125     void transformConfigObject(ObjectMapper objectmapper, List<Map<Object, Object>> respObj) throws Exception {
126         Object configElement = respObj.get(0).get("config");
127         if (configElement instanceof String) {
128             Map<Object, Object> obj = objectmapper.readValue(configElement.toString(),
129                             new TypeReference<Map<Object, Object>>() {});
130             respObj.get(0).put("config", obj);
131         }
132     }
133
134     RestTemplate getRestTemplate() throws Exception {
135         if (restTemplate != null) {
136             return restTemplate;
137         }
138         TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
139         SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
140                         .loadTrustMaterial(null, acceptingTrustStrategy).build();
141         SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
142         CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
143         HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
144         requestFactory.setHttpClient(httpClient);
145         restTemplate = new RestTemplate(requestFactory);
146         restTemplate.getInterceptors().add(getAuthInt());
147         return restTemplate;
148     }
149
150     RestTemplateBuilder getPolicyMgrRestTempBuilder() {
151         return policyMgrRestTempBuilder;
152     }
153
154     void setPolicyMgrRestTempBuilder(RestTemplateBuilder policyMgrRestTempBuilder) {
155         this.policyMgrRestTempBuilder = policyMgrRestTempBuilder;
156     }
157
158     PolicyManagerAuthorizationInterceptor getAuthInt() {
159         return authInt;
160     }
161
162     void setAuthInt(PolicyManagerAuthorizationInterceptor authInt) {
163         this.authInt = authInt;
164     }
165 }