2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
20 package org.onap.policy.admin;
22 import java.io.ByteArrayInputStream;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.OutputStream;
27 import java.io.PrintWriter;
28 import java.net.HttpURLConnection;
30 import java.nio.charset.StandardCharsets;
31 import java.util.ArrayList;
32 import java.util.Base64;
33 import java.util.List;
35 import javax.servlet.http.HttpServletRequest;
36 import javax.servlet.http.HttpServletResponse;
38 import org.apache.commons.fileupload.FileItem;
39 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
40 import org.apache.commons.fileupload.servlet.ServletFileUpload;
41 import org.apache.commons.io.IOUtils;
42 import org.json.JSONObject;
43 import org.onap.policy.common.logging.flexlogger.FlexLogger;
44 import org.onap.policy.common.logging.flexlogger.Logger;
45 import org.onap.policy.controller.CreateClosedLoopFaultController;
46 import org.onap.policy.controller.CreateDcaeMicroServiceController;
47 import org.onap.policy.controller.CreateFirewallController;
48 import org.onap.policy.controller.PolicyController;
49 import org.onap.policy.rest.XACMLRestProperties;
50 import org.onap.policy.rest.adapter.PolicyRestAdapter;
51 import org.onap.policy.rest.dao.CommonClassDao;
52 import org.onap.policy.rest.jpa.PolicyVersion;
53 import org.onap.policy.utils.PolicyUtils;
54 import org.onap.policy.xacml.api.XACMLErrorConstants;
55 import org.onap.portalsdk.core.controller.RestrictedBaseController;
56 import org.onap.portalsdk.core.web.support.UserUtils;
57 import org.springframework.beans.factory.annotation.Autowired;
58 import org.springframework.http.HttpEntity;
59 import org.springframework.http.HttpHeaders;
60 import org.springframework.http.HttpMethod;
61 import org.springframework.http.HttpStatus;
62 import org.springframework.http.ResponseEntity;
63 import org.springframework.web.bind.annotation.RequestMapping;
64 import org.springframework.web.bind.annotation.RequestMethod;
65 import org.springframework.web.bind.annotation.RestController;
66 import org.springframework.web.client.HttpClientErrorException;
67 import org.springframework.web.client.RestTemplate;
68 import org.springframework.web.servlet.ModelAndView;
70 import com.att.research.xacml.util.XACMLProperties;
71 import com.fasterxml.jackson.databind.DeserializationFeature;
72 import com.fasterxml.jackson.databind.JsonNode;
73 import com.fasterxml.jackson.databind.ObjectMapper;
74 import com.fasterxml.jackson.databind.SerializationFeature;
78 public class PolicyRestController extends RestrictedBaseController{
80 private static final Logger policyLogger = FlexLogger.getLogger(PolicyRestController.class);
82 private static final String modal = "model";
83 private static final String importDictionary = "import_dictionary";
85 private static CommonClassDao commonClassDao;
87 public static CommonClassDao getCommonClassDao() {
88 return commonClassDao;
91 public static void setCommonClassDao(CommonClassDao commonClassDao) {
92 PolicyRestController.commonClassDao = commonClassDao;
96 private PolicyRestController(CommonClassDao commonClassDao){
97 PolicyRestController.commonClassDao = commonClassDao;
100 public PolicyRestController(){
101 //default constructor
104 @RequestMapping(value={"/policycreation/save_policy"}, method={RequestMethod.POST})
105 public void policyCreationController(HttpServletRequest request, HttpServletResponse response) {
106 String userId = UserUtils.getUserSession(request).getOrgUserId();
107 ObjectMapper mapper = new ObjectMapper();
108 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
110 JsonNode root = mapper.readTree(request.getReader());
112 policyLogger.info("****************************************Logging UserID while Create/Update Policy**************************************************");
113 policyLogger.info("UserId: " + userId + "Policy Data Object: "+ root.get(PolicyController.getPolicydata()).get("policy").toString());
114 policyLogger.info("***********************************************************************************************************************************");
116 PolicyRestAdapter policyData = mapper.readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class);
118 if("file".equals(root.get(PolicyController.getPolicydata()).get(modal).get("type").toString().replace("\"", ""))){
119 policyData.setEditPolicy(true);
121 if(root.get(PolicyController.getPolicydata()).get(modal).get("path").size() != 0){
123 for(int i = 0; i < root.get(PolicyController.getPolicydata()).get(modal).get("path").size(); i++){
124 dirName = dirName.replace("\"", "") + root.get(PolicyController.getPolicydata()).get(modal).get("path").get(i).toString().replace("\"", "") + File.separator;
126 if(policyData.isEditPolicy()){
127 policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator)));
129 policyData.setDomainDir(dirName + root.get(PolicyController.getPolicydata()).get(modal).get("name").toString().replace("\"", ""));
132 String domain = root.get(PolicyController.getPolicydata()).get("model").get("name").toString();
133 if(domain.contains("/")){
134 domain = domain.substring(0, domain.lastIndexOf('/')).replace("/", File.separator);
136 domain = domain.replace("\"", "");
137 policyData.setDomainDir(domain);
140 if(policyData.getConfigPolicyType() != null){
141 if("ClosedLoop_Fault".equalsIgnoreCase(policyData.getConfigPolicyType())){
142 CreateClosedLoopFaultController faultController = new CreateClosedLoopFaultController();
143 policyData = faultController.setDataToPolicyRestAdapter(policyData, root);
144 }else if("Firewall Config".equalsIgnoreCase(policyData.getConfigPolicyType())){
145 CreateFirewallController fwController = new CreateFirewallController();
146 policyData = fwController.setDataToPolicyRestAdapter(policyData);
147 }else if("Micro Service".equalsIgnoreCase(policyData.getConfigPolicyType())){
148 CreateDcaeMicroServiceController msController = new CreateDcaeMicroServiceController();
149 policyData = msController.setDataToPolicyRestAdapter(policyData, root);
153 policyData.setUserId(userId);
156 String body = PolicyUtils.objectToJsonString(policyData);
157 String uri = request.getRequestURI();
158 ResponseEntity<?> responseEntity = sendToPAP(body, uri, HttpMethod.POST);
159 if(responseEntity != null && responseEntity.getBody().equals(HttpServletResponse.SC_CONFLICT)){
160 result = "PolicyExists";
161 }else if(responseEntity != null){
162 result = responseEntity.getBody().toString();
163 String policyName = responseEntity.getHeaders().get("policyName").get(0);
164 if(policyData.isEditPolicy() && "success".equalsIgnoreCase(result)){
165 PolicyNotificationMail email = new PolicyNotificationMail();
166 String mode = "EditPolicy";
167 String watchPolicyName = policyName.replace(".xml", "");
168 String version = watchPolicyName.substring(watchPolicyName.lastIndexOf('.')+1);
169 watchPolicyName = watchPolicyName.substring(0, watchPolicyName.lastIndexOf('.')).replace(".", File.separator);
170 String policyVersionName = watchPolicyName.replace(".", File.separator);
171 watchPolicyName = watchPolicyName + "." + version + ".xml";
172 PolicyVersion entityItem = new PolicyVersion();
173 entityItem.setPolicyName(policyVersionName);
174 entityItem.setActiveVersion(Integer.parseInt(version));
175 entityItem.setModifiedBy(userId);
176 email.sendMail(entityItem, watchPolicyName, mode, commonClassDao);
179 result = "Response is null from PAP";
182 response.setCharacterEncoding(PolicyController.getCharacterencoding());
183 response.setContentType(PolicyController.getContenttype());
184 request.setCharacterEncoding(PolicyController.getCharacterencoding());
186 PrintWriter out = response.getWriter();
187 String responseString = mapper.writeValueAsString(result);
188 JSONObject j = new JSONObject("{policyData: " + responseString + "}");
189 out.write(j.toString());
191 policyLogger.error("Exception Occured while saving policy" , e);
196 private ResponseEntity<?> sendToPAP(String body, String requestURI, HttpMethod method){
197 String papUrl = PolicyController.getPapUrl();
198 String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
199 String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS);
201 Base64.Encoder encoder = Base64.getEncoder();
202 String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
203 HttpHeaders headers = new HttpHeaders();
204 headers.set("Authorization", "Basic " + encoding);
205 headers.set("Content-Type", PolicyController.getContenttype());
207 RestTemplate restTemplate = new RestTemplate();
208 HttpEntity<?> requestEntity = new HttpEntity<>(body, headers);
209 ResponseEntity<?> result = null;
210 HttpClientErrorException exception = null;
211 String uri = requestURI;
212 if(uri.startsWith("/")){
213 uri = uri.substring(uri.indexOf('/')+1);
215 uri = "onap" + uri.substring(uri.indexOf('/'));
217 result = restTemplate.exchange(papUrl + uri, method, requestEntity, String.class);
219 policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl, e);
220 exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
221 if("409 Conflict".equals(e.getMessage())){
222 return ResponseEntity.ok(HttpServletResponse.SC_CONFLICT);
225 if(exception != null && exception.getStatusCode()!=null){
226 if(exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)){
227 String message = XACMLErrorConstants.ERROR_PERMISSIONS +":"+exception.getStatusCode()+":" + "ERROR_AUTH_GET_PERM" ;
228 policyLogger.error(message);
230 if(exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)){
231 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
232 policyLogger.error(message);
234 if(exception.getStatusCode().equals(HttpStatus.NOT_FOUND)){
235 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl + exception;
236 policyLogger.error(message);
238 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
239 policyLogger.error(message);
244 private String callPAP(HttpServletRequest request , String method, String uriValue){
245 String uri = uriValue;
246 String boundary = null;
247 String papUrl = PolicyController.getPapUrl();
248 String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
249 String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS);
251 Base64.Encoder encoder = Base64.getEncoder();
252 String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
253 HttpHeaders headers = new HttpHeaders();
254 headers.set("Authorization", "Basic " + encoding);
255 headers.set("Content-Type", PolicyController.getContenttype());
258 HttpURLConnection connection = null;
259 List<FileItem> items;
260 FileItem item = null;
262 if(uri.contains(importDictionary)){
264 items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
266 file = new File(item.getName());
267 String newFile = file.toString();
268 uri = uri +"&dictionaryName="+newFile;
269 } catch (Exception e2) {
270 policyLogger.error("Exception Occured while calling PAP with import dictionary request"+e2);
275 URL url = new URL(papUrl + uri);
276 connection = (HttpURLConnection)url.openConnection();
277 connection.setRequestMethod(method);
278 connection.setUseCaches(false);
279 connection.setInstanceFollowRedirects(false);
280 connection.setRequestProperty("Authorization", "Basic " + encoding);
281 connection.setDoOutput(true);
282 connection.setDoInput(true);
284 if(!uri.contains("searchPolicy?action=delete&")){
286 if(!(uri.endsWith("set_BRMSParamData") || uri.contains(importDictionary))){
287 connection.setRequestProperty("Content-Type",PolicyController.getContenttype());
288 ObjectMapper mapper = new ObjectMapper();
289 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
290 JsonNode root = null;
292 root = mapper.readTree(request.getReader());
293 }catch (Exception e1) {
294 policyLogger.error("Exception Occured while calling PAP"+e1);
297 ObjectMapper mapper1 = new ObjectMapper();
298 mapper1.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
300 Object obj = mapper1.treeToValue(root, Object.class);
301 String json = mapper1.writeValueAsString(obj);
303 Object content = new ByteArrayInputStream(json.getBytes());
305 if (content instanceof InputStream) {
306 // send current configuration
307 try (OutputStream os = connection.getOutputStream()) {
308 int count = IOUtils.copy((InputStream) content, os);
309 if (policyLogger.isDebugEnabled()) {
310 policyLogger.debug("copied to output, bytes=" + count);
315 if(uri.endsWith("set_BRMSParamData")){
316 connection.setRequestProperty("Content-Type",PolicyController.getContenttype());
317 try (OutputStream os = connection.getOutputStream()) {
318 IOUtils.copy((InputStream) request.getInputStream(), os);
321 boundary = "===" + System.currentTimeMillis() + "===";
322 connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary);
323 try (OutputStream os = connection.getOutputStream()) {
325 IOUtils.copy((InputStream) item.getInputStream(), os);
332 connection.connect();
334 int responseCode = connection.getResponseCode();
335 if(responseCode == 200){
336 // get the response content into a String
337 String responseJson = null;
338 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
339 java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream());
340 scanner.useDelimiter("\\A");
341 responseJson = scanner.hasNext() ? scanner.next() : "";
343 policyLogger.info("JSON response from PAP: " + responseJson);
347 } catch (Exception e) {
348 policyLogger.error("Exception Occured"+e);
350 if(file != null && file.exists() && file.delete()){
351 policyLogger.info("File Deleted Successfully");
353 if (connection != null) {
355 // For some reason trying to get the inputStream from the connection
356 // throws an exception rather than returning null when the InputStream does not exist.
357 InputStream is = connection.getInputStream();
361 } catch (IOException ex) {
362 policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex);
364 connection.disconnect();
370 @RequestMapping(value={"/getDictionary/*"}, method={RequestMethod.GET})
371 public void getDictionaryController(HttpServletRequest request, HttpServletResponse response){
372 String uri = request.getRequestURI().replace("/getDictionary", "");
374 ResponseEntity<?> responseEntity = sendToPAP(null, uri, HttpMethod.GET);
375 if(responseEntity != null){
376 body = responseEntity.getBody().toString();
381 response.getWriter().write(body);
382 } catch (IOException e) {
383 policyLogger.error("Exception occured while getting Dictionary entries", e);
387 @RequestMapping(value={"/saveDictionary/*/*"}, method={RequestMethod.POST})
388 public ModelAndView saveDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException{
390 String uri = request.getRequestURI().replace("/saveDictionary", "");
391 if(uri.startsWith("/")){
392 uri = uri.substring(uri.indexOf('/')+1);
394 uri = "/onap" + uri.substring(uri.indexOf('/'));
395 if(uri.contains(importDictionary)){
396 userId = UserUtils.getUserSession(request).getOrgUserId();
397 uri = uri+ "?userId=" +userId;
400 policyLogger.info("****************************************Logging UserID while Saving Dictionary*****************************************************");
401 policyLogger.info("UserId: " + userId);
402 policyLogger.info("***********************************************************************************************************************************");
404 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
405 response.getWriter().write(body);
409 @RequestMapping(value={"/deleteDictionary/*/*"}, method={RequestMethod.POST})
410 public ModelAndView deletetDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException {
411 String uri = request.getRequestURI().replace("/deleteDictionary", "");
412 if(uri.startsWith("/")){
413 uri = uri.substring(uri.indexOf('/')+1);
415 uri = "/onap" + uri.substring(uri.indexOf('/'));
417 String userId = UserUtils.getUserSession(request).getOrgUserId();
418 policyLogger.info("****************************************Logging UserID while Deleting Dictionary*****************************************************");
419 policyLogger.info("UserId: " + userId);
420 policyLogger.info("*************************************************************************************************************************************");
422 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
423 response.getWriter().write(body);
427 @RequestMapping(value={"/searchDictionary"}, method={RequestMethod.POST})
428 public ModelAndView searchDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException {
429 Object resultList = null;
430 String uri = request.getRequestURI();
431 if(uri.startsWith("/")){
432 uri = uri.substring(uri.indexOf('/')+1);
434 uri = "/onap" + uri.substring(uri.indexOf('/'));
436 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
437 if(body.contains("CouldNotConnectException")){
438 List<String> data = new ArrayList<>();
439 data.add("Elastic Search Server is down");
442 JSONObject json = new JSONObject(body);
443 resultList = json.get("policyresult");
446 policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception Occured while querying Elastic Search: " + e);
447 List<String> data = new ArrayList<>();
448 data.add("Elastic Search Server is down");
452 response.setCharacterEncoding(PolicyController.getCharacterencoding());
453 response.setContentType(PolicyController.getContenttype());
454 PrintWriter out = response.getWriter();
455 JSONObject j = new JSONObject("{result: " + resultList + "}");
456 out.write(j.toString());
460 @RequestMapping(value={"/searchPolicy"}, method={RequestMethod.POST})
461 public ModelAndView searchPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException{
462 Object resultList = null;
463 String uri = request.getRequestURI()+"?action=search";
464 if(uri.startsWith("/")){
465 uri = uri.substring(uri.indexOf('/')+1);
467 uri = "/onap" + uri.substring(uri.indexOf('/'));
468 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
470 JSONObject json = new JSONObject(body);
472 resultList = json.get("policyresult");
474 List<String> data = new ArrayList<>();
475 data.add("Elastic Search Server is down");
477 policyLogger.error("Exception Occured while searching for Policy in Elastic Database" +e);
480 response.setCharacterEncoding("UTF-8");
481 response.setContentType("application / json");
482 request.setCharacterEncoding("UTF-8");
484 PrintWriter out = response.getWriter();
485 JSONObject j = new JSONObject("{result: " + resultList + "}");
486 out.write(j.toString());
490 public void deleteElasticData(String fileName){
491 String uri = "searchPolicy?action=delete&policyName='"+fileName+"'";
492 callPAP(null, "POST", uri.trim());