Initial OpenECOMP policy/engine commit
[policy/engine.git] / ecomp-sdk-app / src / main / java / org / openecomp / policy / controller / CreateClosedLoopPMController.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.File;
25 import java.io.FileInputStream;
26 import java.io.FileNotFoundException;
27 import java.io.IOException;
28 import java.io.PrintWriter;
29 import java.nio.file.Path;
30 import java.nio.file.Paths;
31 import java.text.DateFormat;
32 import java.text.ParseException;
33 import java.text.SimpleDateFormat;
34 import java.util.Date;
35 import java.util.HashMap;
36 import java.util.Iterator;
37 import java.util.LinkedHashMap;
38 import java.util.List;
39 import java.util.Map;
40 import java.util.UUID;
41
42 import javax.json.Json;
43 import javax.json.JsonReader;
44 import javax.servlet.http.HttpServletRequest;
45 import javax.servlet.http.HttpServletResponse;
46
47 import org.json.JSONObject;
48 import org.openecomp.policy.adapter.ClosedLoopPMBody;
49 import org.openecomp.policy.adapter.PolicyAdapter;
50 import org.openecomp.policy.admin.PolicyNotificationMail;
51 import org.openecomp.policy.admin.RESTfulPAPEngine;
52 import org.openecomp.policy.dao.PolicyVersionDao;
53 import org.openecomp.policy.dao.RuleAlgorithmsDao;
54 import org.openecomp.policy.dao.WatchPolicyNotificationDao;
55 import org.openecomp.policy.elk.client.PolicyElasticSearchController;
56 import org.openecomp.policy.rest.jpa.PolicyVersion;
57 import org.openecomp.policy.rest.jpa.RuleAlgorithms;
58 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
59 import org.openecomp.portalsdk.core.web.support.UserUtils;
60 import org.springframework.beans.factory.annotation.Autowired;
61 import org.springframework.stereotype.Controller;
62 import org.springframework.web.bind.annotation.RequestMapping;
63 import org.springframework.web.servlet.ModelAndView;
64
65 import com.att.research.xacml.api.XACML3;
66 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
67 import org.openecomp.policy.xacml.util.XACMLPolicyScanner;
68 import com.fasterxml.jackson.databind.DeserializationFeature;
69 import com.fasterxml.jackson.databind.JsonNode;
70 import com.fasterxml.jackson.databind.ObjectMapper;
71 import com.google.common.base.Joiner;
72
73 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
74 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
75 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
76 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
77 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
78 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
79
80 @Controller
81 @RequestMapping("/")
82 public class CreateClosedLoopPMController extends RestrictedBaseController{
83
84         private static RuleAlgorithmsDao ruleAlgorithmsDao;
85         private static PolicyVersionDao policyVersionDao;
86         private static WatchPolicyNotificationDao policyNotificationDao;
87         
88         @Autowired
89         private CreateClosedLoopPMController(RuleAlgorithmsDao ruleAlgorithmsDao, PolicyVersionDao policyVersionDao, WatchPolicyNotificationDao policyNotificationDao){
90                 CreateClosedLoopPMController.policyVersionDao = policyVersionDao;
91                 CreateClosedLoopPMController.ruleAlgorithmsDao = ruleAlgorithmsDao;
92                 CreateClosedLoopPMController.policyNotificationDao = policyNotificationDao;
93         }
94         
95         public CreateClosedLoopPMController(){}
96         
97         protected PolicyAdapter policyAdapter = null;
98         private String ruleID = "";
99                 
100         public String newPolicyID() {
101                 return Joiner.on(':').skipNulls().join((PolicyController.getDomain().startsWith("urn") ? null: "urn"),
102                                 PolicyController.getDomain().replaceAll("[/\\\\.]", ":"), "xacml", "policy", "id", UUID.randomUUID());
103         }
104
105         @RequestMapping(value={"/policyController/save_PMPolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
106         public ModelAndView savePMPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{
107                 try {
108                         String userId = UserUtils.getUserIdFromCookie(request);
109                         RESTfulPAPEngine engine = (RESTfulPAPEngine) PolicyController.getPapEngine();
110                         ObjectMapper mapper = new ObjectMapper();
111                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
112                         JsonNode root = mapper.readTree(request.getReader());
113                         PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyAdapter.class);
114                         
115                         if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){
116                                 policyData.isEditPolicy = true;
117                         }
118                         if(root.get("policyData").get("model").get("path").size() != 0){
119                                 String dirName = "";
120                                 for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){
121                                         dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator;
122                                 }
123                                 policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator)));
124                         }else{
125                                 policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", ""));
126                         }
127                         
128                         if (policyData.getTtlDate()==null){
129                                 policyData.setTtlDate("NA");
130                         }else{
131                                 String dateTTL = policyData.getTtlDate();
132                                 String newDate = convertDate(dateTTL);
133                                 policyData.setTtlDate(newDate);
134                         }
135                         
136                         int version = 0;
137                         int highestVersion = 0;
138                         int descriptionVersion = 0;
139                         //get the highest version of policy from policy version table.
140                         //getting the sub scope domain where the policy is created or updated
141                         String dbCheckPolicyName = policyData.getDomainDir() + File.separator + "Config_PM_" + policyData.getPolicyName();
142                         List<PolicyVersion> policyVersionList = policyVersionDao.getPolicyVersionEntityByName(dbCheckPolicyName);
143                         if (policyVersionList.size() > 0) {             
144                                 for(int i = 0;  i < policyVersionList.size(); i++) {
145                                         PolicyVersion entityItem = policyVersionList.get(i);
146                                         if(entityItem.getPolicyName().equals(dbCheckPolicyName)){
147                                                 highestVersion = entityItem.getHigherVersion();
148                                         }
149                                 }
150                         }               
151                         if(highestVersion != 0){
152                                 version = highestVersion;
153                                 descriptionVersion = highestVersion +1;         
154                         }else{
155                                 version = 1;
156                                 descriptionVersion = 1;
157                         }
158                         
159                         //set policy adapter values for Building JSON object containing policy data
160                         String createdBy = "";
161                         String modifiedBy = userId;
162                         if(descriptionVersion == 1){
163                                 createdBy = userId;
164                         }else{
165                                 String policyName = PolicyController.getGitPath().toAbsolutePath().toString() + File.separator + policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml";
166                                 File policyPath = new File(policyName);
167                                 try {
168                                         createdBy =     XACMLPolicyScanner.getCreatedBy(policyPath.toPath());
169                                 } catch (IOException e) {
170                                         createdBy = "guest";
171                                 }
172                         }
173                         
174                         policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:");
175                         
176                         
177                         if(policyData.getServiceTypePolicyName() != null){
178                                 policyData.setServiceType(policyData.getServiceTypePolicyName().get("serviceTypePolicyName").toString());
179                         }
180                         
181                         ObjectMapper jsonMapper = new ObjectMapper();
182                         String jsonBody = jsonMapper.writeValueAsString(policyData.getJsonBodyData());
183                         jsonBody = jsonBody.replaceFirst("\\{", "\\{\"serviceTypePolicyName\": \"serviceTypeFieldValue\",");
184                         jsonBody = jsonBody.replace("serviceTypeFieldValue", policyData.getServiceType());
185                         policyData.setJsonBody(jsonBody);
186                         
187                         Map<String, String> successMap = new HashMap<String, String>();
188                         
189                         //set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON
190                         List<RuleAlgorithms> ruleAlgorithmsList = ruleAlgorithmsDao.getRuleAlgorithms();
191                         for (int i = 0; i < ruleAlgorithmsList.size(); i++) {
192                                 RuleAlgorithms a = ruleAlgorithmsList.get(i);
193                                 if (a.getXacmlId().equals(XACML3.ID_RULE_PERMIT_OVERRIDES.stringValue())) {
194                                         policyData.setRuleCombiningAlgId(a.getXacmlId());
195                                         break;
196                                 }
197                         }
198                         
199                         if (policyData.isEditPolicy()){
200                                 //increment the version and set in policyAdapter
201                                 policyData.setVersion(String.valueOf(version));
202                                 policyData.setHighestVersion(version);
203                                 policyData.setPolicyID(this.newPolicyID());
204                                 policyData.setRuleID(ruleID);
205                                 successMap = engine.updatePolicyRequest(policyData);
206                         } else {
207                                 //send it for policy creation
208                                 policyData.setVersion(String.valueOf(version));
209                                 policyData.setHighestVersion(version);
210                                 successMap = engine.createPolicyRequest(policyData);
211
212                         }
213
214                         if (successMap.containsKey("success")) {
215                                 // Add it into our tree
216                                 Path finalPolicyPath = null;
217                                 finalPolicyPath = Paths.get(successMap.get("success"));
218                                 PolicyElasticSearchController controller = new PolicyElasticSearchController();
219                                 controller.updateElk(finalPolicyPath.toString());
220                                 File file = finalPolicyPath.toFile();
221                                 if(file != null){
222                                         String policyName = file.toString();
223                                         String removePath = policyName.substring(policyName.indexOf("repository")+11);
224                                         String removeXml = removePath.replace(".xml", "");
225                                         String removeExtension = removeXml.substring(0, removeXml.indexOf("."));
226                                         List<PolicyVersion> versionList = policyVersionDao.getPolicyVersionEntityByName(removeExtension);
227                                         if (versionList.size() > 0) {           
228                                                 for(int i = 0;  i < versionList.size(); i++) {
229                                                         PolicyVersion entityItem = versionList.get(i);
230                                                         if(entityItem.getPolicyName().equals(removeExtension)){
231                                                                 version = entityItem.getHigherVersion() +1;
232                                                                 entityItem.setActiveVersion(version);
233                                                                 entityItem.setHigherVersion(version);
234                                                                 entityItem.setModifiedBy(userId);
235                                                                 policyVersionDao.update(entityItem);
236                                                                 if(policyData.isEditPolicy){
237                                                                         PolicyNotificationMail email = new PolicyNotificationMail();
238                                                                         String mode = "EditPolicy";
239                                                                         String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml";
240                                                                         email.sendMail(entityItem, policyNameForEmail, mode, policyNotificationDao);
241                                                                 }
242                                                         }
243                                                 }
244                                         }else{
245                                                 PolicyVersion entityItem = new PolicyVersion();
246                                                 entityItem.setActiveVersion(version);
247                                                 entityItem.setHigherVersion(version);
248                                                 entityItem.setPolicyName(removeExtension);
249                                                 entityItem.setCreatedBy(userId);
250                                                 entityItem.setModifiedBy(userId);
251                                                 policyVersionDao.Save(entityItem);
252                                         }
253                                 }
254                         }
255                         response.setCharacterEncoding("UTF-8");
256                         response.setContentType("application / json");
257                         request.setCharacterEncoding("UTF-8");
258
259                         PrintWriter out = response.getWriter();
260                         String responseString = mapper.writeValueAsString(successMap);
261                         JSONObject j = new JSONObject("{policyData: " + responseString + "}");
262                         out.write(j.toString());
263                         return null;
264                 }
265                 catch (Exception e){
266                         response.setCharacterEncoding("UTF-8");
267                         request.setCharacterEncoding("UTF-8");
268                         PrintWriter out = response.getWriter();
269                         out.write(e.getMessage());
270                 }
271                 return null;
272         }
273
274         private String convertDate(String dateTTL) {
275                 String formateDate = null;
276                 String[] date  = dateTTL.split("T");
277                 String[] parts = date[0].split("-");
278                 
279                 formateDate = parts[2] + "-" + parts[1] + "-" + parts[0];
280                 return formateDate;
281         }
282         
283         public void PrePopulateClosedLoopPMPolicyData(PolicyAdapter policyAdapter) {
284                 if (policyAdapter.getPolicyData() instanceof PolicyType) {
285                         Object policyData = policyAdapter.getPolicyData();
286                         PolicyType policy = (PolicyType) policyData;
287                         policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
288                         String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("PM_") +3 , policyAdapter.getPolicyName().lastIndexOf("."));
289                         policyAdapter.setPolicyName(policyNameValue);
290                         String description = "";
291                         try{
292                                 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
293                         }catch(Exception e){
294                                 description = policy.getDescription();
295                         }
296                         policyAdapter.setPolicyDescription(description);
297                         // Get the target data under policy.
298                         TargetType target = policy.getTarget();
299                         if (target != null) {
300                                 // Under target we have AnyOFType
301                                 List<AnyOfType> anyOfList = target.getAnyOf();
302                                 if (anyOfList != null) {
303                                         Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
304                                         while (iterAnyOf.hasNext()) {
305                                                 AnyOfType anyOf = iterAnyOf.next();
306                                                 // Under AnyOFType we have AllOFType
307                                                 List<AllOfType> allOfList = anyOf.getAllOf();
308                                                 if (allOfList != null) {
309                                                         Iterator<AllOfType> iterAllOf = allOfList.iterator();
310                                                         while (iterAllOf.hasNext()) {
311                                                                 AllOfType allOf = iterAllOf.next();
312                                                                 // Under AllOFType we have Match
313                                                                 List<MatchType> matchList = allOf.getMatch();
314                                                                 if (matchList != null) {
315                                                                         int index = 0;
316                                                                         Iterator<MatchType> iterMatch = matchList.iterator();
317                                                                         while (matchList.size()>1 && iterMatch.hasNext()) {
318                                                                                 MatchType match = iterMatch.next();
319                                                                                 //
320                                                                                 // Under the match we have attributevalue and
321                                                                                 // attributeDesignator. So,finally down to the actual attribute.
322                                                                                 //
323                                                                                 AttributeValueType attributeValue = match.getAttributeValue();
324                                                                                 String value = (String) attributeValue.getContent().get(0);
325
326                                                                                 // First match in the target is EcompName, so set that value.
327                                                                                 if (index == 0) {
328                                                                                         policyAdapter.setEcompName(value);
329                                                                                 }
330
331                                                                                 if (index ==  1){
332                                                                                         policyAdapter.setRiskType(value);
333                                                                                 }
334
335                                                                                 if (index ==  2){
336                                                                                         policyAdapter.setRiskLevel(value);
337                                                                                 }
338                                                                                 
339                                                                                 if (index ==  3){
340                                                                                         policyAdapter.setGuard(value);
341                                                                                 }
342                                                                                 
343                                                                                 if (index == 4 && !value.contains("NA")){
344                                                                                         String newDate = convertDate(value, true);
345                                                                                         policyAdapter.setTtlDate(newDate);
346                                                                                 }
347                                                                                 if (index == 5){
348                                                                                         LinkedHashMap<String, String> serviceTypePolicyName1 = new LinkedHashMap<>();
349                                                                                         String key = "serviceTypePolicyName";
350                                                                                         serviceTypePolicyName1.put(key, value);
351                                                                                         policyAdapter.setServiceTypePolicyName(serviceTypePolicyName1);
352                                                                                 }
353                                                                                 index++;
354                                                                         }
355                                                                 }
356                                                         }
357                                                 }
358                                         }
359                                 }
360                         }
361                         String jsonBodyName = policyAdapter.getDirPath().replace(File.separator, ".")+"."+ policyAdapter.getOldPolicyFileName() + ".";
362                         policyAdapter.setConfigBodyPath(jsonBodyName);
363                         readClosedLoopJSONFile(policyAdapter);
364                 }               
365         }
366         
367         private String convertDate(String dateTTL, boolean portalType) {
368                 String formateDate = null;
369                 String[] date;
370                 String[] parts;
371                 
372                 if (portalType){
373                         parts = dateTTL.split("-");
374                         formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z";
375                 } else {
376                         date  = dateTTL.split("T");
377                         parts = date[0].split("-");
378                         formateDate = parts[2] + "-" + parts[1] + "-" + parts[0];
379                 }
380                 return formateDate;
381         }
382         
383         protected String readClosedLoopJSONFile(PolicyAdapter policyAdapter) {
384                 String fileLocation = null;
385                 String fileName = policyAdapter.getConfigBodyPath();
386                 if (fileName != null ) {
387                         fileLocation = PolicyController.getConfigHome();
388                 }               
389                 if (fileLocation == null) {
390                         return fileLocation;
391                 }
392                 
393                 File dir = new File(fileLocation);
394                 File[] listOfFiles = dir.listFiles();
395                 for (File file : listOfFiles) {
396                         if (file.isFile() && file.getName().contains(fileName)) {
397                                 FileInputStream inputStream = null;
398                                 String location = file.toString();
399                                 try {
400                                         inputStream = new FileInputStream(location);
401                                 } catch (FileNotFoundException e) {
402                                         e.printStackTrace();
403                                 }
404                                 if (location.endsWith("json")) {
405                                         JsonReader jsonReader = null;
406                                         jsonReader = Json.createReader(inputStream);
407                                         ObjectMapper mapper = new ObjectMapper();
408                                         try {
409                                                 ClosedLoopPMBody closedLoopBody = mapper.readValue(jsonReader.read().toString(), ClosedLoopPMBody.class);
410                                                 policyAdapter.setJsonBodyData(closedLoopBody);
411                                         } catch (IOException e) {
412                                                 e.printStackTrace();
413                                                 /*logger.error("JSON Body Mapping Error");*/
414                                         }       
415                                         jsonReader.close();
416                                 }
417                         }
418                 }
419                 return null;
420         }
421
422 }