Merge "Sonar cleanup for PolicyEngineUtils"
[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 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("model").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                                         CreateClosedLoopFaultController faultController = new CreateClosedLoopFaultController();
145                                         policyData = faultController.setDataToPolicyRestAdapter(policyData, root);
146                                 }else if("Firewall Config".equalsIgnoreCase(policyData.getConfigPolicyType())){
147                                         CreateFirewallController fwController = new CreateFirewallController();
148                                         policyData = fwController.setDataToPolicyRestAdapter(policyData);
149                                 }else if("Micro Service".equalsIgnoreCase(policyData.getConfigPolicyType())){
150                                         CreateDcaeMicroServiceController msController = new CreateDcaeMicroServiceController();
151                                         policyData = msController.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 = 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 = 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                                 java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream());
342                                 scanner.useDelimiter("\\A");
343                                 responseJson =  scanner.hasNext() ? scanner.next() : "";
344                                 scanner.close();
345                                 policyLogger.info("JSON response from PAP: " + responseJson);
346                                 return responseJson;
347                         }
348
349                 } catch (Exception e) {
350                         policyLogger.error("Exception Occured"+e);
351                 }finally{
352                         if(file != null && file.exists() && file.delete()){
353                                 policyLogger.info("File Deleted Successfully");
354                         }
355                         if (connection != null) {
356                                 try {
357                                         // For some reason trying to get the inputStream from the connection
358                                         // throws an exception rather than returning null when the InputStream does not exist.
359                                         InputStream is = connection.getInputStream();
360                                         if (is != null) {
361                                                 is.close();
362                                         }
363                                 } catch (IOException ex) {
364                                         policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex);
365                                 }
366                                 connection.disconnect();
367                         }
368                 }
369                 return null;
370         }
371         
372         @RequestMapping(value={"/getDictionary/*"}, method={RequestMethod.GET})
373         public void getDictionaryController(HttpServletRequest request, HttpServletResponse response){
374                 String uri = request.getRequestURI().replace("/getDictionary", "");
375                 String body = null;
376                 ResponseEntity<?> responseEntity = sendToPAP(null, uri, HttpMethod.GET);
377                 if(responseEntity != null){
378                         body = responseEntity.getBody().toString();
379                 }else{
380                         body = "";
381                 }
382                 try {
383                         response.getWriter().write(body);
384                 } catch (IOException e) {
385                         policyLogger.error("Exception occured while getting Dictionary entries", e);
386                 }
387         }
388         
389         @RequestMapping(value={"/saveDictionary/*/*"}, method={RequestMethod.POST})
390         public ModelAndView saveDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException{
391                 String userId = "";
392                 String uri = request.getRequestURI().replace("/saveDictionary", "");
393                 if(uri.startsWith("/")){
394                         uri = uri.substring(uri.indexOf('/')+1);
395                 }
396                 uri = "/onap" + uri.substring(uri.indexOf('/'));
397                 if(uri.contains(importDictionary)){
398                         userId = UserUtils.getUserSession(request).getOrgUserId();
399                         uri = uri+ "?userId=" +userId;
400                 }
401                 
402                 policyLogger.info("****************************************Logging UserID while Saving Dictionary*****************************************************");
403                 policyLogger.info("UserId:  " + userId);
404                 policyLogger.info("***********************************************************************************************************************************");
405                 
406                 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
407                 response.getWriter().write(body);
408                 return null;
409         }
410         
411         @RequestMapping(value={"/deleteDictionary/*/*"}, method={RequestMethod.POST})
412         public ModelAndView 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                 response.getWriter().write(body);
426                 return null;
427         }
428         
429         @RequestMapping(value={"/searchDictionary"}, method={RequestMethod.POST})
430         public ModelAndView searchDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException {
431                 Object resultList = null;
432                 String uri = request.getRequestURI();
433                 if(uri.startsWith("/")){
434                         uri = uri.substring(uri.indexOf('/')+1);
435                 }
436                 uri = "/onap" + uri.substring(uri.indexOf('/'));
437                 try{
438                         String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
439                         if(body.contains("CouldNotConnectException")){
440                                 List<String> data = new ArrayList<>();
441                                 data.add("Elastic Search Server is down");
442                                 resultList = data;
443                         }else{
444                                 JSONObject json = new JSONObject(body);
445                                 resultList = json.get("policyresult");
446                         }
447                 }catch(Exception e){
448                         policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception Occured while querying Elastic Search: " + e);
449                         List<String> data = new ArrayList<>();
450                         data.add("Elastic Search Server is down");
451                         resultList = data;
452                 }
453                 
454                 response.setCharacterEncoding(PolicyController.getCharacterencoding());
455                 response.setContentType(PolicyController.getContenttype());
456                 PrintWriter out = response.getWriter();
457                 JSONObject j = new JSONObject("{result: " + resultList + "}");
458                 out.write(j.toString());
459                 return null;
460         }
461         
462         @RequestMapping(value={"/searchPolicy"}, method={RequestMethod.POST})
463         public ModelAndView searchPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException{
464                 Object resultList = null;
465                 String uri = request.getRequestURI()+"?action=search";
466                 if(uri.startsWith("/")){
467                         uri = uri.substring(uri.indexOf('/')+1);
468                 }
469                 uri = "/onap" + uri.substring(uri.indexOf('/'));
470                 String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
471
472                 JSONObject json = new JSONObject(body);
473                 try{
474                         resultList = json.get("policyresult");
475                 }catch(Exception e){
476                         List<String> data = new ArrayList<>();
477                         data.add("Elastic Search Server is down");
478                         resultList = data;
479                         policyLogger.error("Exception Occured while searching for Policy in Elastic Database" +e);
480                 }
481
482                 response.setCharacterEncoding("UTF-8");
483                 response.setContentType("application / json");
484                 request.setCharacterEncoding("UTF-8");
485
486                 PrintWriter out = response.getWriter();
487                 JSONObject j = new JSONObject("{result: " + resultList + "}");
488                 out.write(j.toString());
489                 return null;
490         }
491         
492         public void deleteElasticData(String fileName){
493                 String uri = "searchPolicy?action=delete&policyName='"+fileName+"'";
494                 callPAP(null, "POST", uri.trim());
495         }
496
497 }