Fixed the Policy API issues and Bugfixes
[policy/engine.git] / ECOMP-PAP-REST / src / main / java / org / openecomp / policy / pap / xacml / rest / components / AutoPushPolicy.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP-PAP-REST
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.pap.xacml.rest.components;
22
23 import java.io.File;
24 import java.io.FileInputStream;
25 import java.nio.file.Paths;
26 import java.util.HashSet;
27 import java.util.Iterator;
28 import java.util.Properties;
29 import java.util.Set;
30
31 import org.openecomp.policy.common.logging.eelf.MessageCodes;
32 import org.openecomp.policy.common.logging.eelf.PolicyLogger;
33 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
34 import org.openecomp.policy.common.logging.flexlogger.Logger;
35 import org.openecomp.policy.xacml.api.pap.EcompPDPGroup;
36 import org.openecomp.policy.xacml.api.pap.PAPPolicyEngine;
37 import org.openecomp.policy.xacml.std.pap.StdPDPGroup;
38 import org.openecomp.policy.xacml.std.pap.StdPDPPolicy;
39
40 import com.att.research.xacml.api.pap.PDPPolicy;
41 /**
42  * Auto Push Policy based on the property file properties. 
43  * 
44  * @version 0.1
45  */
46 public class AutoPushPolicy {
47         
48         private static final Logger LOGGER = FlexLogger.getLogger(AutoPushPolicy.class);
49         
50         private String filePath = null;
51         private Properties properties;
52         private Long newModified;
53         private Long oldModified;
54         private File propFile;
55         
56         
57         /**
58          * Constructor Pass in the property file path. 
59          */
60         public AutoPushPolicy(String file){
61                 filePath = file;
62                 properties = new Properties();
63                 propFile = Paths.get(filePath).toFile();
64                 readFile();
65         }
66         
67         /**
68          * Checks Policy with all the Groups which has set such Property. 
69          * Else returns Empty Set. 
70          * 
71          * @param policyToCreateUpdate
72          * @param papEngine
73          */
74         public Set<StdPDPGroup> checkGroupsToPush(String policyToCreateUpdate, PAPPolicyEngine papEngine) {
75                 Set<StdPDPGroup> changedGroups= new HashSet<>();
76                 // Check if the file has been modified. then re-load the properties file. 
77                 newModified = propFile.lastModified();
78                 try {
79                         if(newModified!=oldModified){
80                                 // File has been updated.
81                                 readFile();
82                         }
83                         // Read the File name as its made.
84                         String gitPath  = PolicyDBDao.getGitPath();
85                         String policyId =  policyToCreateUpdate.substring(policyToCreateUpdate.indexOf(gitPath)+gitPath.length()+1);
86                         String policyName = policyId.substring(policyId.lastIndexOf(File.separator)+1,policyId.lastIndexOf("."));
87                         policyName = policyName.substring(0,policyName.lastIndexOf("."));
88                         policyId = policyId.replace("/", ".");
89                         if(policyId.contains("\\")){
90                                 policyId = policyId.replace("\\", ".");
91                         }
92                         LOGGER.info("Policy ID : " + policyId);
93                         LOGGER.info("Policy Name : " + policyName);
94                         // Read in Groups 
95                         for(EcompPDPGroup pdpGroup: papEngine.getEcompPDPGroups()){
96                                 String groupName = pdpGroup.getName();
97                                 Boolean typeFlag = false;
98                                 Boolean scopeFlag = false;
99                                 if(properties.containsKey(groupName + ".policyType")){
100                                         String type= properties.getProperty(groupName + ".policyType").replaceAll(" ","");
101                                         if(type.equals("")){
102                                                 type = " ";
103                                         }
104                                         typeFlag = policyName.contains(type);
105                                 }
106                                 if(properties.containsKey(groupName + ".policyScope")){
107                                         String scope = properties.getProperty(groupName + ".policyScope").replaceAll(" ", "");
108                                         if(scope.equals("")){
109                                                 scope = " ";
110                                         }
111                                         scopeFlag = policyId.contains(scope);
112                                 }
113                                 if(typeFlag || scopeFlag){
114                                         StdPDPGroup group = addToGroup(policyId,policyName, policyToCreateUpdate, (StdPDPGroup)pdpGroup);
115                                         changedGroups.add(group);
116                                 }
117                         }
118                 } catch (Exception e) {
119                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "AutoPushPolicy", "Error while processing the auto push for " + policyToCreateUpdate);
120                 }
121                 return changedGroups;
122         }
123         
124         private void readFile(){
125                 try {
126                         properties.load(new FileInputStream(propFile));
127                         oldModified = propFile.lastModified();
128                 } catch (Exception e) {
129                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "AutoPushPolicy", "Error while loading in the auto push properties file.");
130                 }
131         }
132         
133         private StdPDPGroup addToGroup(String policyId, String policyName, String policyToCreateUpdate, StdPDPGroup pdpGroup) throws Exception{
134                 // Add to group. Send Notification. 
135                 StdPDPPolicy policy = new StdPDPPolicy(policyId, true, policyName, null);
136                 //Get the current policies from the Group and Add the new one
137         Set<PDPPolicy> currentPoliciesInGroup = pdpGroup.getPolicies();
138         Set<PDPPolicy> policies = new HashSet<>();
139                 policies.add(policy);
140         pdpGroup.copyPolicyToFile(policyId, new FileInputStream(Paths.get(policyToCreateUpdate).toFile()));
141         //If the selected policy is in the group we must remove it because the name is default
142                 Iterator<PDPPolicy> policyIterator = policies.iterator();
143                 while (policyIterator.hasNext()) {
144                         PDPPolicy selPolicy = policyIterator.next();
145                         for (PDPPolicy existingPolicy : currentPoliciesInGroup) {
146                                 if (existingPolicy.getId().equals(selPolicy.getId())) {
147                                         pdpGroup.removePolicyFromGroup(existingPolicy);
148                                         LOGGER.debug("Removing policy: " + existingPolicy);
149                                         break;
150                                 }
151                         }
152                 }
153                 if(currentPoliciesInGroup!=null){
154             policies.addAll(currentPoliciesInGroup);
155         }
156                 pdpGroup.setPolicies(policies);
157                 return pdpGroup;
158         }
159 }