Initial OpenECOMP policy/engine commit
[policy/engine.git] / ecomp-sdk-app / src / main / java / org / openecomp / policy / controller / CreatePolicyController.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
21 package org.openecomp.policy.controller;
22
23
24 import java.io.BufferedReader;
25 import java.io.File;
26 import java.io.FileNotFoundException;
27 import java.io.FileReader;
28 import java.io.IOException;
29 import java.io.PrintWriter;
30 import java.nio.file.Path;
31 import java.nio.file.Paths;
32 import java.util.ArrayList;
33 import java.util.HashMap;
34 import java.util.Iterator;
35 import java.util.LinkedHashMap;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.UUID;
39
40 import javax.servlet.http.HttpServletRequest;
41 import javax.servlet.http.HttpServletResponse;
42
43 //import org.apache.commons.logging.Log;
44 //import org.apache.commons.logging.LogFactory;
45 import org.json.JSONObject;
46 import org.openecomp.policy.adapter.PolicyAdapter;
47 import org.openecomp.policy.admin.PolicyNotificationMail;
48 import org.openecomp.policy.admin.RESTfulPAPEngine;
49 import org.openecomp.policy.dao.PolicyVersionDao;
50 import org.openecomp.policy.dao.RuleAlgorithmsDao;
51 import org.openecomp.policy.dao.WatchPolicyNotificationDao;
52 import org.openecomp.policy.elk.client.PolicyElasticSearchController;
53 import org.openecomp.policy.rest.jpa.PolicyVersion;
54 import org.openecomp.policy.rest.jpa.RuleAlgorithms;
55 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
56 import org.openecomp.portalsdk.core.web.support.JsonMessage;
57 import org.openecomp.portalsdk.core.web.support.UserUtils;
58 import org.springframework.beans.factory.annotation.Autowired;
59 import org.springframework.http.MediaType;
60 import org.springframework.stereotype.Controller;
61 import org.springframework.web.bind.annotation.RequestMapping;
62 import org.springframework.web.servlet.ModelAndView;
63
64 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
65 import org.openecomp.policy.common.logging.flexlogger.Logger;
66
67 import com.att.research.xacml.api.XACML3;
68 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
69 import org.openecomp.policy.xacml.util.XACMLPolicyScanner;
70 import com.fasterxml.jackson.databind.DeserializationFeature;
71 import com.fasterxml.jackson.databind.JsonNode;
72 import com.fasterxml.jackson.databind.ObjectMapper;
73 import com.google.common.base.Joiner;
74
75 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
76 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
77 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
78 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
79 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
80 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
81 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
82 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
83
84 @Controller
85 @RequestMapping("/")
86 public class CreatePolicyController extends RestrictedBaseController{
87         private static Logger logger    = FlexLogger.getLogger(CreatePolicyController.class);
88          
89         private static RuleAlgorithmsDao ruleAlgorithmsDao;
90         private static PolicyVersionDao policyVersionDao;
91         private static WatchPolicyNotificationDao policyNotificationDao;
92         
93         @Autowired
94         private CreatePolicyController(RuleAlgorithmsDao ruleAlgorithmsDao, PolicyVersionDao policyVersionDao, WatchPolicyNotificationDao policyNotificationDao){
95                 CreatePolicyController.policyVersionDao = policyVersionDao;
96                 CreatePolicyController.ruleAlgorithmsDao = ruleAlgorithmsDao;
97                 CreatePolicyController.policyNotificationDao = policyNotificationDao;
98         }
99         
100         public CreatePolicyController(){}
101         
102         protected PolicyAdapter policyAdapter = null;
103         private String ruleID = "";
104         private ArrayList<Object> attributeList;
105         boolean isValidForm = false;
106         private int riskLevelCount; 
107         
108         public String newPolicyID() {
109                 return Joiner.on(':').skipNulls().join((PolicyController.getDomain().startsWith("urn") ? null: "urn"),
110                                 PolicyController.getDomain().replaceAll("[/\\\\.]", ":"), "xacml", "policy", "id", UUID.randomUUID());
111         }
112
113         @RequestMapping(value={"/get_RiskLevelValues"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
114         public void getRiskLevelValuesData(HttpServletRequest request, HttpServletResponse response){
115                 try{
116                         Map<String, Object> model = new HashMap<String, Object>();
117                         ObjectMapper mapper = new ObjectMapper();
118                         List<String> riskLevelList = new ArrayList<String>();
119                         riskLevelCount = 5;
120                         for (int i = 1; i <= riskLevelCount; i++) {
121                                 riskLevelList.add(String.valueOf(i));
122                         }
123                         model.put("riskLevelDatas", mapper.writeValueAsString(riskLevelList));
124                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
125                         JSONObject j = new JSONObject(msg);
126                         response.getWriter().write(j.toString());
127                 }
128                 catch (Exception e){
129                         e.printStackTrace();
130                 }
131         }
132         
133         @RequestMapping(value={"/get_GuardlValues"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
134         public void getGuardValuesData(HttpServletRequest request, HttpServletResponse response){
135                 try{
136                         Map<String, Object> model = new HashMap<String, Object>();
137                         ObjectMapper mapper = new ObjectMapper();
138                         List<String> guardList = new ArrayList<String>();
139                         guardList.add("True");
140                         guardList.add("False");
141                         model.put("guardDatas", mapper.writeValueAsString(guardList));
142                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
143                         JSONObject j = new JSONObject(msg);
144                         response.getWriter().write(j.toString());
145                 }
146                 catch (Exception e){
147                         e.printStackTrace();
148                 }
149         }
150
151         
152         @RequestMapping(value={"/policyController/save_policy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
153         public ModelAndView savePolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{
154                 try {
155                         String userId = UserUtils.getUserIdFromCookie(request);
156                         RESTfulPAPEngine engine = (RESTfulPAPEngine) PolicyController.getPapEngine();
157                         ObjectMapper mapper = new ObjectMapper();
158                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
159                         JsonNode root = mapper.readTree(request.getReader());
160                         PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyAdapter.class);
161                         policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", ""));
162                         if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){
163                                 policyData.isEditPolicy = true;
164                         }
165                         
166                         if (policyData.getTtlDate()==null){
167                                 policyData.setTtlDate("NA");
168                         }else{
169                                 String dateTTL = policyData.getTtlDate();
170                                 String newDate = convertDate(dateTTL, false);
171                                 policyData.setTtlDate(newDate);
172                         }
173                         
174                         if(root.get("policyData").get("model").get("path").size() != 0){
175                                 String dirName = "";
176                                 for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){
177                                         dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator;
178                                 }
179                                 policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator)));
180                         }else{
181                                 policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", ""));
182                         }
183                         
184                         int version = 0;
185                         int highestVersion = 0;
186                         int descriptionVersion = 0;
187                         //get the highest version of policy from policy version table.
188                         //getting the sub scope domain where the policy is created or updated
189                         String dbCheckPolicyName = policyData.getDomainDir() + File.separator + "Config_" + policyData.getPolicyName();
190                         List<PolicyVersion> policyVersionlist = policyVersionDao.getPolicyVersionEntityByName(dbCheckPolicyName);
191                         if (policyVersionlist.size() > 0) {             
192                                 for(int i = 0;  i < policyVersionlist.size(); i++) {
193                                         PolicyVersion entityItem = policyVersionlist.get(i);
194                                         if(entityItem.getPolicyName().equals(dbCheckPolicyName)){
195                                                 highestVersion = entityItem.getHigherVersion();
196                                         }
197                                 }
198                         }               
199                         if(highestVersion != 0){
200                                 version = highestVersion;
201                                 descriptionVersion = highestVersion +1;         
202                         }else{
203                                 version = 1;
204                                 descriptionVersion = 1;
205                         }
206                         
207                         //set policy adapter values for Building JSON object containing policy data
208                         String createdBy = "";
209                         String modifiedBy = userId;
210                         if(descriptionVersion == 1){
211                                 createdBy = userId;
212                         }else{
213                                 String policyName = PolicyController.getGitPath().toAbsolutePath().toString() + File.separator + policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml";
214                                 File policyPath = new File(policyName);
215                                 try {
216                                         createdBy =     XACMLPolicyScanner.getCreatedBy(policyPath.toPath());
217                                 } catch (IOException e) {
218                                         createdBy = "guest";
219                                 }
220                         }
221                         
222                         policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:");
223                         
224                         Map<String, String> successMap = new HashMap<String, String>();
225                         Map<String, String> attributeMap = new HashMap<String, String>();
226                         //set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON
227                         List<RuleAlgorithms> ruleAlgorithmList = ruleAlgorithmsDao.getRuleAlgorithms();
228                         for (int i = 0; i < ruleAlgorithmList.size(); i++) {
229                                 RuleAlgorithms a = ruleAlgorithmList.get(i);
230                                 if (a.getXacmlId().equals(XACML3.ID_RULE_PERMIT_OVERRIDES.stringValue())) {
231                                         policyData.setRuleCombiningAlgId(a.getXacmlId());
232                                         break;
233                                 }
234                         }
235                         
236                         if(policyData.getAttributes().size() > 0){
237                                 for(Object attribute : policyData.getAttributes()){
238                                         if(attribute instanceof LinkedHashMap<?, ?>){
239                                                 String key = ((LinkedHashMap<?, ?>) attribute).get("option").toString();
240                                                 String value = ((LinkedHashMap<?, ?>) attribute).get("number").toString();
241                                                 attributeMap.put(key, value);   
242                                         }
243                                 }
244                         }
245                         policyData.setDynamicFieldConfigAttributes(attributeMap);
246                         
247                         if (policyData.isEditPolicy()){
248                                 //increment the version and set in policyAdapter                        
249                                 policyData.setVersion(String.valueOf(version));
250                                 policyData.setHighestVersion(version);
251                                 policyData.setPolicyID(this.newPolicyID());
252                                 policyData.setRuleID(ruleID);
253                                 successMap = engine.updatePolicyRequest(policyData);
254                         } else {
255                                 //send it for policy creation
256                                 policyData.setVersion(String.valueOf(version));
257                                 policyData.setHighestVersion(version);
258                                 successMap = engine.createPolicyRequest(policyData);
259
260                         }
261
262                         if (successMap.containsKey("success")) {
263                                 // Add it into our tree
264                                 Path finalPolicyPath = null;
265                                 finalPolicyPath = Paths.get(successMap.get("success"));
266                                 PolicyElasticSearchController controller = new PolicyElasticSearchController();
267                                 controller.updateElk(finalPolicyPath.toString());
268                                 File file = finalPolicyPath.toFile();
269                                 if(file != null){
270                                         String policyName = file.toString();
271                                         String removePath = policyName.substring(policyName.indexOf("repository")+11);
272                                         String removeXml = removePath.replace(".xml", "");
273                                         String removeExtension = removeXml.substring(0, removeXml.indexOf("."));
274                                         List<PolicyVersion> versionList = policyVersionDao.getPolicyVersionEntityByName(removeExtension);
275                                         if (versionList.size() > 0) {           
276                                                 for(int i = 0;  i < versionList.size(); i++) {
277                                                 PolicyVersion entityItem = versionList.get(i);
278                                                         if(entityItem.getPolicyName().equals(removeExtension)){
279                                                                 version = entityItem.getHigherVersion() +1;
280                                                                 entityItem.setActiveVersion(version);
281                                                                 entityItem.setHigherVersion(version);
282                                                                 entityItem.setModifiedBy(userId);
283                                                                 policyVersionDao.update(entityItem);
284                                                                 if(policyData.isEditPolicy){
285                                                                         PolicyNotificationMail email = new PolicyNotificationMail();
286                                                                         String mode = "EditPolicy";
287                                                                         String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml";
288                                                                         email.sendMail(entityItem, policyNameForEmail, mode, policyNotificationDao);
289                                                                 }
290                                                         }
291                                                 }
292                                         }else{
293                                                 PolicyVersion entityItem = new PolicyVersion();
294                                                 entityItem.setActiveVersion(version);
295                                                 entityItem.setHigherVersion(version);
296                                                 entityItem.setPolicyName(removeExtension);
297                                                 entityItem.setCreatedBy(userId);
298                                                 entityItem.setModifiedBy(userId);
299                                                 policyVersionDao.Save(entityItem);
300                                         }       
301                                 }
302                         }
303                         response.setCharacterEncoding("UTF-8");
304                         response.setContentType("application / json");
305                         request.setCharacterEncoding("UTF-8");
306
307                         PrintWriter out = response.getWriter();
308                         String responseString = mapper.writeValueAsString(successMap);
309                         JSONObject j = new JSONObject("{policyData: " + responseString + "}");
310                         out.write(j.toString());
311                         return null;
312                 }
313                 catch (Exception e){
314                         response.setCharacterEncoding("UTF-8");
315                         request.setCharacterEncoding("UTF-8");
316                         PrintWriter out = response.getWriter();
317                         out.write(e.getMessage());
318                 }
319                 return null;
320         }
321         
322         private String convertDate(String dateTTL, boolean portalType) {
323                 String formateDate = null;
324                 String[] date;
325                 String[] parts;
326                 
327                 if (portalType){
328                         parts = dateTTL.split("-");
329                         formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z";
330                 } else {
331                         date  = dateTTL.split("T");
332                         parts = date[0].split("-");
333                         formateDate = parts[2] + "-" + parts[1] + "-" + parts[0];
334                 }
335                 return formateDate;
336         }
337
338         public void PrePopulateBaseConfigPolicyData(PolicyAdapter policyAdapter) {
339                 attributeList = new ArrayList<Object>();
340                 if (policyAdapter.getPolicyData() instanceof PolicyType) {
341                         Object policyData = policyAdapter.getPolicyData();
342                         PolicyType policy = (PolicyType) policyData;
343                         policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
344                         policyAdapter.setConfigBodyData(readBaseConfigJSONFile(policyAdapter));
345                         String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("_") + 1 , policyAdapter.getPolicyName().lastIndexOf("."));
346                         policyAdapter.setPolicyName(policyNameValue);
347                         String description = "";
348                         try{
349                                 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
350                         }catch(Exception e){
351                                 description = policy.getDescription();
352                         }
353                         policyAdapter.setPolicyDescription(description);
354                         // Get the target data under policy.
355                         TargetType target = policy.getTarget();
356                         if (target != null) {
357                                 // Under target we have AnyOFType
358                                 List<AnyOfType> anyOfList = target.getAnyOf();
359                                 if (anyOfList != null) {
360                                         Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
361                                         while (iterAnyOf.hasNext()) {
362                                                 AnyOfType anyOf = iterAnyOf.next();
363                                                 // Under AnyOFType we have AllOFType
364                                                 List<AllOfType> allOfList = anyOf.getAllOf();
365                                                 if (allOfList != null) {
366                                                         Iterator<AllOfType> iterAllOf = allOfList.iterator();
367                                                         int index = 0;
368                                                         while (iterAllOf.hasNext()) {
369                                                                 AllOfType allOf = iterAllOf.next();
370                                                                 // Under AllOFType we have Match
371                                                                 List<MatchType> matchList = allOf.getMatch();
372                                                                 if (matchList != null) {
373                                                                         Iterator<MatchType> iterMatch = matchList.iterator();
374                                                                         while (iterMatch.hasNext()) {
375                                                                                 MatchType match = iterMatch.next();
376                                                                                 //
377                                                                                 // Under the match we have attributevalue and
378                                                                                 // attributeDesignator. So,finally down to the actual attribute.
379                                                                                 //
380                                                                                 AttributeValueType attributeValue = match.getAttributeValue();
381                                                                                 String value = (String) attributeValue.getContent().get(0);
382                                                                                 AttributeDesignatorType designator = match.getAttributeDesignator();
383                                                                                 String attributeId = designator.getAttributeId();
384                                                                                 // First match in the target is EcompName, so set that value.
385                                                                                 if (index == 1) {
386                                                                                         policyAdapter.setEcompName(value);
387                                                                                 }
388                                                                                 if (index ==  2){
389                                                                                         policyAdapter.setRiskType(value);
390                                                                                 }
391
392                                                                                 if (index ==  3){
393                                                                                         policyAdapter.setRiskLevel(value);
394                                                                                 }
395                                                                                 
396                                                                                 if (index ==  4){
397                                                                                         policyAdapter.setGuard(value);
398                                                                                 }
399                                                                                 if (index == 5 && !value.contains("NA")){
400                                                                                         String newDate = convertDate(value, true);
401                                                                                         policyAdapter.setTtlDate(newDate);
402                                                                                 }
403                                                                                 if (index == 6){
404                                                                                         policyAdapter.setConfigName(value);
405                                                                                 }
406                                                                                 // After Ecomp and Config it is optional to have attributes, so
407                                                                                 // check weather dynamic values or there or not.
408                                                                                 if (index >= 7) {
409                                                                                         Map<String, String> attribute = new HashMap<String, String>();
410                                                                                         attribute.put("option", attributeId);
411                                                                                         attribute.put("number", value);
412                                                                                         attributeList.add(attribute);
413                                                                                 }
414                                                                                 index++;
415                                                                         }
416                                                                 }
417                                                         }
418                                                 }
419                                         }
420                                 }
421                                 
422                                 policyAdapter.setAttributes(attributeList);
423                         }
424                         List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
425                         for (Object o : ruleList) {
426                                 if (o instanceof RuleType) {
427                                         // get the condition data under the rule for rule  Algorithms.
428                                         policyAdapter.setRuleID(((RuleType) o).getRuleId());
429                                 }
430                         }
431                 }               
432         }
433
434         private String readBaseConfigJSONFile(PolicyAdapter policyAdapter) {
435                 String fileName = policyAdapter.getPolicyName();
436                 String fileLocation = null;
437                 if (fileName != null && fileName.contains("Config")) {
438                         fileLocation = PolicyController.getConfigHome();
439                 }
440                 if (logger.isDebugEnabled()) {
441                         logger.debug("Attempting to read file from the location: " + fileLocation);
442                 }
443
444                 if (fileLocation == null) {
445                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error with the FileName: " + fileName);
446                         return fileLocation;
447                 }
448
449
450                 File dir = new File(fileLocation);
451                 File[] listOfFiles = dir.listFiles();
452                 String extension = null;
453                 for (File file : listOfFiles) {
454                         if (file.isFile() && file.getName().contains(fileName)) {
455                                 // For config form we have set the ConfigType Based on the extention.
456                                 if (fileName.contains("Config")) {
457                                         extension = file.getName().substring(file.getName().lastIndexOf('.') + 1);
458                                         // Based on file type set Combobox config value
459                                         if (extension.equals("txt")) {
460                                                 policyAdapter.setConfigType("OTHER");
461                                         } else {
462                                                 policyAdapter.setConfigType(extension.toUpperCase());
463                                         }
464                                 }
465                                 // Reading the file
466                                 try (BufferedReader br = new BufferedReader(new FileReader(file))) {
467                                         StringBuilder sb = new StringBuilder();
468                                         String line = br.readLine();
469                                         while (line != null) {
470                                                 sb.append(line);
471                                                 sb.append("\n");
472                                                 line = br.readLine();
473                                         }
474                                         return sb.toString();
475                                 } catch (FileNotFoundException e) {
476                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage());
477                                 } catch (IOException e1) {
478                                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e1.getMessage());
479                                 }
480                         }
481                 }
482                 return null;
483         }
484 }