2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.policy.pap.xacml.rest.components;
24 import java.io.IOException;
25 import java.io.PrintWriter;
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;
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;
42 import com.att.research.xacml.api.pap.PAPException;
43 import com.att.research.xacml.std.IdentifierImpl;
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;
59 public class ClosedLoopPolicy extends Policy {
61 private static final Logger LOGGER = FlexLogger.getLogger(ClosedLoopPolicy.class);
63 public ClosedLoopPolicy() {
67 public ClosedLoopPolicy(PolicyRestAdapter policyAdapter) {
68 this.policyAdapter = policyAdapter;
71 //save configuration of the policy based on the policyname
72 private void saveConfigurations(String policyName, String jsonBody) {
74 if (policyName.endsWith(".xml")) {
75 policyName = policyName.replace(".xml", "");
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);
83 } catch (Exception e) {
84 LOGGER.error("Exception Occured while writing Configuration Data" + e);
88 //Utility to read json data from the existing file to a string
89 static String readFile(String path, Charset encoding) throws IOException {
91 byte[] encoded = Files.readAllBytes(Paths.get(path));
92 return new String(encoded, encoding);
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);
102 filename = filename + ".json";
107 public Map<String, String> savePolicies() throws PAPException {
109 Map<String, String> successMap = new HashMap<>();
110 if (isPolicyExists()) {
111 successMap.put("EXISTS", "This Policy already exist on the PAP");
115 if (!isPreparedToSave()) {
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());
123 successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject());
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
130 public boolean prepareToSave() throws PAPException {
132 if (isPreparedToSave()) {
133 //we have already done this
138 String policyID = policyAdapter.getPolicyID();
139 version = policyAdapter.getHighestVersion();
141 // Create the Instance for pojo, PolicyType object is used in marshalling.
142 if (policyAdapter.getPolicyType().equals("Config")) {
143 PolicyType policyConfig = new PolicyType();
145 policyConfig.setVersion(Integer.toString(version));
146 policyConfig.setPolicyId(policyID);
147 policyConfig.setTarget(new TargetType());
148 policyAdapter.setData(policyConfig);
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);
156 // Make sure the filename ends with an extension
157 if (policyName.endsWith(".xml") == false) {
158 policyName = policyName + ".xml";
161 PolicyType faultPolicy = (PolicyType) policyAdapter.getData();
163 faultPolicy.setDescription(policyAdapter.getPolicyDescription());
165 faultPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
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);
173 allOfOne.getMatch().add(createMatch("PolicyName", name));
174 AllOfType allOf = new AllOfType();
175 // Adding the matches to AllOfType element
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()));
188 allOf.getMatch().add(
189 createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
191 AnyOfType anyOf = new AnyOfType();
192 anyOf.getAllOf().add(allOfOne);
193 anyOf.getAllOf().add(allOf);
195 TargetType target = new TargetType();
196 ((TargetType) target).getAnyOf().add(anyOf);
197 // Adding the target to the policy element
198 faultPolicy.setTarget((TargetType) target);
200 RuleType rule = new RuleType();
201 rule.setRuleId(policyAdapter.getRuleID());
202 rule.setEffect(EffectType.PERMIT);
204 // Create Target in Rule
205 AllOfType allOfInRule = new AllOfType();
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;
216 accessURI = new URI(ACTION_ID);
217 } catch (URISyntaxException e) {
218 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "CreateClosedLoopPolicy",
219 "Exception creating ACCESS URI");
221 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
222 accessAttributeDesignator.setDataType(STRING_DATATYPE);
223 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
224 accessMatch.setAttributeDesignator(accessAttributeDesignator);
225 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
227 // Creating Config Match in rule Target
228 MatchType closedMatch = new MatchType();
229 AttributeValueType closedAttributeValue = new AttributeValueType();
230 closedAttributeValue.setDataType(STRING_DATATYPE);
231 closedAttributeValue.getContent().add("Config");
232 closedMatch.setAttributeValue(closedAttributeValue);
233 AttributeDesignatorType closedAttributeDesignator = new AttributeDesignatorType();
234 URI closedURI = null;
236 closedURI = new URI(RESOURCE_ID);
237 } catch (URISyntaxException e) {
238 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "CreateClosedLoopPolicy",
239 "Exception creating closed URI");
241 closedAttributeDesignator.setCategory(CATEGORY_RESOURCE);
242 closedAttributeDesignator.setDataType(STRING_DATATYPE);
243 closedAttributeDesignator.setAttributeId(new IdentifierImpl(closedURI).stringValue());
244 closedMatch.setAttributeDesignator(closedAttributeDesignator);
245 closedMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
247 allOfInRule.getMatch().add(accessMatch);
248 allOfInRule.getMatch().add(closedMatch);
250 AnyOfType anyOfInRule = new AnyOfType();
251 anyOfInRule.getAllOf().add(allOfInRule);
253 TargetType targetInRule = new TargetType();
254 targetInRule.getAnyOf().add(anyOfInRule);
256 rule.setTarget(targetInRule);
257 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
259 faultPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
260 policyAdapter.setPolicyData(faultPolicy);
263 PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
266 setPreparedToSave(true);
270 // Data required for Advice part is setting here.
271 private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
272 AdviceExpressionsType advices = new AdviceExpressionsType();
273 AdviceExpressionType advice = new AdviceExpressionType();
274 advice.setAdviceId("faultID");
275 advice.setAppliesTo(EffectType.PERMIT);
277 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
278 assignment1.setAttributeId("type");
279 assignment1.setCategory(CATEGORY_RESOURCE);
280 assignment1.setIssuer("");
282 AttributeValueType configNameAttributeValue = new AttributeValueType();
283 configNameAttributeValue.setDataType(STRING_DATATYPE);
284 configNameAttributeValue.getContent().add("Configuration");
285 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
287 advice.getAttributeAssignmentExpression().add(assignment1);
288 // For Config file Url if configurations are provided.
289 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
290 assignment2.setAttributeId("URLID");
291 assignment2.setCategory(CATEGORY_RESOURCE);
292 assignment2.setIssuer("");
294 AttributeValueType AttributeValue = new AttributeValueType();
295 AttributeValue.setDataType(URI_DATATYPE);
296 String content = CONFIG_URL + "/Config/" + getConfigFile(policyName);
297 System.out.println("URL value :" + content);
298 AttributeValue.getContent().add(content);
299 assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
301 advice.getAttributeAssignmentExpression().add(assignment2);
302 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
303 assignment3.setAttributeId("PolicyName");
304 assignment3.setCategory(CATEGORY_RESOURCE);
305 assignment3.setIssuer("");
307 AttributeValueType attributeValue3 = new AttributeValueType();
308 attributeValue3.setDataType(STRING_DATATYPE);
309 fileName = FilenameUtils.removeExtension(fileName);
310 fileName = fileName + ".xml";
311 String name = fileName.substring(fileName.lastIndexOf("\\") + 1);
312 if ((name == null) || (name.equals(""))) {
313 name = fileName.substring(fileName.lastIndexOf("/") + 1);
315 attributeValue3.getContent().add(name);
316 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
317 advice.getAttributeAssignmentExpression().add(assignment3);
319 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
320 assignment4.setAttributeId("VersionNumber");
321 assignment4.setCategory(CATEGORY_RESOURCE);
322 assignment4.setIssuer("");
324 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
325 configNameAttributeValue4.setDataType(STRING_DATATYPE);
326 configNameAttributeValue4.getContent().add(Integer.toString(version));
327 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
329 advice.getAttributeAssignmentExpression().add(assignment4);
331 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
332 assignment5.setAttributeId("matching:" + ONAPID);
333 assignment5.setCategory(CATEGORY_RESOURCE);
334 assignment5.setIssuer("");
336 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
337 configNameAttributeValue5.setDataType(STRING_DATATYPE);
338 configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
339 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
341 advice.getAttributeAssignmentExpression().add(assignment5);
344 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
345 assignment6.setAttributeId("RiskType");
346 assignment6.setCategory(CATEGORY_RESOURCE);
347 assignment6.setIssuer("");
349 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
350 configNameAttributeValue6.setDataType(STRING_DATATYPE);
351 configNameAttributeValue6.getContent().add(policyAdapter.getRiskType());
352 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
354 advice.getAttributeAssignmentExpression().add(assignment6);
356 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
357 assignment7.setAttributeId("RiskLevel");
358 assignment7.setCategory(CATEGORY_RESOURCE);
359 assignment7.setIssuer("");
361 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
362 configNameAttributeValue7.setDataType(STRING_DATATYPE);
363 configNameAttributeValue7.getContent().add(policyAdapter.getRiskLevel());
364 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
366 advice.getAttributeAssignmentExpression().add(assignment7);
368 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
369 assignment8.setAttributeId("guard");
370 assignment8.setCategory(CATEGORY_RESOURCE);
371 assignment8.setIssuer("");
373 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
374 configNameAttributeValue8.setDataType(STRING_DATATYPE);
375 configNameAttributeValue8.getContent().add(policyAdapter.getGuard());
376 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
378 advice.getAttributeAssignmentExpression().add(assignment8);
380 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
381 assignment9.setAttributeId("TTLDate");
382 assignment9.setCategory(CATEGORY_RESOURCE);
383 assignment9.setIssuer("");
385 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
386 configNameAttributeValue9.setDataType(STRING_DATATYPE);
387 configNameAttributeValue9.getContent().add(policyAdapter.getTtlDate());
388 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
390 advice.getAttributeAssignmentExpression().add(assignment9);
393 advices.getAdviceExpression().add(advice);
398 public Object getCorrectPolicyDataObject() {
399 return policyAdapter.getPolicyData();