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