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, fileName.length());
170 if ((name == null) || (name.equals(""))) {
171 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
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", "Exception creating ACCESS URI");
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);
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;
235 closedURI = new URI(RESOURCE_ID);
236 } catch (URISyntaxException e) {
237 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "CreateClosedLoopPolicy", "Exception creating closed URI");
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);
245 allOfInRule.getMatch().add(accessMatch);
246 allOfInRule.getMatch().add(closedMatch);
248 AnyOfType anyOfInRule = new AnyOfType();
249 anyOfInRule.getAllOf().add(allOfInRule);
251 TargetType targetInRule = new TargetType();
252 targetInRule.getAnyOf().add(anyOfInRule);
254 rule.setTarget(targetInRule);
255 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
257 faultPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
258 policyAdapter.setPolicyData(faultPolicy);
261 PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
264 setPreparedToSave(true);
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);
275 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
276 assignment1.setAttributeId("type");
277 assignment1.setCategory(CATEGORY_RESOURCE);
278 assignment1.setIssuer("");
280 AttributeValueType configNameAttributeValue = new AttributeValueType();
281 configNameAttributeValue.setDataType(STRING_DATATYPE);
282 configNameAttributeValue.getContent().add("Configuration");
283 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
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("");
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));
299 advice.getAttributeAssignmentExpression().add(assignment2);
300 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
301 assignment3.setAttributeId("PolicyName");
302 assignment3.setCategory(CATEGORY_RESOURCE);
303 assignment3.setIssuer("");
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());
313 attributeValue3.getContent().add(name);
314 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
315 advice.getAttributeAssignmentExpression().add(assignment3);
317 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
318 assignment4.setAttributeId("VersionNumber");
319 assignment4.setCategory(CATEGORY_RESOURCE);
320 assignment4.setIssuer("");
322 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
323 configNameAttributeValue4.setDataType(STRING_DATATYPE);
324 configNameAttributeValue4.getContent().add(Integer.toString(version));
325 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
327 advice.getAttributeAssignmentExpression().add(assignment4);
329 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
330 assignment5.setAttributeId("matching:" + ONAPID);
331 assignment5.setCategory(CATEGORY_RESOURCE);
332 assignment5.setIssuer("");
334 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
335 configNameAttributeValue5.setDataType(STRING_DATATYPE);
336 configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
337 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
339 advice.getAttributeAssignmentExpression().add(assignment5);
342 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
343 assignment6.setAttributeId("RiskType");
344 assignment6.setCategory(CATEGORY_RESOURCE);
345 assignment6.setIssuer("");
347 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
348 configNameAttributeValue6.setDataType(STRING_DATATYPE);
349 configNameAttributeValue6.getContent().add(policyAdapter.getRiskType());
350 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
352 advice.getAttributeAssignmentExpression().add(assignment6);
354 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
355 assignment7.setAttributeId("RiskLevel");
356 assignment7.setCategory(CATEGORY_RESOURCE);
357 assignment7.setIssuer("");
359 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
360 configNameAttributeValue7.setDataType(STRING_DATATYPE);
361 configNameAttributeValue7.getContent().add(policyAdapter.getRiskLevel());
362 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
364 advice.getAttributeAssignmentExpression().add(assignment7);
366 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
367 assignment8.setAttributeId("guard");
368 assignment8.setCategory(CATEGORY_RESOURCE);
369 assignment8.setIssuer("");
371 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
372 configNameAttributeValue8.setDataType(STRING_DATATYPE);
373 configNameAttributeValue8.getContent().add(policyAdapter.getGuard());
374 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
376 advice.getAttributeAssignmentExpression().add(assignment8);
378 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
379 assignment9.setAttributeId("TTLDate");
380 assignment9.setCategory(CATEGORY_RESOURCE);
381 assignment9.setIssuer("");
383 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
384 configNameAttributeValue9.setDataType(STRING_DATATYPE);
385 configNameAttributeValue9.getContent().add(policyAdapter.getTtlDate());
386 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
388 advice.getAttributeAssignmentExpression().add(assignment9);
392 advices.getAdviceExpression().add(advice);
397 public Object getCorrectPolicyDataObject() {
398 return policyAdapter.getPolicyData();