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.std.IdentifierImpl;
44 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
51 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
52 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
53 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
54 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
55 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
56 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
58 public class ClosedLoopPolicy extends Policy {
60 private static final Logger LOGGER = FlexLogger.getLogger(ClosedLoopPolicy.class);
62 public ClosedLoopPolicy() {
66 public ClosedLoopPolicy(PolicyRestAdapter policyAdapter){
67 this.policyAdapter = policyAdapter;
70 //save configuration of the policy based on the policyname
71 private void saveConfigurations(String policyName, String jsonBody) {
73 String body = jsonBody;
76 //Remove the trapMaxAge in Verification Signature
77 body = body.replace(",\"trapMaxAge\":null", "");
79 LOGGER.debug("No Trap Max Age in JSON body");
81 this.policyAdapter.setJsonBody(body);
82 } catch (Exception e) {
83 LOGGER.error("Exception Occured"+e);
86 if(policyName.endsWith(".xml")){
87 policyName = policyName.replace(".xml", "");
89 PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator+ policyName +".json");
93 } catch (Exception e) {
94 LOGGER.error("Exception Occured while writing Configuration Data"+e);
98 //Utility to read json data from the existing file to a string
99 static String readFile(String path, Charset encoding) throws IOException {
101 byte[] encoded = Files.readAllBytes(Paths.get(path));
102 return new String(encoded, encoding);
106 //create the configuration file based on the policy name on adding the extension as .json
107 private String getConfigFile(String filename) {
108 filename = FilenameUtils.removeExtension(filename);
109 if (filename.endsWith(".xml")) {
110 filename = filename.substring(0, filename.length() - 4);
112 filename = filename + ".json";
117 public Map<String, String> savePolicies() throws Exception {
119 Map<String, String> successMap = new HashMap<>();
120 if(isPolicyExists()){
121 successMap.put("EXISTS", "This Policy already exist on the PAP");
125 if(!isPreparedToSave()){
129 // Until here we prepared the data and here calling the method to create xml.
130 Path newPolicyPath = null;
131 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
133 successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject());
137 //This is the method for preparing the policy for saving. We have broken it out
138 //separately because the fully configured policy is used for multiple things
140 public boolean prepareToSave() throws Exception{
142 if(isPreparedToSave()){
143 //we have already done this
148 String policyID = policyAdapter.getPolicyID();
149 version = policyAdapter.getHighestVersion();
151 // Create the Instance for pojo, PolicyType object is used in marshalling.
152 if (policyAdapter.getPolicyType().equals("Config")) {
153 PolicyType policyConfig = new PolicyType();
155 policyConfig.setVersion(Integer.toString(version));
156 policyConfig.setPolicyId(policyID);
157 policyConfig.setTarget(new TargetType());
158 policyAdapter.setData(policyConfig);
160 policyName = policyAdapter.getNewFileName();
161 if (policyAdapter.getData() != null) {
162 // Save the Configurations file with the policy name with extention based on selection.
163 String jsonBody = policyAdapter.getJsonBody();
164 saveConfigurations(policyName, jsonBody);
166 // Make sure the filename ends with an extension
167 if (policyName.endsWith(".xml") == false) {
168 policyName = policyName + ".xml";
171 PolicyType faultPolicy = (PolicyType) policyAdapter.getData();
173 faultPolicy.setDescription(policyAdapter.getPolicyDescription());
175 faultPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
177 AllOfType allOfOne = new AllOfType();
178 String fileName = policyAdapter.getNewFileName();
179 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
180 if ((name == null) || (name.equals(""))) {
181 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
183 allOfOne.getMatch().add(createMatch("PolicyName", name));
184 AllOfType allOf = new AllOfType();
185 // Adding the matches to AllOfType element
187 allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
188 // Match for riskType
189 allOf.getMatch().add(
190 createDynamicMatch("RiskType", policyAdapter.getRiskType()));
191 // Match for riskLevel
192 allOf.getMatch().add(
193 createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
194 // Match for riskguard
195 allOf.getMatch().add(
196 createDynamicMatch("guard", policyAdapter.getGuard()));
198 allOf.getMatch().add(
199 createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
201 AnyOfType anyOf = new AnyOfType();
202 anyOf.getAllOf().add(allOfOne);
203 anyOf.getAllOf().add(allOf);
205 TargetType target = new TargetType();
206 ((TargetType) target).getAnyOf().add(anyOf);
207 // Adding the target to the policy element
208 faultPolicy.setTarget((TargetType) target);
210 RuleType rule = new RuleType();
211 rule.setRuleId(policyAdapter.getRuleID());
212 rule.setEffect(EffectType.PERMIT);
214 // Create Target in Rule
215 AllOfType allOfInRule = new AllOfType();
217 // Creating match for ACCESS in rule target
218 MatchType accessMatch = new MatchType();
219 AttributeValueType accessAttributeValue = new AttributeValueType();
220 accessAttributeValue.setDataType(STRING_DATATYPE);
221 accessAttributeValue.getContent().add("ACCESS");
222 accessMatch.setAttributeValue(accessAttributeValue);
223 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
224 URI accessURI = null;
226 accessURI = new URI(ACTION_ID);
227 } catch (URISyntaxException e) {
228 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "CreateClosedLoopPolicy", "Exception creating ACCESS URI");
230 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
231 accessAttributeDesignator.setDataType(STRING_DATATYPE);
232 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
233 accessMatch.setAttributeDesignator(accessAttributeDesignator);
234 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
236 // Creating Config Match in rule Target
237 MatchType closedMatch = new MatchType();
238 AttributeValueType closedAttributeValue = new AttributeValueType();
239 closedAttributeValue.setDataType(STRING_DATATYPE);
240 closedAttributeValue.getContent().add("Config");
241 closedMatch.setAttributeValue(closedAttributeValue);
242 AttributeDesignatorType closedAttributeDesignator = new AttributeDesignatorType();
243 URI closedURI = null;
245 closedURI = new URI(RESOURCE_ID);
246 } catch (URISyntaxException e) {
247 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "CreateClosedLoopPolicy", "Exception creating closed URI");
249 closedAttributeDesignator.setCategory(CATEGORY_RESOURCE);
250 closedAttributeDesignator.setDataType(STRING_DATATYPE);
251 closedAttributeDesignator.setAttributeId(new IdentifierImpl(closedURI).stringValue());
252 closedMatch.setAttributeDesignator(closedAttributeDesignator);
253 closedMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
255 allOfInRule.getMatch().add(accessMatch);
256 allOfInRule.getMatch().add(closedMatch);
258 AnyOfType anyOfInRule = new AnyOfType();
259 anyOfInRule.getAllOf().add(allOfInRule);
261 TargetType targetInRule = new TargetType();
262 targetInRule.getAnyOf().add(anyOfInRule);
264 rule.setTarget(targetInRule);
265 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
267 faultPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
268 policyAdapter.setPolicyData(faultPolicy);
271 PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
274 setPreparedToSave(true);
278 // Data required for Advice part is setting here.
279 private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
280 AdviceExpressionsType advices = new AdviceExpressionsType();
281 AdviceExpressionType advice = new AdviceExpressionType();
282 advice.setAdviceId("faultID");
283 advice.setAppliesTo(EffectType.PERMIT);
285 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
286 assignment1.setAttributeId("type");
287 assignment1.setCategory(CATEGORY_RESOURCE);
288 assignment1.setIssuer("");
290 AttributeValueType configNameAttributeValue = new AttributeValueType();
291 configNameAttributeValue.setDataType(STRING_DATATYPE);
292 configNameAttributeValue.getContent().add("Configuration");
293 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
295 advice.getAttributeAssignmentExpression().add(assignment1);
296 // For Config file Url if configurations are provided.
297 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
298 assignment2.setAttributeId("URLID");
299 assignment2.setCategory(CATEGORY_RESOURCE);
300 assignment2.setIssuer("");
302 AttributeValueType AttributeValue = new AttributeValueType();
303 AttributeValue.setDataType(URI_DATATYPE);
304 String content = CONFIG_URL +"/Config/" + getConfigFile(policyName);
305 System.out.println("URL value :" + content);
306 AttributeValue.getContent().add(content);
307 assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
309 advice.getAttributeAssignmentExpression().add(assignment2);
310 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
311 assignment3.setAttributeId("PolicyName");
312 assignment3.setCategory(CATEGORY_RESOURCE);
313 assignment3.setIssuer("");
315 AttributeValueType attributeValue3 = new AttributeValueType();
316 attributeValue3.setDataType(STRING_DATATYPE);
317 fileName = FilenameUtils.removeExtension(fileName);
318 fileName = fileName + ".xml";
319 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
320 if ((name == null) || (name.equals(""))) {
321 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
323 attributeValue3.getContent().add(name);
324 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
325 advice.getAttributeAssignmentExpression().add(assignment3);
327 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
328 assignment4.setAttributeId("VersionNumber");
329 assignment4.setCategory(CATEGORY_RESOURCE);
330 assignment4.setIssuer("");
332 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
333 configNameAttributeValue4.setDataType(STRING_DATATYPE);
334 configNameAttributeValue4.getContent().add(Integer.toString(version));
335 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
337 advice.getAttributeAssignmentExpression().add(assignment4);
339 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
340 assignment5.setAttributeId("matching:" + ONAPID);
341 assignment5.setCategory(CATEGORY_RESOURCE);
342 assignment5.setIssuer("");
344 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
345 configNameAttributeValue5.setDataType(STRING_DATATYPE);
346 configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
347 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
349 advice.getAttributeAssignmentExpression().add(assignment5);
352 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
353 assignment6.setAttributeId("RiskType");
354 assignment6.setCategory(CATEGORY_RESOURCE);
355 assignment6.setIssuer("");
357 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
358 configNameAttributeValue6.setDataType(STRING_DATATYPE);
359 configNameAttributeValue6.getContent().add(policyAdapter.getRiskType());
360 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
362 advice.getAttributeAssignmentExpression().add(assignment6);
364 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
365 assignment7.setAttributeId("RiskLevel");
366 assignment7.setCategory(CATEGORY_RESOURCE);
367 assignment7.setIssuer("");
369 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
370 configNameAttributeValue7.setDataType(STRING_DATATYPE);
371 configNameAttributeValue7.getContent().add(policyAdapter.getRiskLevel());
372 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
374 advice.getAttributeAssignmentExpression().add(assignment7);
376 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
377 assignment8.setAttributeId("guard");
378 assignment8.setCategory(CATEGORY_RESOURCE);
379 assignment8.setIssuer("");
381 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
382 configNameAttributeValue8.setDataType(STRING_DATATYPE);
383 configNameAttributeValue8.getContent().add(policyAdapter.getGuard());
384 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
386 advice.getAttributeAssignmentExpression().add(assignment8);
388 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
389 assignment9.setAttributeId("TTLDate");
390 assignment9.setCategory(CATEGORY_RESOURCE);
391 assignment9.setIssuer("");
393 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
394 configNameAttributeValue9.setDataType(STRING_DATATYPE);
395 configNameAttributeValue9.getContent().add(policyAdapter.getTtlDate());
396 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
398 advice.getAttributeAssignmentExpression().add(assignment9);
402 advices.getAdviceExpression().add(advice);
407 public Object getCorrectPolicyDataObject() {
408 return policyAdapter.getPolicyData();