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