2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
7 * Modified Copyright (C) 2019 Bell Canada.
8 * ================================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
20 * ============LICENSE_END=========================================================
23 package org.onap.policy.pap.xacml.rest.components;
25 import java.io.BufferedWriter;
27 import java.io.FileWriter;
28 import java.io.IOException;
30 import java.net.URISyntaxException;
31 import java.nio.file.Path;
32 import java.nio.file.Paths;
33 import java.util.HashMap;
36 import org.apache.commons.io.FilenameUtils;
37 import org.onap.policy.common.logging.eelf.MessageCodes;
38 import org.onap.policy.common.logging.eelf.PolicyLogger;
39 import org.onap.policy.common.logging.flexlogger.FlexLogger;
40 import org.onap.policy.common.logging.flexlogger.Logger;
41 import org.onap.policy.rest.adapter.PolicyRestAdapter;
42 import org.onap.policy.utils.PolicyUtils;
44 import com.att.research.xacml.api.pap.PAPException;
45 import com.att.research.xacml.std.IdentifierImpl;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
51 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
52 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
53 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
54 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
55 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
56 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
57 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
58 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
59 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
61 public class ConfigPolicy extends Policy {
66 private static final Logger LOGGER = FlexLogger.getLogger(ConfigPolicy.class);
68 public static final String JSON_CONFIG = "JSON";
69 public static final String XML_CONFIG = "XML";
70 public static final String PROPERTIES_CONFIG = "PROPERTIES";
71 public static final String OTHER_CONFIG = "OTHER";
73 private String configBodyData;
75 public ConfigPolicy() {
79 public ConfigPolicy(PolicyRestAdapter policyAdapter) {
80 this.policyAdapter = policyAdapter;
83 // Saving the Configurations file at server location for config policy.
84 protected void saveConfigurations(String policyName) {
85 String fileName = getConfigFile(policyName);
86 try (BufferedWriter bw = new BufferedWriter(new FileWriter(CONFIG_HOME + File.separator + fileName))) {
87 bw.write(configBodyData);
88 if (LOGGER.isDebugEnabled()) {
89 LOGGER.debug("Configuration is succesfully saved");
91 } catch (IOException e) {
92 LOGGER.error("Exception Occured while writing Configuration Data" + e);
97 // Here we are adding the extension for the configurations file based on the
98 // config type selection for saving.
99 private String getConfigFile(String filename) {
100 filename = removeExtentsion(filename);
101 String id = policyAdapter.getConfigType();
106 switch (id.toUpperCase())
109 return filename + ".json";
111 return filename + ".xml";
112 case PROPERTIES_CONFIG:
113 return filename + ".properties";
115 return filename + ".txt";
122 private String removeExtentsion(String filename) {
123 filename = FilenameUtils.removeExtension(filename);
124 if (filename.endsWith(".xml")) {
125 filename = filename.substring(0, filename.length() - 4);
131 // Validations for Config form
133 * FORM VALIDATION WILL BE DONE BY THE PAP-ADMIN before creating JSON object...
134 * BODY VALIDATION WILL BE DONE BY THE PAP-REST after receiving and deserializing the JSON object
136 public boolean validateConfigForm() {
141 * Validate Text Area Body
143 configBodyData = policyAdapter.getConfigBodyData();
144 String id = policyAdapter.getConfigType();
150 if (!PolicyUtils.isJSONValid(configBodyData)) {
155 if (!PolicyUtils.isXMLValid(configBodyData)) {
159 case PROPERTIES_CONFIG:
160 if (!PolicyUtils.isPropValid(configBodyData) || configBodyData.equals("")) {
165 if (configBodyData.equals("")) {
175 public Map<String, String> savePolicies() throws PAPException {
177 Map<String, String> successMap = new HashMap<>();
178 if (isPolicyExists()) {
179 successMap.put("EXISTS", "This Policy already exist on the PAP");
183 if (!isPreparedToSave()) {
184 //Prep and configure the policy for saving
188 // Until here we prepared the data and here calling the method to create xml.
189 Path newPolicyPath = null;
190 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
191 successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject());
195 //This is the method for preparing the policy for saving. We have broken it out
196 //separately because the fully configured policy is used for multiple things
198 public boolean prepareToSave() throws PAPException {
200 if (isPreparedToSave()) {
205 String policyID = policyAdapter.getPolicyID();
206 version = policyAdapter.getHighestVersion();
208 // Create the Instance for pojo, PolicyType object is used in marshalling.
209 if (policyAdapter.getPolicyType().equals("Config")) {
210 PolicyType policyConfig = new PolicyType();
212 policyConfig.setVersion(Integer.toString(version));
213 policyConfig.setPolicyId(policyID);
214 policyConfig.setTarget(new TargetType());
215 policyAdapter.setData(policyConfig);
218 policyName = policyAdapter.getNewFileName();
219 configBodyData = policyAdapter.getConfigBodyData();
220 saveConfigurations(policyName);
222 if (policyAdapter.getData() != null) {
223 PolicyType configPolicy = (PolicyType) policyAdapter.getData();
225 configPolicy.setDescription(policyAdapter.getPolicyDescription());
227 configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
228 AllOfType allOfOne = new AllOfType();
230 String fileName = policyAdapter.getNewFileName();
231 String name = fileName.substring(fileName.lastIndexOf("\\") + 1);
232 if ((name == null) || (name.equals(""))) {
233 name = fileName.substring(fileName.lastIndexOf("/") + 1);
235 allOfOne.getMatch().add(createMatch("PolicyName", name));
236 AllOfType allOf = new AllOfType();
238 // Adding the matches to AllOfType element Match for Onap
239 allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
240 // Match for riskType
241 allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
242 // Match for riskLevel
243 allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
244 // Match for riskguard
245 allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
247 allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
248 // Match for ConfigName
249 allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
251 Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
253 // If there is any dynamic field create the matches here
254 for (String keyField : dynamicFieldConfigAttributes.keySet()) {
255 String key = keyField;
256 String value = dynamicFieldConfigAttributes.get(key);
257 MatchType dynamicMatch = createDynamicMatch(key, value);
258 allOf.getMatch().add(dynamicMatch);
261 AnyOfType anyOf = new AnyOfType();
262 anyOf.getAllOf().add(allOfOne);
263 anyOf.getAllOf().add(allOf);
265 TargetType target = new TargetType();
266 ((TargetType) target).getAnyOf().add(anyOf);
268 // Adding the target to the policy element
269 configPolicy.setTarget((TargetType) target);
271 RuleType rule = new RuleType();
272 rule.setRuleId(policyAdapter.getRuleID());
273 rule.setEffect(EffectType.PERMIT);
275 // Create Target in Rule
276 AllOfType allOfInRule = new AllOfType();
278 // Creating match for ACCESS in rule target
279 MatchType accessMatch = new MatchType();
280 AttributeValueType accessAttributeValue = new AttributeValueType();
281 accessAttributeValue.setDataType(STRING_DATATYPE);
282 accessAttributeValue.getContent().add("ACCESS");
283 accessMatch.setAttributeValue(accessAttributeValue);
284 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
285 URI accessURI = null;
287 accessURI = new URI(ACTION_ID);
288 } catch (URISyntaxException e) {
289 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "ConfigPolicy", "Exception creating ACCESS URI");
291 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
292 accessAttributeDesignator.setDataType(STRING_DATATYPE);
293 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
294 accessMatch.setAttributeDesignator(accessAttributeDesignator);
295 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
297 // Creating Config Match in rule Target
298 MatchType configMatch = new MatchType();
299 AttributeValueType configAttributeValue = new AttributeValueType();
300 configAttributeValue.setDataType(STRING_DATATYPE);
301 configAttributeValue.getContent().add("Config");
302 configMatch.setAttributeValue(configAttributeValue);
303 AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
304 URI configURI = null;
306 configURI = new URI(RESOURCE_ID);
307 } catch (URISyntaxException e) {
308 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "ConfigPolicy", "Exception creating Config URI");
310 configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
311 configAttributeDesignator.setDataType(STRING_DATATYPE);
312 configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
313 configMatch.setAttributeDesignator(configAttributeDesignator);
314 configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
316 allOfInRule.getMatch().add(accessMatch);
317 allOfInRule.getMatch().add(configMatch);
319 AnyOfType anyOfInRule = new AnyOfType();
320 anyOfInRule.getAllOf().add(allOfInRule);
322 TargetType targetInRule = new TargetType();
323 targetInRule.getAnyOf().add(anyOfInRule);
325 rule.setTarget(targetInRule);
326 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
328 configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
329 policyAdapter.setPolicyData(configPolicy);
332 PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
334 setPreparedToSave(true);
338 // Data required for Advice part is setting here.
339 private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
340 AdviceExpressionsType advices = new AdviceExpressionsType();
341 AdviceExpressionType advice = new AdviceExpressionType();
342 advice.setAdviceId("configID");
343 advice.setAppliesTo(EffectType.PERMIT);
346 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
347 assignment1.setAttributeId("type");
348 assignment1.setCategory(CATEGORY_RESOURCE);
349 assignment1.setIssuer("");
351 AttributeValueType configNameAttributeValue = new AttributeValueType();
352 configNameAttributeValue.setDataType(STRING_DATATYPE);
353 configNameAttributeValue.getContent().add("Configuration");
354 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
356 advice.getAttributeAssignmentExpression().add(assignment1);
358 // For Config file Url if configurations are provided.
359 if (policyAdapter.getConfigType() != null) {
360 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
361 assignment2.setAttributeId("URLID");
362 assignment2.setCategory(CATEGORY_RESOURCE);
363 assignment2.setIssuer("");
365 AttributeValueType AttributeValue = new AttributeValueType();
366 AttributeValue.setDataType(URI_DATATYPE);
367 String content = "$URL" + "/Config/" + getConfigFile(policyName);
368 AttributeValue.getContent().add(content);
369 assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
371 advice.getAttributeAssignmentExpression().add(assignment2);
372 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
373 assignment3.setAttributeId("PolicyName");
374 assignment3.setCategory(CATEGORY_RESOURCE);
375 assignment3.setIssuer("");
377 AttributeValueType attributeValue3 = new AttributeValueType();
378 attributeValue3.setDataType(STRING_DATATYPE);
380 fileName = FilenameUtils.removeExtension(fileName);
381 fileName = fileName + ".xml";
382 String name = fileName.substring(fileName.lastIndexOf("\\") + 1);
383 if ((name == null) || (name.equals(""))) {
384 name = fileName.substring(fileName.lastIndexOf("/") + 1);
386 attributeValue3.getContent().add(name);
387 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
388 advice.getAttributeAssignmentExpression().add(assignment3);
390 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
391 assignment4.setAttributeId("VersionNumber");
392 assignment4.setCategory(CATEGORY_RESOURCE);
393 assignment4.setIssuer("");
395 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
396 configNameAttributeValue4.setDataType(STRING_DATATYPE);
397 configNameAttributeValue4.getContent().add(Integer.toString(version));
398 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
400 advice.getAttributeAssignmentExpression().add(assignment4);
402 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
403 assignment5.setAttributeId("matching:" + ONAPID);
404 assignment5.setCategory(CATEGORY_RESOURCE);
405 assignment5.setIssuer("");
407 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
408 configNameAttributeValue5.setDataType(STRING_DATATYPE);
409 configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
410 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
412 advice.getAttributeAssignmentExpression().add(assignment5);
414 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
415 assignment6.setAttributeId("matching:" + CONFIGID);
416 assignment6.setCategory(CATEGORY_RESOURCE);
417 assignment6.setIssuer("");
419 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
420 configNameAttributeValue6.setDataType(STRING_DATATYPE);
421 configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
422 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
424 advice.getAttributeAssignmentExpression().add(assignment6);
426 Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
427 for (String keyField : dynamicFieldConfigAttributes.keySet()) {
428 String key = keyField;
429 String value = dynamicFieldConfigAttributes.get(key);
430 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
431 assignment7.setAttributeId("matching:" + key);
432 assignment7.setCategory(CATEGORY_RESOURCE);
433 assignment7.setIssuer("");
435 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
436 configNameAttributeValue7.setDataType(STRING_DATATYPE);
437 configNameAttributeValue7.getContent().add(value);
438 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
440 advice.getAttributeAssignmentExpression().add(assignment7);
445 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
446 assignment8.setAttributeId("RiskType");
447 assignment8.setCategory(CATEGORY_RESOURCE);
448 assignment8.setIssuer("");
450 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
451 configNameAttributeValue8.setDataType(STRING_DATATYPE);
452 configNameAttributeValue8.getContent().add(policyAdapter.getRiskType());
453 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
455 advice.getAttributeAssignmentExpression().add(assignment8);
457 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
458 assignment9.setAttributeId("RiskLevel");
459 assignment9.setCategory(CATEGORY_RESOURCE);
460 assignment9.setIssuer("");
462 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
463 configNameAttributeValue9.setDataType(STRING_DATATYPE);
464 configNameAttributeValue9.getContent().add(policyAdapter.getRiskLevel());
465 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
467 advice.getAttributeAssignmentExpression().add(assignment9);
469 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
470 assignment10.setAttributeId("guard");
471 assignment10.setCategory(CATEGORY_RESOURCE);
472 assignment10.setIssuer("");
474 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
475 configNameAttributeValue10.setDataType(STRING_DATATYPE);
476 configNameAttributeValue10.getContent().add(policyAdapter.getGuard());
477 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
479 advice.getAttributeAssignmentExpression().add(assignment10);
481 AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
482 assignment11.setAttributeId("TTLDate");
483 assignment11.setCategory(CATEGORY_RESOURCE);
484 assignment11.setIssuer("");
486 AttributeValueType configNameAttributeValue11 = new AttributeValueType();
487 configNameAttributeValue11.setDataType(STRING_DATATYPE);
488 configNameAttributeValue11.getContent().add(policyAdapter.getTtlDate());
489 assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11));
491 advice.getAttributeAssignmentExpression().add(assignment11);
493 advices.getAdviceExpression().add(advice);
498 public Object getCorrectPolicyDataObject() {
499 return policyAdapter.getPolicyData();