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