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