Merge "Increase JUnit Code Coverage for PolicyDBDao"
[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  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21 package org.onap.policy.admin;
22
23 import java.io.ByteArrayInputStream;
24 import java.io.File;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.io.OutputStream;
28 import java.io.PrintWriter;
29 import java.net.HttpURLConnection;
30 import java.net.URL;
31 import java.nio.charset.StandardCharsets;
32 import java.util.ArrayList;
33 import java.util.Base64;
34 import java.util.List;
35
36 import javax.mail.MessagingException;
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, MessagingException {
140         JsonNode root = mapper.readTree(request.getReader());
141
142         policyLogger.info("****************************************Logging UserID while Create/Update Policy**************************************************");
143         policyLogger.info(USER_ID + userId + "Policy Data Object:  "+ root.get(PolicyController.getPolicydata()).get("policy").toString());
144         policyLogger.info("***********************************************************************************************************************************");
145
146         PolicyRestAdapter policyData = mapper.readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class);
147
148         modifyPolicyData(root, policyData);
149
150         if(policyData.getConfigPolicyType() != null){
151             if(CLOSED_LOOP_FAULT.equalsIgnoreCase(policyData.getConfigPolicyType())){
152                 policyData = new CreateClosedLoopFaultController().setDataToPolicyRestAdapter(policyData, root);
153             }else if(FIREWALL_CONFIG.equalsIgnoreCase(policyData.getConfigPolicyType())){
154                 policyData = new CreateFirewallController().setDataToPolicyRestAdapter(policyData);
155             }else if(MICRO_SERVICE.equalsIgnoreCase(policyData.getConfigPolicyType())){
156                 policyData = new CreateDcaeMicroServiceController().setDataToPolicyRestAdapter(policyData, root);
157             }else if(OPTIMIZATION.equalsIgnoreCase(policyData.getConfigPolicyType())){
158                 policyData = new CreateOptimizationController().setDataToPolicyRestAdapter(policyData, root);
159             }
160         }
161
162         policyData.setUserId(userId);
163
164         String result;
165         String body = PolicyUtils.objectToJsonString(policyData);
166         String uri = request.getRequestURI();
167         ResponseEntity<?> responseEntity = sendToPAP(body, uri, HttpMethod.POST);
168         if(responseEntity != null && responseEntity.getBody().equals(HttpServletResponse.SC_CONFLICT)){
169             result = "PolicyExists";
170         }else if(responseEntity != null){
171             result =  responseEntity.getBody().toString();
172             String policyName = responseEntity.getHeaders().get(POLICY_NAME).get(0);
173             if(policyData.isEditPolicy() && SUCCESS.equalsIgnoreCase(result)){
174                 PolicyNotificationMail email = new PolicyNotificationMail();
175                 String mode = "EditPolicy";
176                 String watchPolicyName = policyName.replace(XML, "");
177                 String version = watchPolicyName.substring(watchPolicyName.lastIndexOf('.')+1);
178                 watchPolicyName = watchPolicyName.substring(0, watchPolicyName.lastIndexOf('.')).replace(".", File.separator);
179                 String policyVersionName = watchPolicyName.replace(".", File.separator);
180                 watchPolicyName = watchPolicyName + "." + version + XML;
181                 PolicyVersion entityItem = new PolicyVersion();
182                 entityItem.setPolicyName(policyVersionName);
183                 entityItem.setActiveVersion(Integer.parseInt(version));
184                 entityItem.setModifiedBy(userId);
185                 email.sendMail(entityItem, watchPolicyName, mode, commonClassDao);
186             }
187         }else{
188             result =  "Response is null from PAP";
189         }
190
191         response.setCharacterEncoding(PolicyController.getCharacterencoding());
192         response.setContentType(PolicyController.getContenttype());
193         request.setCharacterEncoding(PolicyController.getCharacterencoding());
194
195         PrintWriter out = response.getWriter();
196         String responseString = mapper.writeValueAsString(result);
197         JSONObject j = new JSONObject("{policyData: " + responseString + "}");
198         out.write(j.toString());
199     }
200
201     private void modifyPolicyData(JsonNode root, PolicyRestAdapter policyData) {
202         if(FILE.equals(root.get(PolicyController.getPolicydata()).get(MODEL).get(TYPE).toString().replace("\"", ""))){
203             policyData.setEditPolicy(true);
204         }
205         if(root.get(PolicyController.getPolicydata()).get(MODEL).get(PATH).size() != 0){
206             String dirName = "";
207             for(int i = 0; i < root.get(PolicyController.getPolicydata()).get(MODEL).get(PATH).size(); i++){
208                 dirName = dirName.replace("\"", "") + root.get(PolicyController.getPolicydata()).get(
209                     MODEL).get(PATH).get(i).toString().replace("\"", "") + File.separator;
210             }
211             if(policyData.isEditPolicy()){
212                 policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator)));
213             }else{
214                 policyData.setDomainDir(dirName + root.get(PolicyController.getPolicydata()).get(
215                     MODEL).get(NAME).toString().replace("\"", ""));
216             }
217         }else{
218             String domain = root.get(PolicyController.getPolicydata()).get(MODEL).get(NAME).toString();
219             if(domain.contains("/")){
220                 domain = domain.substring(0, domain.lastIndexOf('/')).replace("/", File.separator);
221             }
222             domain = domain.replace("\"", "");
223             policyData.setDomainDir(domain);
224         }
225     }
226
227
228     private ResponseEntity<?> sendToPAP(String body, String requestURI, HttpMethod method){
229         String papUrl = PolicyController.getPapUrl();
230         String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
231         String papPass = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
232
233         Base64.Encoder encoder = Base64.getEncoder();
234         String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
235         HttpHeaders headers = new HttpHeaders();
236         headers.set(AUTHORIZATION, BASIC + encoding);
237         headers.set(CONTENT_TYPE, PolicyController.getContenttype());
238
239         RestTemplate restTemplate = new RestTemplate();
240         HttpEntity<?> requestEntity = new HttpEntity<>(body, headers);
241         ResponseEntity<?> result = null;
242         HttpClientErrorException exception = null;
243         String uri = requestURI;
244         if(uri.startsWith("/")){
245             uri = uri.substring(uri.indexOf('/')+1);
246         }
247         uri = "onap" + uri.substring(uri.indexOf('/'));
248         try{
249             result = restTemplate.exchange(papUrl + uri, method, requestEntity, String.class);
250         }catch(Exception e){
251             policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl, e);
252             exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
253             if("409 Conflict".equals(e.getMessage())){
254                 return ResponseEntity.ok(HttpServletResponse.SC_CONFLICT);
255             }
256         }
257         if(exception != null && exception.getStatusCode()!=null){
258             if(exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)){
259                 String message = XACMLErrorConstants.ERROR_PERMISSIONS +":"+exception.getStatusCode()+":" + "ERROR_AUTH_GET_PERM" ;
260                 policyLogger.error(message);
261             }
262             if(exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)){
263                 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
264                 policyLogger.error(message);
265             }
266             if(exception.getStatusCode().equals(HttpStatus.NOT_FOUND)){
267                 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl + exception;
268                 policyLogger.error(message);
269             }
270             String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
271             policyLogger.error(message);
272         }
273         return result;
274     }
275
276     private String callPAP(HttpServletRequest request , String method, String uriValue){
277         String uri = uriValue;
278         String papUrl = PolicyController.getPapUrl();
279         String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
280         String papPass = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
281
282         Base64.Encoder encoder = Base64.getEncoder();
283         String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
284         HttpHeaders headers = new HttpHeaders();
285         headers.set(AUTHORIZATION, BASIC + encoding);
286         headers.set(CONTENT_TYPE, PolicyController.getContenttype());
287
288
289         HttpURLConnection connection = null;
290         List<FileItem> items;
291         FileItem item = null;
292         File file = null;
293         if(uri.contains(IMPORT_DICTIONARY)){
294             try {
295                 items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
296                 item = items.get(0);
297                 file = new File(item.getName());
298                 String newFile = file.toString();
299                 uri = uri +"&dictionaryName="+newFile;
300             } catch (Exception e2) {
301                 policyLogger.error("Exception Occured while calling PAP with import dictionary request"+e2);
302             }
303         }
304
305         try {
306             URL url = new URL(papUrl + uri);
307             connection = (HttpURLConnection)url.openConnection();
308             connection.setRequestMethod(method);
309             connection.setUseCaches(false);
310             connection.setInstanceFollowRedirects(false);
311             connection.setRequestProperty(AUTHORIZATION, BASIC + encoding);
312             connection.setDoOutput(true);
313             connection.setDoInput(true);
314
315             if(uri.contains("searchPolicy?action=delete&")){
316                 //do something
317                 return doConnect(connection);
318             }
319
320             checkURI(request, uri, connection, item);
321
322             return doConnect(connection);
323         } catch (Exception e) {
324             policyLogger.error("Exception Occured"+e);
325         }finally{
326             if(file != null && file.exists() && file.delete()){
327                 policyLogger.info("File Deleted Successfully");
328             }
329             if (connection != null) {
330                 try {
331                     // For some reason trying to get the inputStream from the connection
332                     // throws an exception rather than returning null when the InputStream does not exist.
333                     InputStream is = connection.getInputStream();
334                     if (is != null) {
335                         is.close();
336                     }
337                 } catch (IOException ex) {
338                     policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex);
339                 }
340                 connection.disconnect();
341             }
342         }
343         return null;
344     }
345
346     private void checkURI(HttpServletRequest request, String uri, HttpURLConnection connection, FileItem item) throws IOException {
347         String boundary;
348         if(!(uri.endsWith("set_BRMSParamData") || uri.contains(IMPORT_DICTIONARY))){
349             connection.setRequestProperty(CONTENT_TYPE,PolicyController.getContenttype());
350             ObjectMapper mapper = new ObjectMapper();
351             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
352             JsonNode root = getJsonNode(request, mapper);
353
354             ObjectMapper mapper1 = new ObjectMapper();
355             mapper1.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
356
357             Object obj = mapper1.treeToValue(root, Object.class);
358             String json = mapper1.writeValueAsString(obj);
359
360             // send current configuration
361             try(InputStream content =  new ByteArrayInputStream(json.getBytes());
362                 OutputStream os = connection.getOutputStream()) {
363                 int count = IOUtils.copy(content, os);
364                 if (policyLogger.isDebugEnabled()) {
365                     policyLogger.debug("copied to output, bytes=" + count);
366                 }
367             }
368         }else{
369             if(uri.endsWith("set_BRMSParamData")){
370                 connection.setRequestProperty(CONTENT_TYPE,PolicyController.getContenttype());
371                 try (OutputStream os = connection.getOutputStream()) {
372                     IOUtils.copy((InputStream) request.getInputStream(), os);
373                 }
374             }else{
375                 boundary = "===" + System.currentTimeMillis() + "===";
376                 connection.setRequestProperty(CONTENT_TYPE,"multipart/form-data; boundary=" + boundary);
377                 try (OutputStream os = connection.getOutputStream()) {
378                     if(item != null){
379                         IOUtils.copy((InputStream) item.getInputStream(), os);
380                     }
381                 }
382             }
383         }
384     }
385
386     private JsonNode getJsonNode(HttpServletRequest request, ObjectMapper mapper) {
387         JsonNode root = null;
388         try {
389             root = mapper.readTree(request.getReader());
390         }catch (Exception e1) {
391             policyLogger.error("Exception Occured while calling PAP"+e1);
392         }
393         return root;
394     }
395
396     private String doConnect(final HttpURLConnection connection) throws IOException{
397         connection.connect();
398         int responseCode = connection.getResponseCode();
399         if(responseCode == 200){
400             // get the response content into a String
401             String responseJson = null;
402             // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
403             try(java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream())) {
404                 scanner.useDelimiter("\\A");
405                 responseJson = scanner.hasNext() ? scanner.next() : "";
406             } catch (Exception e){
407                 //Reason for rethrowing the exception is if any exception occurs during reading of inputsteam
408                 //then the exception handling is done by the outer block without returning the response immediately
409                 //Also finally block is existing only in outer block and not here so all exception handling is
410                 //done in only one place
411                 policyLogger.error("Exception Occured"+e);
412                 throw e;
413             }
414
415             policyLogger.info("JSON response from PAP: " + responseJson);
416             return responseJson;
417         }
418         return null;
419     }
420
421     @RequestMapping(value={"/getDictionary/*"}, method={RequestMethod.GET})
422     public void getDictionaryController(HttpServletRequest request, HttpServletResponse response){
423         String uri = request.getRequestURI().replace("/getDictionary", "");
424         String body;
425         ResponseEntity<?> responseEntity = sendToPAP(null, uri, HttpMethod.GET);
426         if(responseEntity != null){
427             body = responseEntity.getBody().toString();
428         }else{
429             body = "";
430         }
431         try {
432             response.getWriter().write(body);
433         } catch (IOException e) {
434             policyLogger.error("Exception occured while getting Dictionary entries", e);
435         }
436     }
437
438     @RequestMapping(value={"/saveDictionary/*/*"}, method={RequestMethod.POST})
439     public void saveDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException{
440         String userId = "";
441         String uri = request.getRequestURI().replace("/saveDictionary", "");
442         if(uri.startsWith("/")){
443             uri = uri.substring(uri.indexOf('/')+1);
444         }
445         uri = ONAP + uri.substring(uri.indexOf('/'));
446         if(uri.contains(IMPORT_DICTIONARY)){
447             userId = UserUtils.getUserSession(request).getOrgUserId();
448             uri = uri+ "?userId=" +userId;
449         }
450
451         policyLogger.info("****************************************Logging UserID while Saving Dictionary*****************************************************");
452         policyLogger.info(USER_ID + userId);
453         policyLogger.info("***********************************************************************************************************************************");
454
455         String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
456         if(body != null && !body.isEmpty()){
457             response.getWriter().write(body);
458         }else{
459             response.getWriter().write("Failed");
460         }
461     }
462
463     @RequestMapping(value={"/deleteDictionary/*/*"}, method={RequestMethod.POST})
464     public void deletetDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException {
465         String uri = request.getRequestURI().replace("/deleteDictionary", "");
466         if(uri.startsWith("/")){
467             uri = uri.substring(uri.indexOf('/')+1);
468         }
469         uri = ONAP + uri.substring(uri.indexOf('/'));
470
471         String userId = UserUtils.getUserSession(request).getOrgUserId();
472         policyLogger.info("****************************************Logging UserID while Deleting Dictionary*****************************************************");
473         policyLogger.info(USER_ID + userId);
474         policyLogger.info("*************************************************************************************************************************************");
475
476         String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
477         if(body != null && !body.isEmpty()){
478             response.getWriter().write(body);
479         }else{
480             response.getWriter().write("Failed");
481         }
482     }
483
484     @RequestMapping(value={"/searchDictionary"}, method={RequestMethod.POST})
485     public ModelAndView searchDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException {
486         Object resultList;
487         String uri = request.getRequestURI();
488         if(uri.startsWith("/")){
489             uri = uri.substring(uri.indexOf('/')+1);
490         }
491         uri = ONAP + uri.substring(uri.indexOf('/'));
492         try{
493             String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
494             if(body.contains("CouldNotConnectException")){
495                 List<String> data = new ArrayList<>();
496                 data.add("Elastic Search Server is down");
497                 resultList = data;
498             }else{
499                 JSONObject json = new JSONObject(body);
500                 resultList = json.get("policyresult");
501             }
502         }catch(Exception e){
503             policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception Occured while querying Elastic Search: " + e);
504             List<String> data = new ArrayList<>();
505             data.add("Elastic Search Server is down");
506             resultList = data;
507         }
508
509         response.setCharacterEncoding(PolicyController.getCharacterencoding());
510         response.setContentType(PolicyController.getContenttype());
511         PrintWriter out = response.getWriter();
512         JSONObject j = new JSONObject("{result: " + resultList + "}");
513         out.write(j.toString());
514         return null;
515     }
516
517     @RequestMapping(value={"/searchPolicy"}, method={RequestMethod.POST})
518     public ModelAndView searchPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException{
519         Object resultList;
520         String uri = request.getRequestURI()+"?action=search";
521         if(uri.startsWith("/")){
522             uri = uri.substring(uri.indexOf('/')+1);
523         }
524         uri = ONAP + uri.substring(uri.indexOf('/'));
525         String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
526
527         JSONObject json = new JSONObject(body);
528         try{
529             resultList = json.get("policyresult");
530         }catch(Exception e){
531             List<String> data = new ArrayList<>();
532             resultList = json.get(DATA);
533             data.add("Exception");
534             data.add(resultList.toString());
535             resultList = data;
536             policyLogger.error("Exception Occured while searching for Policy in Elastic Database" +e);
537         }
538
539         response.setCharacterEncoding(UTF_8);
540         response.setContentType("application / json");
541         request.setCharacterEncoding(UTF_8);
542
543         PrintWriter out = response.getWriter();
544         JSONObject j = new JSONObject("{result: " + resultList + "}");
545         out.write(j.toString());
546         return null;
547     }
548
549     public void deleteElasticData(String fileName){
550         String uri = "searchPolicy?action=delete&policyName='"+fileName+"'";
551         callPAP(null, "POST", uri.trim());
552     }
553
554     public String notifyOtherPAPSToUpdateConfigurations(String mode, String newName, String oldName){
555         String uri = "onap/notifyOtherPAPs?action="+mode+"&newPolicyName="+newName+"&oldPolicyName="+oldName+"";
556         return callPAP(null, "POST", uri.trim());
557     }
558
559 }