Merge "Push and unpush to support multiple policies"
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / admin / PolicyRestController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
7  * Modifications Copyright (C) 2019 Bell Canada
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
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
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=========================================================
21  */
22 package org.onap.policy.admin;
23
24 import java.io.ByteArrayInputStream;
25 import java.io.File;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.OutputStream;
29 import java.io.PrintWriter;
30 import java.net.HttpURLConnection;
31 import java.net.URL;
32 import java.nio.charset.StandardCharsets;
33 import java.util.ArrayList;
34 import java.util.Base64;
35 import java.util.List;
36
37 import javax.servlet.http.HttpServletRequest;
38 import javax.servlet.http.HttpServletResponse;
39
40 import org.apache.commons.fileupload.FileItem;
41 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
42 import org.apache.commons.fileupload.servlet.ServletFileUpload;
43 import org.apache.commons.io.IOUtils;
44 import org.json.JSONObject;
45 import org.onap.policy.common.logging.flexlogger.FlexLogger;
46 import org.onap.policy.common.logging.flexlogger.Logger;
47 import org.onap.policy.controller.CreateClosedLoopFaultController;
48 import org.onap.policy.controller.CreateDcaeMicroServiceController;
49 import org.onap.policy.controller.CreateFirewallController;
50 import org.onap.policy.controller.CreateOptimizationController;
51 import org.onap.policy.controller.PolicyController;
52 import org.onap.policy.rest.XACMLRestProperties;
53 import org.onap.policy.rest.adapter.PolicyRestAdapter;
54 import org.onap.policy.rest.dao.CommonClassDao;
55 import org.onap.policy.rest.jpa.PolicyVersion;
56 import org.onap.policy.utils.PolicyUtils;
57 import org.onap.policy.xacml.api.XACMLErrorConstants;
58 import org.onap.portalsdk.core.controller.RestrictedBaseController;
59 import org.onap.portalsdk.core.web.support.UserUtils;
60 import org.springframework.beans.factory.annotation.Autowired;
61 import org.springframework.http.HttpEntity;
62 import org.springframework.http.HttpHeaders;
63 import org.springframework.http.HttpMethod;
64 import org.springframework.http.HttpStatus;
65 import org.springframework.http.ResponseEntity;
66 import org.springframework.web.bind.annotation.RequestMapping;
67 import org.springframework.web.bind.annotation.RequestMethod;
68 import org.springframework.web.bind.annotation.RestController;
69 import org.springframework.web.client.HttpClientErrorException;
70 import org.springframework.web.client.RestTemplate;
71 import org.springframework.web.servlet.ModelAndView;
72 import org.onap.policy.utils.CryptoUtils;
73 import com.att.research.xacml.util.XACMLProperties;
74 import com.fasterxml.jackson.databind.DeserializationFeature;
75 import com.fasterxml.jackson.databind.JsonNode;
76 import com.fasterxml.jackson.databind.ObjectMapper;
77 import com.fasterxml.jackson.databind.SerializationFeature;
78
79 @RestController
80 @RequestMapping("/")
81 public class PolicyRestController extends RestrictedBaseController{
82
83     private static final Logger policyLogger = FlexLogger.getLogger(PolicyRestController.class);
84
85     private static final String MODEL = "model";
86     private static final String IMPORT_DICTIONARY = "import_dictionary";
87     private static final String FILE = "file";
88     private static final String TYPE = "type";
89     private static final String PATH = "path";
90     private static final String NAME = "name";
91     private static final String CLOSED_LOOP_FAULT = "ClosedLoop_Fault";
92     private static final String FIREWALL_CONFIG = "Firewall Config";
93     private static final String MICRO_SERVICE = "Micro Service";
94     private static final String OPTIMIZATION = "Optimization";
95     private static final String POLICY_NAME = "policyName";
96     private static final String SUCCESS = "success";
97     private static final String XML = ".xml";
98     private static final String UTF_8 = "UTF-8";
99     private static final String DATA = "data";
100     private static final String USER_ID = "UserId:  ";
101     private static final String BASIC = "Basic ";
102     private static final String AUTHORIZATION = "Authorization";
103     private static final String CONTENT_TYPE = "Content-Type";
104     private static final String ONAP = "/onap";
105
106     private static CommonClassDao commonClassDao;
107
108     public PolicyRestController(){
109         //default constructor
110     }
111
112     @Autowired
113     private PolicyRestController(CommonClassDao commonClassDao){
114         PolicyRestController.commonClassDao = commonClassDao;
115     }
116
117     public static CommonClassDao getCommonClassDao() {
118         return commonClassDao;
119     }
120
121     public static void setCommonClassDao(CommonClassDao commonClassDao) {
122         PolicyRestController.commonClassDao = commonClassDao;
123     }
124
125
126
127     @RequestMapping(value={"/policycreation/save_policy"}, method={RequestMethod.POST})
128     public void policyCreationController(HttpServletRequest request, HttpServletResponse response) {
129         String userId = UserUtils.getUserSession(request).getOrgUserId();
130         ObjectMapper mapper = new ObjectMapper();
131         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
132         try{
133             updateAndSendToPAP(request, response, userId, mapper);
134         }catch(Exception e){
135             policyLogger.error("Exception Occured while saving policy" , e);
136         }
137     }
138
139     private void updateAndSendToPAP(HttpServletRequest request, HttpServletResponse response, String userId, ObjectMapper mapper) throws IOException {
140         JsonNode root = mapper.readTree(request.getReader());
141         policyLogger.info(
142             "****************************************Logging UserID while Create/Update Policy**************************************************");
143         policyLogger.info(
144             USER_ID + userId + "Policy Data Object:  " + root.get(PolicyController.getPolicydata()).get("policy")
145                 .toString());
146         policyLogger.info(
147             "***********************************************************************************************************************************");
148
149         PolicyRestAdapter policyData = mapper
150             .readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class);
151         modifyPolicyData(root, policyData);
152
153         if (policyData.getConfigPolicyType() != null) {
154             if (CLOSED_LOOP_FAULT.equalsIgnoreCase(policyData.getConfigPolicyType())) {
155                 policyData = new CreateClosedLoopFaultController().setDataToPolicyRestAdapter(policyData, root);
156             } else if (FIREWALL_CONFIG.equalsIgnoreCase(policyData.getConfigPolicyType())) {
157                 policyData = new CreateFirewallController().setDataToPolicyRestAdapter(policyData);
158             } else if (MICRO_SERVICE.equalsIgnoreCase(policyData.getConfigPolicyType())) {
159                 policyData = new CreateDcaeMicroServiceController().setDataToPolicyRestAdapter(policyData, root);
160             } else if (OPTIMIZATION.equalsIgnoreCase(policyData.getConfigPolicyType())) {
161                 policyData = new CreateOptimizationController().setDataToPolicyRestAdapter(policyData, root);
162             }
163         }
164
165         policyData.setUserId(userId);
166
167         String result;
168         String body = PolicyUtils.objectToJsonString(policyData);
169         String uri = request.getRequestURI();
170         ResponseEntity<?> responseEntity = sendToPAP(body, uri, HttpMethod.POST);
171         if (responseEntity != null && responseEntity.getBody().equals(HttpServletResponse.SC_CONFLICT)) {
172             result = "PolicyExists";
173         } else if (responseEntity != null) {
174             result = responseEntity.getBody().toString();
175             String policyName = responseEntity.getHeaders().get(POLICY_NAME).get(0);
176             if (policyData.isEditPolicy() && SUCCESS.equalsIgnoreCase(result)) {
177                 PolicyNotificationMail email = new PolicyNotificationMail();
178                 String mode = "EditPolicy";
179                 String watchPolicyName = policyName.replace(XML, "");
180                 String version = watchPolicyName.substring(watchPolicyName.lastIndexOf('.') + 1);
181                 watchPolicyName = watchPolicyName.substring(0, watchPolicyName.lastIndexOf('.'))
182                     .replace(".", File.separator);
183                 String policyVersionName = watchPolicyName.replace(".", File.separator);
184                 watchPolicyName = watchPolicyName + "." + version + XML;
185                 PolicyVersion entityItem = new PolicyVersion();
186                 entityItem.setPolicyName(policyVersionName);
187                 entityItem.setActiveVersion(Integer.parseInt(version));
188                 entityItem.setModifiedBy(userId);
189                 email.sendMail(entityItem, watchPolicyName, mode, commonClassDao);
190             }
191         } else {
192             result = "Response is null from PAP";
193         }
194
195         response.setCharacterEncoding(PolicyController.getCharacterencoding());
196         response.setContentType(PolicyController.getContenttype());
197         request.setCharacterEncoding(PolicyController.getCharacterencoding());
198
199         PrintWriter out = response.getWriter();
200         String responseString = mapper.writeValueAsString(result);
201         JSONObject j = new JSONObject("{policyData: " + responseString + "}");
202         out.write(j.toString());
203     }
204
205     private void modifyPolicyData(JsonNode root, PolicyRestAdapter policyData) {
206         if(FILE.equals(root.get(PolicyController.getPolicydata()).get(MODEL).get(TYPE).toString().replace("\"", ""))){
207             policyData.setEditPolicy(true);
208         }
209         if(root.get(PolicyController.getPolicydata()).get(MODEL).get(PATH).size() != 0){
210             String dirName = "";
211             for(int i = 0; i < root.get(PolicyController.getPolicydata()).get(MODEL).get(PATH).size(); i++){
212                 dirName = dirName.replace("\"", "") + root.get(PolicyController.getPolicydata()).get(
213                     MODEL).get(PATH).get(i).toString().replace("\"", "") + File.separator;
214             }
215             if(policyData.isEditPolicy()){
216                 policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator)));
217             }else{
218                 policyData.setDomainDir(dirName + root.get(PolicyController.getPolicydata()).get(
219                     MODEL).get(NAME).toString().replace("\"", ""));
220             }
221         }else{
222             String domain = root.get(PolicyController.getPolicydata()).get(MODEL).get(NAME).toString();
223             if(domain.contains("/")){
224                 domain = domain.substring(0, domain.lastIndexOf('/')).replace("/", File.separator);
225             }
226             domain = domain.replace("\"", "");
227             policyData.setDomainDir(domain);
228         }
229     }
230
231
232     private ResponseEntity<?> sendToPAP(String body, String requestURI, HttpMethod method){
233         String papUrl = PolicyController.getPapUrl();
234         String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
235         String papPass = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
236
237         Base64.Encoder encoder = Base64.getEncoder();
238         String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
239         HttpHeaders headers = new HttpHeaders();
240         headers.set(AUTHORIZATION, BASIC + encoding);
241         headers.set(CONTENT_TYPE, PolicyController.getContenttype());
242
243         RestTemplate restTemplate = new RestTemplate();
244         HttpEntity<?> requestEntity = new HttpEntity<>(body, headers);
245         ResponseEntity<?> result = null;
246         HttpClientErrorException exception = null;
247         String uri = requestURI;
248         if(uri.startsWith("/")){
249             uri = uri.substring(uri.indexOf('/')+1);
250         }
251         uri = "onap" + uri.substring(uri.indexOf('/'));
252         try{
253             result = restTemplate.exchange(papUrl + uri, method, requestEntity, String.class);
254         }catch(Exception e){
255             policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl, e);
256             exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
257             if("409 Conflict".equals(e.getMessage())){
258                 return ResponseEntity.ok(HttpServletResponse.SC_CONFLICT);
259             }
260         }
261         if(exception != null && exception.getStatusCode()!=null){
262             if(exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)){
263                 String message = XACMLErrorConstants.ERROR_PERMISSIONS +":"+exception.getStatusCode()+":" + "ERROR_AUTH_GET_PERM" ;
264                 policyLogger.error(message);
265             }
266             if(exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)){
267                 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
268                 policyLogger.error(message);
269             }
270             if(exception.getStatusCode().equals(HttpStatus.NOT_FOUND)){
271                 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl + exception;
272                 policyLogger.error(message);
273             }
274             String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
275             policyLogger.error(message);
276         }
277         return result;
278     }
279
280     private String callPAP(HttpServletRequest request , String method, String uriValue){
281         String uri = uriValue;
282         String papUrl = PolicyController.getPapUrl();
283         String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
284         String papPass = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
285
286         Base64.Encoder encoder = Base64.getEncoder();
287         String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
288         HttpHeaders headers = new HttpHeaders();
289         headers.set(AUTHORIZATION, BASIC + encoding);
290         headers.set(CONTENT_TYPE, PolicyController.getContenttype());
291
292
293         HttpURLConnection connection = null;
294         List<FileItem> items;
295         FileItem item = null;
296         File file = null;
297         if(uri.contains(IMPORT_DICTIONARY)){
298             try {
299                 items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
300                 item = items.get(0);
301                 file = new File(item.getName());
302                 String newFile = file.toString();
303                 uri = uri +"&dictionaryName="+newFile;
304             } catch (Exception e2) {
305                 policyLogger.error("Exception Occured while calling PAP with import dictionary request"+e2);
306             }
307         }
308
309         try {
310             URL url = new URL(papUrl + uri);
311             connection = (HttpURLConnection)url.openConnection();
312             connection.setRequestMethod(method);
313             connection.setUseCaches(false);
314             connection.setInstanceFollowRedirects(false);
315             connection.setRequestProperty(AUTHORIZATION, BASIC + encoding);
316             connection.setDoOutput(true);
317             connection.setDoInput(true);
318
319             if(uri.contains("searchPolicy?action=delete&")){
320                 //do something
321                 return doConnect(connection);
322             }
323
324             checkURI(request, uri, connection, item);
325
326             return doConnect(connection);
327         } catch (Exception e) {
328             policyLogger.error("Exception Occured"+e);
329         }finally{
330             if(file != null && file.exists() && file.delete()){
331                 policyLogger.info("File Deleted Successfully");
332             }
333             if (connection != null) {
334                 try {
335                     // For some reason trying to get the inputStream from the connection
336                     // throws an exception rather than returning null when the InputStream does not exist.
337                     InputStream is = connection.getInputStream();
338                     if (is != null) {
339                         is.close();
340                     }
341                 } catch (IOException ex) {
342                     policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex);
343                 }
344                 connection.disconnect();
345             }
346         }
347         return null;
348     }
349
350     private void checkURI(HttpServletRequest request, String uri, HttpURLConnection connection, FileItem item)
351         throws IOException {
352         String boundary;
353         if (!(uri.endsWith("set_BRMSParamData") || uri.contains(IMPORT_DICTIONARY))) {
354             connection.setRequestProperty(CONTENT_TYPE, PolicyController.getContenttype());
355             ObjectMapper mapper = new ObjectMapper();
356             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
357             JsonNode root = getJsonNode(request, mapper);
358
359             ObjectMapper mapper1 = new ObjectMapper();
360             mapper1.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
361
362             Object obj = mapper1.treeToValue(root, Object.class);
363             String json = mapper1.writeValueAsString(obj);
364
365             // send current configuration
366             try (InputStream content = new ByteArrayInputStream(json.getBytes());
367                 OutputStream os = connection.getOutputStream()) {
368                 int count = IOUtils.copy(content, os);
369                 if (policyLogger.isDebugEnabled()) {
370                     policyLogger.debug("copied to output, bytes=" + count);
371                 }
372             }
373         } else if (uri.endsWith("set_BRMSParamData")) {
374             connection.setRequestProperty(CONTENT_TYPE, PolicyController.getContenttype());
375             try (OutputStream os = connection.getOutputStream()) {
376                 IOUtils.copy(request.getInputStream(), os);
377             }
378         } else {
379             boundary = "===" + System.currentTimeMillis() + "===";
380             connection.setRequestProperty(CONTENT_TYPE, "multipart/form-data; boundary=" + boundary);
381             try (OutputStream os = connection.getOutputStream()) {
382                 if (item != null) {
383                     IOUtils.copy(item.getInputStream(), os);
384                 }
385             }
386         }
387     }
388
389     private JsonNode getJsonNode(HttpServletRequest request, ObjectMapper mapper) {
390         JsonNode root = null;
391         try {
392             root = mapper.readTree(request.getReader());
393         }catch (Exception e1) {
394             policyLogger.error("Exception Occured while calling PAP"+e1);
395         }
396         return root;
397     }
398
399     private String doConnect(final HttpURLConnection connection) throws IOException{
400         connection.connect();
401         int responseCode = connection.getResponseCode();
402         if(responseCode == 200){
403             // get the response content into a String
404             String responseJson = null;
405             // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
406             try(java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream())) {
407                 scanner.useDelimiter("\\A");
408                 responseJson = scanner.hasNext() ? scanner.next() : "";
409             } catch (Exception e){
410                 //Reason for rethrowing the exception is if any exception occurs during reading of inputsteam
411                 //then the exception handling is done by the outer block without returning the response immediately
412                 //Also finally block is existing only in outer block and not here so all exception handling is
413                 //done in only one place
414                 policyLogger.error("Exception Occured"+e);
415                 throw e;
416             }
417
418             policyLogger.info("JSON response from PAP: " + responseJson);
419             return responseJson;
420         }
421         return null;
422     }
423
424     @RequestMapping(value={"/getDictionary/*"}, method={RequestMethod.GET})
425     public void getDictionaryController(HttpServletRequest request, HttpServletResponse response){
426         String uri = request.getRequestURI().replace("/getDictionary", "");
427         String body;
428         ResponseEntity<?> responseEntity = sendToPAP(null, uri, HttpMethod.GET);
429         if(responseEntity != null){
430             body = responseEntity.getBody().toString();
431         }else{
432             body = "";
433         }
434         try {
435             response.getWriter().write(body);
436         } catch (IOException e) {
437             policyLogger.error("Exception occured while getting Dictionary entries", e);
438         }
439     }
440
441     @RequestMapping(value={"/saveDictionary/*/*"}, method={RequestMethod.POST})
442     public void saveDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException{
443         String userId = "";
444         String uri = request.getRequestURI().replace("/saveDictionary", "");
445         if(uri.startsWith("/")){
446             uri = uri.substring(uri.indexOf('/')+1);
447         }
448         uri = ONAP + uri.substring(uri.indexOf('/'));
449         if(uri.contains(IMPORT_DICTIONARY)){
450             userId = UserUtils.getUserSession(request).getOrgUserId();
451             uri = uri+ "?userId=" +userId;
452         }
453
454         policyLogger.info("****************************************Logging UserID while Saving Dictionary*****************************************************");
455         policyLogger.info(USER_ID + userId);
456         policyLogger.info("***********************************************************************************************************************************");
457
458         String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
459         if(body != null && !body.isEmpty()){
460             response.getWriter().write(body);
461         }else{
462             response.getWriter().write("Failed");
463         }
464     }
465
466     @RequestMapping(value={"/deleteDictionary/*/*"}, method={RequestMethod.POST})
467     public void deletetDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException {
468         String uri = request.getRequestURI().replace("/deleteDictionary", "");
469         if(uri.startsWith("/")){
470             uri = uri.substring(uri.indexOf('/')+1);
471         }
472         uri = ONAP + uri.substring(uri.indexOf('/'));
473
474         String userId = UserUtils.getUserSession(request).getOrgUserId();
475         policyLogger.info("****************************************Logging UserID while Deleting Dictionary*****************************************************");
476         policyLogger.info(USER_ID + userId);
477         policyLogger.info("*************************************************************************************************************************************");
478
479         String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
480         if(body != null && !body.isEmpty()){
481             response.getWriter().write(body);
482         }else{
483             response.getWriter().write("Failed");
484         }
485     }
486
487     @RequestMapping(value={"/searchDictionary"}, method={RequestMethod.POST})
488     public ModelAndView searchDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException {
489         Object resultList;
490         String uri = request.getRequestURI();
491         if(uri.startsWith("/")){
492             uri = uri.substring(uri.indexOf('/')+1);
493         }
494         uri = ONAP + uri.substring(uri.indexOf('/'));
495         try{
496             String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
497             if(body.contains("CouldNotConnectException")){
498                 List<String> data = new ArrayList<>();
499                 data.add("Elastic Search Server is down");
500                 resultList = data;
501             }else{
502                 JSONObject json = new JSONObject(body);
503                 resultList = json.get("policyresult");
504             }
505         }catch(Exception e){
506             policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception Occured while querying Elastic Search: " + e);
507             List<String> data = new ArrayList<>();
508             data.add("Elastic Search Server is down");
509             resultList = data;
510         }
511
512         response.setCharacterEncoding(PolicyController.getCharacterencoding());
513         response.setContentType(PolicyController.getContenttype());
514         PrintWriter out = response.getWriter();
515         JSONObject j = new JSONObject("{result: " + resultList + "}");
516         out.write(j.toString());
517         return null;
518     }
519
520     @RequestMapping(value={"/searchPolicy"}, method={RequestMethod.POST})
521     public ModelAndView searchPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException{
522         Object resultList;
523         String uri = request.getRequestURI()+"?action=search";
524         if(uri.startsWith("/")){
525             uri = uri.substring(uri.indexOf('/')+1);
526         }
527         uri = ONAP + uri.substring(uri.indexOf('/'));
528         String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
529
530         JSONObject json = new JSONObject(body);
531         try{
532             resultList = json.get("policyresult");
533         }catch(Exception e){
534             List<String> data = new ArrayList<>();
535             resultList = json.get(DATA);
536             data.add("Exception");
537             data.add(resultList.toString());
538             resultList = data;
539             policyLogger.error("Exception Occured while searching for Policy in Elastic Database" +e);
540         }
541
542         response.setCharacterEncoding(UTF_8);
543         response.setContentType("application / json");
544         request.setCharacterEncoding(UTF_8);
545
546         PrintWriter out = response.getWriter();
547         JSONObject j = new JSONObject("{result: " + resultList + "}");
548         out.write(j.toString());
549         return null;
550     }
551
552     public void deleteElasticData(String fileName){
553         String uri = "searchPolicy?action=delete&policyName='"+fileName+"'";
554         callPAP(null, "POST", uri.trim());
555     }
556
557     public String notifyOtherPAPSToUpdateConfigurations(String mode, String newName, String oldName){
558         String uri = "onap/notifyOtherPAPs?action="+mode+"&newPolicyName="+newName+"&oldPolicyName="+oldName+"";
559         return callPAP(null, "POST", uri.trim());
560     }
561
562 }