Consolidate PolicyRestAdapter setup
[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, 2019 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 com.att.research.xacml.api.pap.PAPException;
24 import com.att.research.xacml.std.IdentifierImpl;
25
26 import java.io.File;
27 import java.io.IOException;
28 import java.io.PrintWriter;
29 import java.net.URI;
30 import java.net.URISyntaxException;
31 import java.nio.charset.Charset;
32 import java.nio.file.Files;
33 import java.nio.file.Path;
34 import java.nio.file.Paths;
35 import java.util.HashMap;
36 import java.util.Map;
37
38 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
39 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
40 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
41 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
42 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
43 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
44 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
51
52 import org.apache.commons.io.FilenameUtils;
53 import org.onap.policy.common.logging.eelf.MessageCodes;
54 import org.onap.policy.common.logging.eelf.PolicyLogger;
55 import org.onap.policy.common.logging.flexlogger.FlexLogger;
56 import org.onap.policy.common.logging.flexlogger.Logger;
57 import org.onap.policy.rest.adapter.PolicyRestAdapter;
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);
170             if ((name == null) || (name.equals(""))) {
171                 name = fileName.substring(fileName.lastIndexOf("/") + 1);
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(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
180             // Match for riskLevel
181             allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
182             // Match for riskguard
183             allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
184             // Match for ttlDate
185             allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
186
187             AnyOfType anyOf = new AnyOfType();
188             anyOf.getAllOf().add(allOfOne);
189             anyOf.getAllOf().add(allOf);
190
191             TargetType target = new TargetType();
192             ((TargetType) target).getAnyOf().add(anyOf);
193             // Adding the target to the policy element
194             faultPolicy.setTarget((TargetType) target);
195
196             RuleType rule = new RuleType();
197             rule.setRuleId(policyAdapter.getRuleID());
198             rule.setEffect(EffectType.PERMIT);
199
200             // Create Target in Rule
201             AllOfType allOfInRule = new AllOfType();
202
203             // Creating match for ACCESS in rule target
204             MatchType accessMatch = new MatchType();
205             AttributeValueType accessAttributeValue = new AttributeValueType();
206             accessAttributeValue.setDataType(STRING_DATATYPE);
207             accessAttributeValue.getContent().add("ACCESS");
208             accessMatch.setAttributeValue(accessAttributeValue);
209             AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
210             URI accessURI = null;
211             try {
212                 accessURI = new URI(ACTION_ID);
213             } catch (URISyntaxException e) {
214                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "CreateClosedLoopPolicy",
215                         "Exception creating ACCESS URI");
216             }
217             accessAttributeDesignator.setCategory(CATEGORY_ACTION);
218             accessAttributeDesignator.setDataType(STRING_DATATYPE);
219             accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
220             accessMatch.setAttributeDesignator(accessAttributeDesignator);
221             accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
222
223             // Creating Config Match in rule Target
224             MatchType closedMatch = new MatchType();
225             AttributeValueType closedAttributeValue = new AttributeValueType();
226             closedAttributeValue.setDataType(STRING_DATATYPE);
227             closedAttributeValue.getContent().add("Config");
228             closedMatch.setAttributeValue(closedAttributeValue);
229             AttributeDesignatorType closedAttributeDesignator = new AttributeDesignatorType();
230             URI closedURI = null;
231             try {
232                 closedURI = new URI(RESOURCE_ID);
233             } catch (URISyntaxException e) {
234                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "CreateClosedLoopPolicy",
235                         "Exception creating closed URI");
236             }
237             closedAttributeDesignator.setCategory(CATEGORY_RESOURCE);
238             closedAttributeDesignator.setDataType(STRING_DATATYPE);
239             closedAttributeDesignator.setAttributeId(new IdentifierImpl(closedURI).stringValue());
240             closedMatch.setAttributeDesignator(closedAttributeDesignator);
241             closedMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
242
243             allOfInRule.getMatch().add(accessMatch);
244             allOfInRule.getMatch().add(closedMatch);
245
246             AnyOfType anyOfInRule = new AnyOfType();
247             anyOfInRule.getAllOf().add(allOfInRule);
248
249             TargetType targetInRule = new TargetType();
250             targetInRule.getAnyOf().add(anyOfInRule);
251
252             rule.setTarget(targetInRule);
253             rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
254
255             faultPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
256             policyAdapter.setPolicyData(faultPolicy);
257
258         } else {
259             PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
260         }
261
262         setPreparedToSave(true);
263         return true;
264     }
265
266     // Data required for Advice part is setting here.
267     private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
268         AdviceExpressionsType advices = new AdviceExpressionsType();
269         AdviceExpressionType advice = new AdviceExpressionType();
270         advice.setAdviceId("faultID");
271         advice.setAppliesTo(EffectType.PERMIT);
272         // For Configuration
273         AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
274         assignment1.setAttributeId("type");
275         assignment1.setCategory(CATEGORY_RESOURCE);
276         assignment1.setIssuer("");
277
278         AttributeValueType configNameAttributeValue = new AttributeValueType();
279         configNameAttributeValue.setDataType(STRING_DATATYPE);
280         configNameAttributeValue.getContent().add("Configuration");
281         assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
282
283         advice.getAttributeAssignmentExpression().add(assignment1);
284         // For Config file Url if configurations are provided.
285         AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
286         assignment2.setAttributeId("URLID");
287         assignment2.setCategory(CATEGORY_RESOURCE);
288         assignment2.setIssuer("");
289
290         AttributeValueType AttributeValue = new AttributeValueType();
291         AttributeValue.setDataType(URI_DATATYPE);
292         String content = CONFIG_URL + "/Config/" + getConfigFile(policyName);
293         System.out.println("URL value :" + content);
294         AttributeValue.getContent().add(content);
295         assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
296
297         advice.getAttributeAssignmentExpression().add(assignment2);
298         AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
299         assignment3.setAttributeId("PolicyName");
300         assignment3.setCategory(CATEGORY_RESOURCE);
301         assignment3.setIssuer("");
302
303         AttributeValueType attributeValue3 = new AttributeValueType();
304         attributeValue3.setDataType(STRING_DATATYPE);
305         fileName = FilenameUtils.removeExtension(fileName);
306         fileName = fileName + ".xml";
307         String name = fileName.substring(fileName.lastIndexOf("\\") + 1);
308         if ((name == null) || (name.equals(""))) {
309             name = fileName.substring(fileName.lastIndexOf("/") + 1);
310         }
311         attributeValue3.getContent().add(name);
312         assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
313         advice.getAttributeAssignmentExpression().add(assignment3);
314
315         AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
316         assignment4.setAttributeId("VersionNumber");
317         assignment4.setCategory(CATEGORY_RESOURCE);
318         assignment4.setIssuer("");
319
320         AttributeValueType configNameAttributeValue4 = new AttributeValueType();
321         configNameAttributeValue4.setDataType(STRING_DATATYPE);
322         configNameAttributeValue4.getContent().add(Integer.toString(version));
323         assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
324
325         advice.getAttributeAssignmentExpression().add(assignment4);
326
327         AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
328         assignment5.setAttributeId("matching:" + ONAPID);
329         assignment5.setCategory(CATEGORY_RESOURCE);
330         assignment5.setIssuer("");
331
332         AttributeValueType configNameAttributeValue5 = new AttributeValueType();
333         configNameAttributeValue5.setDataType(STRING_DATATYPE);
334         configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
335         assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
336
337         advice.getAttributeAssignmentExpression().add(assignment5);
338
339         // Risk Attributes
340         AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
341         assignment6.setAttributeId("RiskType");
342         assignment6.setCategory(CATEGORY_RESOURCE);
343         assignment6.setIssuer("");
344
345         AttributeValueType configNameAttributeValue6 = new AttributeValueType();
346         configNameAttributeValue6.setDataType(STRING_DATATYPE);
347         configNameAttributeValue6.getContent().add(policyAdapter.getRiskType());
348         assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
349
350         advice.getAttributeAssignmentExpression().add(assignment6);
351
352         AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
353         assignment7.setAttributeId("RiskLevel");
354         assignment7.setCategory(CATEGORY_RESOURCE);
355         assignment7.setIssuer("");
356
357         AttributeValueType configNameAttributeValue7 = new AttributeValueType();
358         configNameAttributeValue7.setDataType(STRING_DATATYPE);
359         configNameAttributeValue7.getContent().add(policyAdapter.getRiskLevel());
360         assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
361
362         advice.getAttributeAssignmentExpression().add(assignment7);
363
364         AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
365         assignment8.setAttributeId("guard");
366         assignment8.setCategory(CATEGORY_RESOURCE);
367         assignment8.setIssuer("");
368
369         AttributeValueType configNameAttributeValue8 = new AttributeValueType();
370         configNameAttributeValue8.setDataType(STRING_DATATYPE);
371         configNameAttributeValue8.getContent().add(policyAdapter.getGuard());
372         assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
373
374         advice.getAttributeAssignmentExpression().add(assignment8);
375
376         AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
377         assignment9.setAttributeId("TTLDate");
378         assignment9.setCategory(CATEGORY_RESOURCE);
379         assignment9.setIssuer("");
380
381         AttributeValueType configNameAttributeValue9 = new AttributeValueType();
382         configNameAttributeValue9.setDataType(STRING_DATATYPE);
383         configNameAttributeValue9.getContent().add(policyAdapter.getTtlDate());
384         assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
385
386         advice.getAttributeAssignmentExpression().add(assignment9);
387
388         advices.getAdviceExpression().add(advice);
389         return advices;
390     }
391
392     @Override
393     public Object getCorrectPolicyDataObject() {
394         return policyAdapter.getPolicyData();
395     }
396
397 }