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