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