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