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