2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017, 2019 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 com.att.research.xacml.api.pap.PAPException;
26 import com.att.research.xacml.std.IdentifierImpl;
28 import java.io.BufferedWriter;
30 import java.io.FileWriter;
31 import java.io.IOException;
33 import java.net.URISyntaxException;
34 import java.nio.file.Path;
35 import java.nio.file.Paths;
36 import java.util.HashMap;
39 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
40 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
41 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
42 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
43 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
44 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
51 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
53 import org.apache.commons.io.FilenameUtils;
54 import org.onap.policy.common.logging.eelf.MessageCodes;
55 import org.onap.policy.common.logging.eelf.PolicyLogger;
56 import org.onap.policy.common.logging.flexlogger.FlexLogger;
57 import org.onap.policy.common.logging.flexlogger.Logger;
58 import org.onap.policy.rest.adapter.PolicyRestAdapter;
59 import org.onap.policy.utils.PolicyUtils;
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);
96 // Here we are adding the extension for the configurations file based on the
97 // config type selection for saving.
98 private String getConfigFile(String filename) {
99 filename = removeExtentsion(filename);
100 String id = policyAdapter.getConfigType();
105 switch (id.toUpperCase()) {
107 return filename + ".json";
109 return filename + ".xml";
110 case PROPERTIES_CONFIG:
111 return filename + ".properties";
113 return filename + ".txt";
120 private String removeExtentsion(String filename) {
121 filename = FilenameUtils.removeExtension(filename);
122 if (filename.endsWith(".xml")) {
123 filename = filename.substring(0, filename.length() - 4);
128 // Validations for Config form
130 * FORM VALIDATION WILL BE DONE BY THE PAP-ADMIN before creating JSON object...
131 * BODY VALIDATION WILL BE DONE BY THE PAP-REST after receiving and deserializing the JSON object
133 public boolean validateConfigForm() {
138 * Validate Text Area Body
140 configBodyData = policyAdapter.getConfigBodyData();
141 String id = policyAdapter.getConfigType();
147 if (!PolicyUtils.isJSONValid(configBodyData)) {
152 if (!PolicyUtils.isXMLValid(configBodyData)) {
156 case PROPERTIES_CONFIG:
157 if (!PolicyUtils.isPropValid(configBodyData) || configBodyData.equals("")) {
162 if (configBodyData.equals("")) {
172 public Map<String, String> savePolicies() throws PAPException {
174 Map<String, String> successMap = new HashMap<>();
175 if (isPolicyExists()) {
176 successMap.put("EXISTS", "This Policy already exist on the PAP");
180 if (!isPreparedToSave()) {
181 // Prep and configure the policy for saving
185 // Until here we prepared the data and here calling the method to create xml.
186 Path newPolicyPath = null;
187 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
188 successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject());
192 // This is the method for preparing the policy for saving. We have broken it out
193 // separately because the fully configured policy is used for multiple things
195 public boolean prepareToSave() throws PAPException {
197 if (isPreparedToSave()) {
202 String policyID = policyAdapter.getPolicyID();
203 version = policyAdapter.getHighestVersion();
205 // Create the Instance for pojo, PolicyType object is used in marshalling.
206 if (policyAdapter.getPolicyType().equals("Config")) {
207 PolicyType policyConfig = new PolicyType();
209 policyConfig.setVersion(Integer.toString(version));
210 policyConfig.setPolicyId(policyID);
211 policyConfig.setTarget(new TargetType());
212 policyAdapter.setData(policyConfig);
215 policyName = policyAdapter.getNewFileName();
216 configBodyData = policyAdapter.getConfigBodyData();
217 saveConfigurations(policyName);
219 if (policyAdapter.getData() != null) {
220 PolicyType configPolicy = (PolicyType) policyAdapter.getData();
222 configPolicy.setDescription(policyAdapter.getPolicyDescription());
224 configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
225 AllOfType allOfOne = new AllOfType();
227 String fileName = policyAdapter.getNewFileName();
228 String name = fileName.substring(fileName.lastIndexOf("\\") + 1);
229 if ((name == null) || (name.equals(""))) {
230 name = fileName.substring(fileName.lastIndexOf("/") + 1);
232 allOfOne.getMatch().add(createMatch("PolicyName", name));
233 AllOfType allOf = new AllOfType();
235 // Adding the matches to AllOfType element Match for Onap
236 allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
237 // Match for riskType
238 allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
239 // Match for riskLevel
240 allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
241 // Match for riskguard
242 allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
244 allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
245 // Match for ConfigName
246 allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
248 Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
250 // If there is any dynamic field create the matches here
251 for (String keyField : dynamicFieldConfigAttributes.keySet()) {
252 String key = keyField;
253 String value = dynamicFieldConfigAttributes.get(key);
254 MatchType dynamicMatch = createDynamicMatch(key, value);
255 allOf.getMatch().add(dynamicMatch);
258 AnyOfType anyOf = new AnyOfType();
259 anyOf.getAllOf().add(allOfOne);
260 anyOf.getAllOf().add(allOf);
262 TargetType target = new TargetType();
263 ((TargetType) target).getAnyOf().add(anyOf);
265 // Adding the target to the policy element
266 configPolicy.setTarget((TargetType) target);
268 RuleType rule = new RuleType();
269 rule.setRuleId(policyAdapter.getRuleID());
270 rule.setEffect(EffectType.PERMIT);
272 // Create Target in Rule
273 AllOfType allOfInRule = new AllOfType();
275 // Creating match for ACCESS in rule target
276 MatchType accessMatch = new MatchType();
277 AttributeValueType accessAttributeValue = new AttributeValueType();
278 accessAttributeValue.setDataType(STRING_DATATYPE);
279 accessAttributeValue.getContent().add("ACCESS");
280 accessMatch.setAttributeValue(accessAttributeValue);
281 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
282 URI accessURI = null;
284 accessURI = new URI(ACTION_ID);
285 } catch (URISyntaxException e) {
286 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "ConfigPolicy", "Exception creating ACCESS URI");
288 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
289 accessAttributeDesignator.setDataType(STRING_DATATYPE);
290 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
291 accessMatch.setAttributeDesignator(accessAttributeDesignator);
292 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
294 // Creating Config Match in rule Target
295 MatchType configMatch = new MatchType();
296 AttributeValueType configAttributeValue = new AttributeValueType();
297 configAttributeValue.setDataType(STRING_DATATYPE);
298 configAttributeValue.getContent().add("Config");
299 configMatch.setAttributeValue(configAttributeValue);
300 AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
301 URI configURI = null;
303 configURI = new URI(RESOURCE_ID);
304 } catch (URISyntaxException e) {
305 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "ConfigPolicy", "Exception creating Config URI");
307 configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
308 configAttributeDesignator.setDataType(STRING_DATATYPE);
309 configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
310 configMatch.setAttributeDesignator(configAttributeDesignator);
311 configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
313 allOfInRule.getMatch().add(accessMatch);
314 allOfInRule.getMatch().add(configMatch);
316 AnyOfType anyOfInRule = new AnyOfType();
317 anyOfInRule.getAllOf().add(allOfInRule);
319 TargetType targetInRule = new TargetType();
320 targetInRule.getAnyOf().add(anyOfInRule);
322 rule.setTarget(targetInRule);
323 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
325 configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
326 policyAdapter.setPolicyData(configPolicy);
329 PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
331 setPreparedToSave(true);
335 // Data required for Advice part is setting here.
336 private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
337 AdviceExpressionsType advices = new AdviceExpressionsType();
338 AdviceExpressionType advice = new AdviceExpressionType();
339 advice.setAdviceId("configID");
340 advice.setAppliesTo(EffectType.PERMIT);
343 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
344 assignment1.setAttributeId("type");
345 assignment1.setCategory(CATEGORY_RESOURCE);
346 assignment1.setIssuer("");
348 AttributeValueType configNameAttributeValue = new AttributeValueType();
349 configNameAttributeValue.setDataType(STRING_DATATYPE);
350 configNameAttributeValue.getContent().add("Configuration");
351 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
353 advice.getAttributeAssignmentExpression().add(assignment1);
355 // For Config file Url if configurations are provided.
356 if (policyAdapter.getConfigType() != null) {
357 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
358 assignment2.setAttributeId("URLID");
359 assignment2.setCategory(CATEGORY_RESOURCE);
360 assignment2.setIssuer("");
362 AttributeValueType AttributeValue = new AttributeValueType();
363 AttributeValue.setDataType(URI_DATATYPE);
364 String content = "$URL" + "/Config/" + getConfigFile(policyName);
365 AttributeValue.getContent().add(content);
366 assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
368 advice.getAttributeAssignmentExpression().add(assignment2);
369 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
370 assignment3.setAttributeId("PolicyName");
371 assignment3.setCategory(CATEGORY_RESOURCE);
372 assignment3.setIssuer("");
374 AttributeValueType attributeValue3 = new AttributeValueType();
375 attributeValue3.setDataType(STRING_DATATYPE);
377 fileName = FilenameUtils.removeExtension(fileName);
378 fileName = fileName + ".xml";
379 String name = fileName.substring(fileName.lastIndexOf("\\") + 1);
380 if ((name == null) || (name.equals(""))) {
381 name = fileName.substring(fileName.lastIndexOf("/") + 1);
383 attributeValue3.getContent().add(name);
384 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
385 advice.getAttributeAssignmentExpression().add(assignment3);
387 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
388 assignment4.setAttributeId("VersionNumber");
389 assignment4.setCategory(CATEGORY_RESOURCE);
390 assignment4.setIssuer("");
392 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
393 configNameAttributeValue4.setDataType(STRING_DATATYPE);
394 configNameAttributeValue4.getContent().add(Integer.toString(version));
395 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
397 advice.getAttributeAssignmentExpression().add(assignment4);
399 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
400 assignment5.setAttributeId("matching:" + ONAPID);
401 assignment5.setCategory(CATEGORY_RESOURCE);
402 assignment5.setIssuer("");
404 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
405 configNameAttributeValue5.setDataType(STRING_DATATYPE);
406 configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
407 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
409 advice.getAttributeAssignmentExpression().add(assignment5);
411 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
412 assignment6.setAttributeId("matching:" + CONFIGID);
413 assignment6.setCategory(CATEGORY_RESOURCE);
414 assignment6.setIssuer("");
416 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
417 configNameAttributeValue6.setDataType(STRING_DATATYPE);
418 configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
419 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
421 advice.getAttributeAssignmentExpression().add(assignment6);
423 Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
424 for (String keyField : dynamicFieldConfigAttributes.keySet()) {
425 String key = keyField;
426 String value = dynamicFieldConfigAttributes.get(key);
427 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
428 assignment7.setAttributeId("matching:" + key);
429 assignment7.setCategory(CATEGORY_RESOURCE);
430 assignment7.setIssuer("");
432 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
433 configNameAttributeValue7.setDataType(STRING_DATATYPE);
434 configNameAttributeValue7.getContent().add(value);
435 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
437 advice.getAttributeAssignmentExpression().add(assignment7);
442 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
443 assignment8.setAttributeId("RiskType");
444 assignment8.setCategory(CATEGORY_RESOURCE);
445 assignment8.setIssuer("");
447 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
448 configNameAttributeValue8.setDataType(STRING_DATATYPE);
449 configNameAttributeValue8.getContent().add(policyAdapter.getRiskType());
450 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
452 advice.getAttributeAssignmentExpression().add(assignment8);
454 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
455 assignment9.setAttributeId("RiskLevel");
456 assignment9.setCategory(CATEGORY_RESOURCE);
457 assignment9.setIssuer("");
459 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
460 configNameAttributeValue9.setDataType(STRING_DATATYPE);
461 configNameAttributeValue9.getContent().add(policyAdapter.getRiskLevel());
462 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
464 advice.getAttributeAssignmentExpression().add(assignment9);
466 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
467 assignment10.setAttributeId("guard");
468 assignment10.setCategory(CATEGORY_RESOURCE);
469 assignment10.setIssuer("");
471 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
472 configNameAttributeValue10.setDataType(STRING_DATATYPE);
473 configNameAttributeValue10.getContent().add(policyAdapter.getGuard());
474 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
476 advice.getAttributeAssignmentExpression().add(assignment10);
478 AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
479 assignment11.setAttributeId("TTLDate");
480 assignment11.setCategory(CATEGORY_RESOURCE);
481 assignment11.setIssuer("");
483 AttributeValueType configNameAttributeValue11 = new AttributeValueType();
484 configNameAttributeValue11.setDataType(STRING_DATATYPE);
485 configNameAttributeValue11.getContent().add(policyAdapter.getTtlDate());
486 assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11));
488 advice.getAttributeAssignmentExpression().add(assignment11);
490 advices.getAdviceExpression().add(advice);
495 public Object getCorrectPolicyDataObject() {
496 return policyAdapter.getPolicyData();