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