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;
23 import java.io.BufferedWriter;
25 import java.io.FileWriter;
26 import java.io.IOException;
28 import java.net.URISyntaxException;
29 import java.nio.file.Path;
30 import java.nio.file.Paths;
31 import java.util.HashMap;
34 import org.apache.commons.io.FilenameUtils;
35 import org.onap.policy.common.logging.eelf.MessageCodes;
36 import org.onap.policy.common.logging.eelf.PolicyLogger;
37 import org.onap.policy.common.logging.flexlogger.FlexLogger;
38 import org.onap.policy.common.logging.flexlogger.Logger;
39 import org.onap.policy.rest.adapter.PolicyRestAdapter;
40 import org.onap.policy.utils.PolicyUtils;
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 ConfigPolicy extends Policy {
64 private static final Logger LOGGER = FlexLogger.getLogger(ConfigPolicy.class);
66 public static final String JSON_CONFIG = "JSON";
67 public static final String XML_CONFIG = "XML";
68 public static final String PROPERTIES_CONFIG = "PROPERTIES";
69 public static final String OTHER_CONFIG = "OTHER";
71 private String configBodyData;
73 public ConfigPolicy() {
77 public ConfigPolicy(PolicyRestAdapter policyAdapter){
78 this.policyAdapter = policyAdapter;
81 // Saving the Configurations file at server location for config policy.
82 protected void saveConfigurations(String policyName) {
83 BufferedWriter bw = null;
85 String fileName = getConfigFile(policyName);
86 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 } catch (Exception e) {
98 LOGGER.error("Exception Occured while closing the BufferedWriter"+e);
105 // Here we are adding the extension for the configurations file based on the
106 // config type selection for saving.
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 String id = policyAdapter.getConfigType();
115 if (id.equalsIgnoreCase(JSON_CONFIG)) {
116 filename = filename + ".json";
118 if (id.equalsIgnoreCase(XML_CONFIG)) {
119 filename = filename + ".xml";
121 if (id.equalsIgnoreCase(PROPERTIES_CONFIG)) {
122 filename = filename + ".properties";
124 if (id.equalsIgnoreCase(OTHER_CONFIG)) {
125 filename = filename + ".txt";
132 // Validations for Config form
134 * FORM VALIDATION WILL BE DONE BY THE PAP-ADMIN before creating JSON object...
135 * BODY VALIDATION WILL BE DONE BY THE PAP-REST after receiving and deserializing the JSON object
137 public boolean validateConfigForm() {
142 * Validate Text Area Body
144 configBodyData = policyAdapter.getConfigBodyData();
145 String id = policyAdapter.getConfigType();
147 if (id.equals(JSON_CONFIG)) {
148 if (!PolicyUtils.isJSONValid(configBodyData)) {
151 } else if (id.equals(XML_CONFIG)) {
152 if (!PolicyUtils.isXMLValid(configBodyData)) {
155 } else if (id.equals(PROPERTIES_CONFIG)) {
156 if (!PolicyUtils.isPropValid(configBodyData)||configBodyData.equals("")) {
159 } else if (id.equals(OTHER_CONFIG)) {
160 if (configBodyData.equals("")) {
170 public Map<String, String> savePolicies() throws PAPException {
172 Map<String, String> successMap = new HashMap<>();
173 if(isPolicyExists()){
174 successMap.put("EXISTS", "This Policy already exist on the PAP");
178 if(!isPreparedToSave()){
179 //Prep and configure the policy for saving
183 // Until here we prepared the data and here calling the method to create xml.
184 Path newPolicyPath = null;
185 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
186 successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject());
190 //This is the method for preparing the policy for saving. We have broken it out
191 //separately because the fully configured policy is used for multiple things
193 public boolean prepareToSave() throws PAPException{
195 if(isPreparedToSave()){
200 String policyID = policyAdapter.getPolicyID();
201 version = policyAdapter.getHighestVersion();
203 // Create the Instance for pojo, PolicyType object is used in marshalling.
204 if (policyAdapter.getPolicyType().equals("Config")) {
205 PolicyType policyConfig = new PolicyType();
207 policyConfig.setVersion(Integer.toString(version));
208 policyConfig.setPolicyId(policyID);
209 policyConfig.setTarget(new TargetType());
210 policyAdapter.setData(policyConfig);
213 policyName = policyAdapter.getNewFileName();
214 configBodyData = policyAdapter.getConfigBodyData();
215 saveConfigurations(policyName);
217 if (policyAdapter.getData() != null) {
218 PolicyType configPolicy = (PolicyType) policyAdapter.getData();
220 configPolicy.setDescription(policyAdapter.getPolicyDescription());
222 configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
223 AllOfType allOfOne = new AllOfType();
225 String fileName = policyAdapter.getNewFileName();
226 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
227 if ((name == null) || (name.equals(""))) {
228 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
230 allOfOne.getMatch().add(createMatch("PolicyName", name));
231 AllOfType allOf = new AllOfType();
233 // Adding the matches to AllOfType element Match for Onap
234 allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
235 // Match for riskType
236 allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
237 // Match for riskLevel
238 allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
239 // Match for riskguard
240 allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
242 allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
243 // Match for ConfigName
244 allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
246 Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
248 // If there is any dynamic field create the matches here
249 for (String keyField : dynamicFieldConfigAttributes.keySet()) {
250 String key = keyField;
251 String value = dynamicFieldConfigAttributes.get(key);
252 MatchType dynamicMatch = createDynamicMatch(key, value);
253 allOf.getMatch().add(dynamicMatch);
256 AnyOfType anyOf = new AnyOfType();
257 anyOf.getAllOf().add(allOfOne);
258 anyOf.getAllOf().add(allOf);
260 TargetType target = new TargetType();
261 ((TargetType) target).getAnyOf().add(anyOf);
263 // Adding the target to the policy element
264 configPolicy.setTarget((TargetType) target);
266 RuleType rule = new RuleType();
267 rule.setRuleId(policyAdapter.getRuleID());
268 rule.setEffect(EffectType.PERMIT);
270 // Create Target in Rule
271 AllOfType allOfInRule = new AllOfType();
273 // Creating match for ACCESS in rule target
274 MatchType accessMatch = new MatchType();
275 AttributeValueType accessAttributeValue = new AttributeValueType();
276 accessAttributeValue.setDataType(STRING_DATATYPE);
277 accessAttributeValue.getContent().add("ACCESS");
278 accessMatch.setAttributeValue(accessAttributeValue);
279 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
280 URI accessURI = null;
282 accessURI = new URI(ACTION_ID);
283 }catch(URISyntaxException e){
284 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "ConfigPolicy", "Exception creating ACCESS URI");
286 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
287 accessAttributeDesignator.setDataType(STRING_DATATYPE);
288 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
289 accessMatch.setAttributeDesignator(accessAttributeDesignator);
290 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
292 // Creating Config Match in rule Target
293 MatchType configMatch = new MatchType();
294 AttributeValueType configAttributeValue = new AttributeValueType();
295 configAttributeValue.setDataType(STRING_DATATYPE);
296 configAttributeValue.getContent().add("Config");
297 configMatch.setAttributeValue(configAttributeValue);
298 AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
299 URI configURI = null;
301 configURI = new URI(RESOURCE_ID);
302 }catch(URISyntaxException e){
303 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "ConfigPolicy", "Exception creating Config URI");
305 configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
306 configAttributeDesignator.setDataType(STRING_DATATYPE);
307 configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
308 configMatch.setAttributeDesignator(configAttributeDesignator);
309 configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
311 allOfInRule.getMatch().add(accessMatch);
312 allOfInRule.getMatch().add(configMatch);
314 AnyOfType anyOfInRule = new AnyOfType();
315 anyOfInRule.getAllOf().add(allOfInRule);
317 TargetType targetInRule = new TargetType();
318 targetInRule.getAnyOf().add(anyOfInRule);
320 rule.setTarget(targetInRule);
321 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
323 configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
324 policyAdapter.setPolicyData(configPolicy);
327 PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
329 setPreparedToSave(true);
333 // Data required for Advice part is setting here.
334 private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
335 AdviceExpressionsType advices = new AdviceExpressionsType();
336 AdviceExpressionType advice = new AdviceExpressionType();
337 advice.setAdviceId("configID");
338 advice.setAppliesTo(EffectType.PERMIT);
341 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
342 assignment1.setAttributeId("type");
343 assignment1.setCategory(CATEGORY_RESOURCE);
344 assignment1.setIssuer("");
346 AttributeValueType configNameAttributeValue = new AttributeValueType();
347 configNameAttributeValue.setDataType(STRING_DATATYPE);
348 configNameAttributeValue.getContent().add("Configuration");
349 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
351 advice.getAttributeAssignmentExpression().add(assignment1);
353 // For Config file Url if configurations are provided.
354 if (policyAdapter.getConfigType() != null) {
355 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
356 assignment2.setAttributeId("URLID");
357 assignment2.setCategory(CATEGORY_RESOURCE);
358 assignment2.setIssuer("");
360 AttributeValueType AttributeValue = new AttributeValueType();
361 AttributeValue.setDataType(URI_DATATYPE);
362 String content = "$URL" + "/Config/" + getConfigFile(policyName);
363 AttributeValue.getContent().add(content);
364 assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
366 advice.getAttributeAssignmentExpression().add(assignment2);
367 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
368 assignment3.setAttributeId("PolicyName");
369 assignment3.setCategory(CATEGORY_RESOURCE);
370 assignment3.setIssuer("");
372 AttributeValueType attributeValue3 = new AttributeValueType();
373 attributeValue3.setDataType(STRING_DATATYPE);
375 fileName = FilenameUtils.removeExtension(fileName);
376 fileName = fileName + ".xml";
377 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
378 if ((name == null) || (name.equals(""))) {
379 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
381 attributeValue3.getContent().add(name);
382 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
383 advice.getAttributeAssignmentExpression().add(assignment3);
385 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
386 assignment4.setAttributeId("VersionNumber");
387 assignment4.setCategory(CATEGORY_RESOURCE);
388 assignment4.setIssuer("");
390 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
391 configNameAttributeValue4.setDataType(STRING_DATATYPE);
392 configNameAttributeValue4.getContent().add(Integer.toString(version));
393 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
395 advice.getAttributeAssignmentExpression().add(assignment4);
397 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
398 assignment5.setAttributeId("matching:" + ONAPID);
399 assignment5.setCategory(CATEGORY_RESOURCE);
400 assignment5.setIssuer("");
402 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
403 configNameAttributeValue5.setDataType(STRING_DATATYPE);
404 configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
405 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
407 advice.getAttributeAssignmentExpression().add(assignment5);
409 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
410 assignment6.setAttributeId("matching:" + CONFIGID);
411 assignment6.setCategory(CATEGORY_RESOURCE);
412 assignment6.setIssuer("");
414 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
415 configNameAttributeValue6.setDataType(STRING_DATATYPE);
416 configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
417 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
419 advice.getAttributeAssignmentExpression().add(assignment6);
421 Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
422 for (String keyField : dynamicFieldConfigAttributes.keySet()) {
423 String key = keyField;
424 String value = dynamicFieldConfigAttributes.get(key);
425 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
426 assignment7.setAttributeId("matching:" + key);
427 assignment7.setCategory(CATEGORY_RESOURCE);
428 assignment7.setIssuer("");
430 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
431 configNameAttributeValue7.setDataType(STRING_DATATYPE);
432 configNameAttributeValue7.getContent().add(value);
433 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
435 advice.getAttributeAssignmentExpression().add(assignment7);
440 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
441 assignment8.setAttributeId("RiskType");
442 assignment8.setCategory(CATEGORY_RESOURCE);
443 assignment8.setIssuer("");
445 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
446 configNameAttributeValue8.setDataType(STRING_DATATYPE);
447 configNameAttributeValue8.getContent().add(policyAdapter.getRiskType());
448 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
450 advice.getAttributeAssignmentExpression().add(assignment8);
452 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
453 assignment9.setAttributeId("RiskLevel");
454 assignment9.setCategory(CATEGORY_RESOURCE);
455 assignment9.setIssuer("");
457 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
458 configNameAttributeValue9.setDataType(STRING_DATATYPE);
459 configNameAttributeValue9.getContent().add(policyAdapter.getRiskLevel());
460 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
462 advice.getAttributeAssignmentExpression().add(assignment9);
464 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
465 assignment10.setAttributeId("guard");
466 assignment10.setCategory(CATEGORY_RESOURCE);
467 assignment10.setIssuer("");
469 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
470 configNameAttributeValue10.setDataType(STRING_DATATYPE);
471 configNameAttributeValue10.getContent().add(policyAdapter.getGuard());
472 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
474 advice.getAttributeAssignmentExpression().add(assignment10);
476 AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
477 assignment11.setAttributeId("TTLDate");
478 assignment11.setCategory(CATEGORY_RESOURCE);
479 assignment11.setIssuer("");
481 AttributeValueType configNameAttributeValue11 = new AttributeValueType();
482 configNameAttributeValue11.setDataType(STRING_DATATYPE);
483 configNameAttributeValue11.getContent().add(policyAdapter.getTtlDate());
484 assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11));
486 advice.getAttributeAssignmentExpression().add(assignment11);
488 advices.getAdviceExpression().add(advice);
493 public Object getCorrectPolicyDataObject() {
494 return policyAdapter.getPolicyData();