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 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.pap.xacml.rest.components;
24 import java.io.BufferedWriter;
26 import java.io.FileWriter;
27 import java.io.IOException;
29 import java.net.URISyntaxException;
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;
41 import org.onap.policy.utils.PolicyUtils;
43 import com.att.research.xacml.api.pap.PAPException;
44 import com.att.research.xacml.std.IdentifierImpl;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
51 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
52 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
53 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
54 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
55 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
56 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
57 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
58 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
60 public class ConfigPolicy extends Policy {
65 private static final Logger LOGGER = FlexLogger.getLogger(ConfigPolicy.class);
67 public static final String JSON_CONFIG = "JSON";
68 public static final String XML_CONFIG = "XML";
69 public static final String PROPERTIES_CONFIG = "PROPERTIES";
70 public static final String OTHER_CONFIG = "OTHER";
72 private String configBodyData;
74 public ConfigPolicy() {
78 public ConfigPolicy(PolicyRestAdapter policyAdapter) {
79 this.policyAdapter = policyAdapter;
82 // Saving the Configurations file at server location for config policy.
83 protected void saveConfigurations(String policyName) {
84 String fileName = getConfigFile(policyName);
85 try (BufferedWriter bw = new BufferedWriter(new FileWriter(CONFIG_HOME + File.separator + fileName))) {
86 bw.write(configBodyData);
87 if (LOGGER.isDebugEnabled()) {
88 LOGGER.debug("Configuration is succesfully saved");
90 } catch (IOException e) {
91 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 = FilenameUtils.removeExtension(filename);
100 if (filename.endsWith(".xml")) {
101 filename = filename.substring(0, filename.length() - 4);
103 String id = policyAdapter.getConfigType();
106 if (id.equalsIgnoreCase(JSON_CONFIG)) {
107 filename = filename + ".json";
109 if (id.equalsIgnoreCase(XML_CONFIG)) {
110 filename = filename + ".xml";
112 if (id.equalsIgnoreCase(PROPERTIES_CONFIG)) {
113 filename = filename + ".properties";
115 if (id.equalsIgnoreCase(OTHER_CONFIG)) {
116 filename = filename + ".txt";
123 // Validations for Config form
125 * FORM VALIDATION WILL BE DONE BY THE PAP-ADMIN before creating JSON object...
126 * BODY VALIDATION WILL BE DONE BY THE PAP-REST after receiving and deserializing the JSON object
128 public boolean validateConfigForm() {
133 * Validate Text Area Body
135 configBodyData = policyAdapter.getConfigBodyData();
136 String id = policyAdapter.getConfigType();
138 if (id.equals(JSON_CONFIG)) {
139 if (!PolicyUtils.isJSONValid(configBodyData)) {
142 } else if (id.equals(XML_CONFIG)) {
143 if (!PolicyUtils.isXMLValid(configBodyData)) {
146 } else if (id.equals(PROPERTIES_CONFIG)) {
147 if (!PolicyUtils.isPropValid(configBodyData) || configBodyData.equals("")) {
150 } else if (id.equals(OTHER_CONFIG)) {
151 if (configBodyData.equals("")) {
161 public Map<String, String> savePolicies() throws PAPException {
163 Map<String, String> successMap = new HashMap<>();
164 if (isPolicyExists()) {
165 successMap.put("EXISTS", "This Policy already exist on the PAP");
169 if (!isPreparedToSave()) {
170 //Prep and configure the policy for saving
174 // Until here we prepared the data and here calling the method to create xml.
175 Path newPolicyPath = null;
176 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
177 successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject());
181 //This is the method for preparing the policy for saving. We have broken it out
182 //separately because the fully configured policy is used for multiple things
184 public boolean prepareToSave() throws PAPException {
186 if (isPreparedToSave()) {
191 String policyID = policyAdapter.getPolicyID();
192 version = policyAdapter.getHighestVersion();
194 // Create the Instance for pojo, PolicyType object is used in marshalling.
195 if (policyAdapter.getPolicyType().equals("Config")) {
196 PolicyType policyConfig = new PolicyType();
198 policyConfig.setVersion(Integer.toString(version));
199 policyConfig.setPolicyId(policyID);
200 policyConfig.setTarget(new TargetType());
201 policyAdapter.setData(policyConfig);
204 policyName = policyAdapter.getNewFileName();
205 configBodyData = policyAdapter.getConfigBodyData();
206 saveConfigurations(policyName);
208 if (policyAdapter.getData() != null) {
209 PolicyType configPolicy = (PolicyType) policyAdapter.getData();
211 configPolicy.setDescription(policyAdapter.getPolicyDescription());
213 configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
214 AllOfType allOfOne = new AllOfType();
216 String fileName = policyAdapter.getNewFileName();
217 String name = fileName.substring(fileName.lastIndexOf("\\") + 1);
218 if ((name == null) || (name.equals(""))) {
219 name = fileName.substring(fileName.lastIndexOf("/") + 1);
221 allOfOne.getMatch().add(createMatch("PolicyName", name));
222 AllOfType allOf = new AllOfType();
224 // Adding the matches to AllOfType element Match for Onap
225 allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
226 // Match for riskType
227 allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
228 // Match for riskLevel
229 allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
230 // Match for riskguard
231 allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
233 allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
234 // Match for ConfigName
235 allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
237 Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
239 // If there is any dynamic field create the matches here
240 for (String keyField : dynamicFieldConfigAttributes.keySet()) {
241 String key = keyField;
242 String value = dynamicFieldConfigAttributes.get(key);
243 MatchType dynamicMatch = createDynamicMatch(key, value);
244 allOf.getMatch().add(dynamicMatch);
247 AnyOfType anyOf = new AnyOfType();
248 anyOf.getAllOf().add(allOfOne);
249 anyOf.getAllOf().add(allOf);
251 TargetType target = new TargetType();
252 ((TargetType) target).getAnyOf().add(anyOf);
254 // Adding the target to the policy element
255 configPolicy.setTarget((TargetType) target);
257 RuleType rule = new RuleType();
258 rule.setRuleId(policyAdapter.getRuleID());
259 rule.setEffect(EffectType.PERMIT);
261 // Create Target in Rule
262 AllOfType allOfInRule = new AllOfType();
264 // Creating match for ACCESS in rule target
265 MatchType accessMatch = new MatchType();
266 AttributeValueType accessAttributeValue = new AttributeValueType();
267 accessAttributeValue.setDataType(STRING_DATATYPE);
268 accessAttributeValue.getContent().add("ACCESS");
269 accessMatch.setAttributeValue(accessAttributeValue);
270 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
271 URI accessURI = null;
273 accessURI = new URI(ACTION_ID);
274 } catch (URISyntaxException e) {
275 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "ConfigPolicy", "Exception creating ACCESS URI");
277 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
278 accessAttributeDesignator.setDataType(STRING_DATATYPE);
279 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
280 accessMatch.setAttributeDesignator(accessAttributeDesignator);
281 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
283 // Creating Config Match in rule Target
284 MatchType configMatch = new MatchType();
285 AttributeValueType configAttributeValue = new AttributeValueType();
286 configAttributeValue.setDataType(STRING_DATATYPE);
287 configAttributeValue.getContent().add("Config");
288 configMatch.setAttributeValue(configAttributeValue);
289 AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
290 URI configURI = null;
292 configURI = new URI(RESOURCE_ID);
293 } catch (URISyntaxException e) {
294 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "ConfigPolicy", "Exception creating Config URI");
296 configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
297 configAttributeDesignator.setDataType(STRING_DATATYPE);
298 configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
299 configMatch.setAttributeDesignator(configAttributeDesignator);
300 configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
302 allOfInRule.getMatch().add(accessMatch);
303 allOfInRule.getMatch().add(configMatch);
305 AnyOfType anyOfInRule = new AnyOfType();
306 anyOfInRule.getAllOf().add(allOfInRule);
308 TargetType targetInRule = new TargetType();
309 targetInRule.getAnyOf().add(anyOfInRule);
311 rule.setTarget(targetInRule);
312 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
314 configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
315 policyAdapter.setPolicyData(configPolicy);
318 PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
320 setPreparedToSave(true);
324 // Data required for Advice part is setting here.
325 private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
326 AdviceExpressionsType advices = new AdviceExpressionsType();
327 AdviceExpressionType advice = new AdviceExpressionType();
328 advice.setAdviceId("configID");
329 advice.setAppliesTo(EffectType.PERMIT);
332 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
333 assignment1.setAttributeId("type");
334 assignment1.setCategory(CATEGORY_RESOURCE);
335 assignment1.setIssuer("");
337 AttributeValueType configNameAttributeValue = new AttributeValueType();
338 configNameAttributeValue.setDataType(STRING_DATATYPE);
339 configNameAttributeValue.getContent().add("Configuration");
340 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
342 advice.getAttributeAssignmentExpression().add(assignment1);
344 // For Config file Url if configurations are provided.
345 if (policyAdapter.getConfigType() != null) {
346 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
347 assignment2.setAttributeId("URLID");
348 assignment2.setCategory(CATEGORY_RESOURCE);
349 assignment2.setIssuer("");
351 AttributeValueType AttributeValue = new AttributeValueType();
352 AttributeValue.setDataType(URI_DATATYPE);
353 String content = "$URL" + "/Config/" + getConfigFile(policyName);
354 AttributeValue.getContent().add(content);
355 assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
357 advice.getAttributeAssignmentExpression().add(assignment2);
358 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
359 assignment3.setAttributeId("PolicyName");
360 assignment3.setCategory(CATEGORY_RESOURCE);
361 assignment3.setIssuer("");
363 AttributeValueType attributeValue3 = new AttributeValueType();
364 attributeValue3.setDataType(STRING_DATATYPE);
366 fileName = FilenameUtils.removeExtension(fileName);
367 fileName = fileName + ".xml";
368 String name = fileName.substring(fileName.lastIndexOf("\\") + 1);
369 if ((name == null) || (name.equals(""))) {
370 name = fileName.substring(fileName.lastIndexOf("/") + 1);
372 attributeValue3.getContent().add(name);
373 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
374 advice.getAttributeAssignmentExpression().add(assignment3);
376 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
377 assignment4.setAttributeId("VersionNumber");
378 assignment4.setCategory(CATEGORY_RESOURCE);
379 assignment4.setIssuer("");
381 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
382 configNameAttributeValue4.setDataType(STRING_DATATYPE);
383 configNameAttributeValue4.getContent().add(Integer.toString(version));
384 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
386 advice.getAttributeAssignmentExpression().add(assignment4);
388 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
389 assignment5.setAttributeId("matching:" + ONAPID);
390 assignment5.setCategory(CATEGORY_RESOURCE);
391 assignment5.setIssuer("");
393 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
394 configNameAttributeValue5.setDataType(STRING_DATATYPE);
395 configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
396 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
398 advice.getAttributeAssignmentExpression().add(assignment5);
400 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
401 assignment6.setAttributeId("matching:" + CONFIGID);
402 assignment6.setCategory(CATEGORY_RESOURCE);
403 assignment6.setIssuer("");
405 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
406 configNameAttributeValue6.setDataType(STRING_DATATYPE);
407 configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
408 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
410 advice.getAttributeAssignmentExpression().add(assignment6);
412 Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
413 for (String keyField : dynamicFieldConfigAttributes.keySet()) {
414 String key = keyField;
415 String value = dynamicFieldConfigAttributes.get(key);
416 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
417 assignment7.setAttributeId("matching:" + key);
418 assignment7.setCategory(CATEGORY_RESOURCE);
419 assignment7.setIssuer("");
421 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
422 configNameAttributeValue7.setDataType(STRING_DATATYPE);
423 configNameAttributeValue7.getContent().add(value);
424 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
426 advice.getAttributeAssignmentExpression().add(assignment7);
431 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
432 assignment8.setAttributeId("RiskType");
433 assignment8.setCategory(CATEGORY_RESOURCE);
434 assignment8.setIssuer("");
436 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
437 configNameAttributeValue8.setDataType(STRING_DATATYPE);
438 configNameAttributeValue8.getContent().add(policyAdapter.getRiskType());
439 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
441 advice.getAttributeAssignmentExpression().add(assignment8);
443 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
444 assignment9.setAttributeId("RiskLevel");
445 assignment9.setCategory(CATEGORY_RESOURCE);
446 assignment9.setIssuer("");
448 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
449 configNameAttributeValue9.setDataType(STRING_DATATYPE);
450 configNameAttributeValue9.getContent().add(policyAdapter.getRiskLevel());
451 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
453 advice.getAttributeAssignmentExpression().add(assignment9);
455 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
456 assignment10.setAttributeId("guard");
457 assignment10.setCategory(CATEGORY_RESOURCE);
458 assignment10.setIssuer("");
460 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
461 configNameAttributeValue10.setDataType(STRING_DATATYPE);
462 configNameAttributeValue10.getContent().add(policyAdapter.getGuard());
463 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
465 advice.getAttributeAssignmentExpression().add(assignment10);
467 AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
468 assignment11.setAttributeId("TTLDate");
469 assignment11.setCategory(CATEGORY_RESOURCE);
470 assignment11.setIssuer("");
472 AttributeValueType configNameAttributeValue11 = new AttributeValueType();
473 configNameAttributeValue11.setDataType(STRING_DATATYPE);
474 configNameAttributeValue11.getContent().add(policyAdapter.getTtlDate());
475 assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11));
477 advice.getAttributeAssignmentExpression().add(assignment11);
479 advices.getAdviceExpression().add(advice);
484 public Object getCorrectPolicyDataObject() {
485 return policyAdapter.getPolicyData();