Policy TestSuite Enabled
[policy/engine.git] / ECOMP-PAP-REST / src / main / java / org / openecomp / policy / pap / xacml / rest / components / ClosedLoopPolicy.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.IOException;
25 import java.io.PrintWriter;
26 import java.net.URI;
27 import java.net.URISyntaxException;
28 import java.nio.charset.Charset;
29 import java.nio.file.Files;
30 import java.nio.file.Path;
31 import java.nio.file.Paths;
32 import java.util.HashMap;
33 import java.util.Map;
34
35 import org.apache.commons.io.FilenameUtils;
36 import org.openecomp.policy.common.logging.eelf.MessageCodes;
37 import org.openecomp.policy.common.logging.eelf.PolicyLogger;
38 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
39 import org.openecomp.policy.common.logging.flexlogger.Logger;
40 import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
41
42 import com.att.research.xacml.std.IdentifierImpl;
43
44 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
51 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
52 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
53 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
54 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
55 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
56 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; 
57
58 public class ClosedLoopPolicy extends Policy {
59
60         private static final Logger LOGGER = FlexLogger.getLogger(ClosedLoopPolicy.class);
61
62         public ClosedLoopPolicy() {
63                 super();
64         }
65         
66         public ClosedLoopPolicy(PolicyRestAdapter policyAdapter){
67                 this.policyAdapter = policyAdapter;
68         }
69         
70         //save configuration of the policy based on the policyname
71         private void saveConfigurations(String policyName, String jsonBody) {
72                 try {
73                         String body = jsonBody;
74                         try {
75                                 try{
76                                         //Remove the trapMaxAge in Verification Signature
77                                         body = body.replace(",\"trapMaxAge\":null", "");
78                                 }catch(Exception e){
79                                         LOGGER.debug("No Trap Max Age in JSON body");
80                                 }
81                                 this.policyAdapter.setJsonBody(body);
82                         } catch (Exception e) {
83                                 LOGGER.error("Exception Occured"+e);
84                         }
85
86                         if(policyName.endsWith(".xml")){
87                                 policyName = policyName.replace(".xml", "");
88                         }
89                         PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator+ policyName +".json");
90                         out.println(body);
91                         out.close();
92
93                 } catch (Exception e) {
94                         LOGGER.error("Exception Occured while writing Configuration Data"+e);
95                 } 
96         }
97         
98         //Utility to read json data from the existing file to a string
99         static String readFile(String path, Charset encoding) throws IOException {
100                 
101                 byte[] encoded = Files.readAllBytes(Paths.get(path));
102                 return new String(encoded, encoding);
103                 
104         }
105         
106         //create the configuration file based on the policy name on adding the extension as .json 
107         private String getConfigFile(String filename) {
108                 filename = FilenameUtils.removeExtension(filename);
109                 if (filename.endsWith(".xml")) {
110                         filename = filename.substring(0, filename.length() - 4);
111                 }
112                 filename = filename + ".json";
113                 return filename;
114         }
115
116         @Override
117         public Map<String, String> savePolicies() throws Exception {
118                 
119                 Map<String, String> successMap = new HashMap<String,String>();
120                 if(isPolicyExists()){
121                         successMap.put("EXISTS", "This Policy already exist on the PAP");
122                         return successMap;
123                 }
124                 
125                 if(!isPreparedToSave()){
126                         prepareToSave();
127                 }
128                 
129                 // Until here we prepared the data and here calling the method to create xml.
130                 Path newPolicyPath = null;
131                 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
132
133                 successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject());  
134                 return successMap;              
135         }
136
137         //This is the method for preparing the policy for saving.  We have broken it out
138         //separately because the fully configured policy is used for multiple things
139         @Override
140         public boolean prepareToSave() throws Exception{
141                 
142                 if(isPreparedToSave()){
143                         //we have already done this
144                         return true;
145                 }
146                 
147                 int version = 0;
148                 String policyID = policyAdapter.getPolicyID();
149                 version = policyAdapter.getHighestVersion();
150                 
151                 // Create the Instance for pojo, PolicyType object is used in marshalling.
152                 if (policyAdapter.getPolicyType().equals("Config")) {
153                         PolicyType policyConfig = new PolicyType();
154
155                         policyConfig.setVersion(Integer.toString(version));
156                         policyConfig.setPolicyId(policyID);
157                         policyConfig.setTarget(new TargetType());
158                         policyAdapter.setData(policyConfig);
159                 }
160                 policyName = policyAdapter.getNewFileName();
161                 if (policyAdapter.getData() != null) {
162                         // Save the Configurations file with the policy name with extention based on selection.
163                         String jsonBody = policyAdapter.getJsonBody();
164                         saveConfigurations(policyName, jsonBody);
165                         
166                         // Make sure the filename ends with an extension
167                         if (policyName.endsWith(".xml") == false) {
168                                 policyName = policyName + ".xml";
169                         }
170                         
171                         PolicyType faultPolicy = (PolicyType) policyAdapter.getData();
172                         
173                         faultPolicy.setDescription(policyAdapter.getPolicyDescription());
174
175                         faultPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
176                         
177                         AllOfType allOfOne = new AllOfType();
178                         String fileName = policyAdapter.getNewFileName();
179                         String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
180                         if ((name == null) || (name.equals(""))) {
181                                 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
182                         }
183                         allOfOne.getMatch().add(createMatch("PolicyName", name));
184                         AllOfType allOf = new AllOfType();
185                         // Adding the matches to AllOfType element
186                         // Match for Ecomp
187                         allOf.getMatch().add(createMatch("ECOMPName", policyAdapter.getEcompName()));
188                         // Match for riskType
189                         allOf.getMatch().add(
190                                         createDynamicMatch("RiskType", policyAdapter.getRiskType()));
191                         // Match for riskLevel
192                         allOf.getMatch().add(
193                                         createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
194                         // Match for riskguard
195                         allOf.getMatch().add(
196                                         createDynamicMatch("guard", policyAdapter.getGuard()));
197                         // Match for ttlDate
198                         allOf.getMatch().add(
199                                         createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
200                         
201                         AnyOfType anyOf = new AnyOfType();
202                         anyOf.getAllOf().add(allOfOne);
203                         anyOf.getAllOf().add(allOf);
204
205                         TargetType target = new TargetType();
206                         ((TargetType) target).getAnyOf().add(anyOf);
207                         // Adding the target to the policy element
208                         faultPolicy.setTarget((TargetType) target);
209
210                         RuleType rule = new RuleType();
211                         rule.setRuleId(policyAdapter.getRuleID());
212                         rule.setEffect(EffectType.PERMIT);
213                         
214                         // Create Target in Rule
215                         AllOfType allOfInRule = new AllOfType();
216
217                         // Creating match for ACCESS in rule target
218                         MatchType accessMatch = new MatchType();
219                         AttributeValueType accessAttributeValue = new AttributeValueType();
220                         accessAttributeValue.setDataType(STRING_DATATYPE);
221                         accessAttributeValue.getContent().add("ACCESS");
222                         accessMatch.setAttributeValue(accessAttributeValue);
223                         AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
224                         URI accessURI = null;
225                         try {
226                                 accessURI = new URI(ACTION_ID);
227                         } catch (URISyntaxException e) {
228                                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "CreateClosedLoopPolicy", "Exception creating ACCESS URI");
229                         }
230                         accessAttributeDesignator.setCategory(CATEGORY_ACTION);
231                         accessAttributeDesignator.setDataType(STRING_DATATYPE);
232                         accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
233                         accessMatch.setAttributeDesignator(accessAttributeDesignator);
234                         accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
235
236                         // Creating Config Match in rule Target
237                         MatchType closedMatch = new MatchType();
238                         AttributeValueType closedAttributeValue = new AttributeValueType();
239                         closedAttributeValue.setDataType(STRING_DATATYPE);
240                         closedAttributeValue.getContent().add("Config");
241                         closedMatch.setAttributeValue(closedAttributeValue);
242                         AttributeDesignatorType closedAttributeDesignator = new AttributeDesignatorType();
243                         URI closedURI = null;
244                         try {
245                                 closedURI = new URI(RESOURCE_ID);
246                         } catch (URISyntaxException e) {
247                                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "CreateClosedLoopPolicy", "Exception creating closed URI");
248                         }
249                         closedAttributeDesignator.setCategory(CATEGORY_RESOURCE);
250                         closedAttributeDesignator.setDataType(STRING_DATATYPE);
251                         closedAttributeDesignator.setAttributeId(new IdentifierImpl(closedURI).stringValue());
252                         closedMatch.setAttributeDesignator(closedAttributeDesignator);
253                         closedMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
254
255                         allOfInRule.getMatch().add(accessMatch);
256                         allOfInRule.getMatch().add(closedMatch);
257
258                         AnyOfType anyOfInRule = new AnyOfType();
259                         anyOfInRule.getAllOf().add(allOfInRule);
260
261                         TargetType targetInRule = new TargetType();
262                         targetInRule.getAnyOf().add(anyOfInRule);
263
264                         rule.setTarget(targetInRule);
265                         rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
266
267                         faultPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
268                         policyAdapter.setPolicyData(faultPolicy);
269
270                 } else {
271                         PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
272                 }
273
274                 setPreparedToSave(true);
275                 return true;
276         }
277
278         // Data required for Advice part is setting here.
279         private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
280                 AdviceExpressionsType advices = new AdviceExpressionsType();
281                 AdviceExpressionType advice = new AdviceExpressionType();
282                 advice.setAdviceId("faultID");
283                 advice.setAppliesTo(EffectType.PERMIT);
284                 // For Configuration
285                 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
286                 assignment1.setAttributeId("type");
287                 assignment1.setCategory(CATEGORY_RESOURCE);
288                 assignment1.setIssuer("");
289
290                 AttributeValueType configNameAttributeValue = new AttributeValueType();
291                 configNameAttributeValue.setDataType(STRING_DATATYPE);
292                 configNameAttributeValue.getContent().add("Configuration");
293                 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
294
295                 advice.getAttributeAssignmentExpression().add(assignment1);
296                 // For Config file Url if configurations are provided.
297                 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
298                 assignment2.setAttributeId("URLID");
299                 assignment2.setCategory(CATEGORY_RESOURCE);
300                 assignment2.setIssuer("");
301
302                 AttributeValueType AttributeValue = new AttributeValueType();
303                 AttributeValue.setDataType(URI_DATATYPE);
304                 String content = CONFIG_URL +"/Config/" + getConfigFile(policyName);
305                 System.out.println("URL value :" + content);
306                 AttributeValue.getContent().add(content);
307                 assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
308
309                 advice.getAttributeAssignmentExpression().add(assignment2);
310                 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
311                 assignment3.setAttributeId("PolicyName");
312                 assignment3.setCategory(CATEGORY_RESOURCE);
313                 assignment3.setIssuer("");
314
315                 AttributeValueType attributeValue3 = new AttributeValueType();
316                 attributeValue3.setDataType(STRING_DATATYPE);
317                 fileName = FilenameUtils.removeExtension(fileName);
318                 fileName = fileName + ".xml";
319                 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
320                 if ((name == null) || (name.equals(""))) {
321                         name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
322                 }
323                 attributeValue3.getContent().add(name);
324                 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
325                 advice.getAttributeAssignmentExpression().add(assignment3);
326
327                 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
328                 assignment4.setAttributeId("VersionNumber");
329                 assignment4.setCategory(CATEGORY_RESOURCE);
330                 assignment4.setIssuer("");
331
332                 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
333                 configNameAttributeValue4.setDataType(STRING_DATATYPE);
334                 configNameAttributeValue4.getContent().add(Integer.toString(version));
335                 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
336
337                 advice.getAttributeAssignmentExpression().add(assignment4);
338
339                 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
340                 assignment5.setAttributeId("matching:" + ECOMPID);
341                 assignment5.setCategory(CATEGORY_RESOURCE);
342                 assignment5.setIssuer("");
343
344                 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
345                 configNameAttributeValue5.setDataType(STRING_DATATYPE);
346                 configNameAttributeValue5.getContent().add(policyAdapter.getEcompName());
347                 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
348
349                 advice.getAttributeAssignmentExpression().add(assignment5);
350                 
351                 //Risk Attributes
352                 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
353                 assignment6.setAttributeId("RiskType");
354                 assignment6.setCategory(CATEGORY_RESOURCE);
355                 assignment6.setIssuer("");
356
357                 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
358                 configNameAttributeValue6.setDataType(STRING_DATATYPE);
359                 configNameAttributeValue6.getContent().add(policyAdapter.getRiskType());
360                 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
361
362                 advice.getAttributeAssignmentExpression().add(assignment6);
363                 
364                 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
365                 assignment7.setAttributeId("RiskLevel");
366                 assignment7.setCategory(CATEGORY_RESOURCE);
367                 assignment7.setIssuer("");
368
369                 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
370                 configNameAttributeValue7.setDataType(STRING_DATATYPE);
371                 configNameAttributeValue7.getContent().add(policyAdapter.getRiskLevel());
372                 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
373
374                 advice.getAttributeAssignmentExpression().add(assignment7);     
375
376                 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
377                 assignment8.setAttributeId("guard");
378                 assignment8.setCategory(CATEGORY_RESOURCE);
379                 assignment8.setIssuer("");
380
381                 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
382                 configNameAttributeValue8.setDataType(STRING_DATATYPE);
383                 configNameAttributeValue8.getContent().add(policyAdapter.getGuard());
384                 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
385
386                 advice.getAttributeAssignmentExpression().add(assignment8);
387                 
388                 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
389                 assignment9.setAttributeId("TTLDate");
390                 assignment9.setCategory(CATEGORY_RESOURCE);
391                 assignment9.setIssuer("");
392
393                 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
394                 configNameAttributeValue9.setDataType(STRING_DATATYPE);
395                 configNameAttributeValue9.getContent().add(policyAdapter.getTtlDate());
396                 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
397
398                 advice.getAttributeAssignmentExpression().add(assignment9);
399
400
401                 
402                 advices.getAdviceExpression().add(advice);
403                 return advices;
404         }
405
406         @Override
407         public Object getCorrectPolicyDataObject() {
408                 return policyAdapter.getPolicyData();
409         }
410
411
412 }