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