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) {
84 String fileName = getConfigFile(policyName);
85 FileWriter fw = new FileWriter(CONFIG_HOME + File.separator + fileName);
86 BufferedWriter bw = new BufferedWriter(fw);
87 bw.write(configBodyData);
89 if (LOGGER.isDebugEnabled()) {
90 LOGGER.debug("Configuration is succesfully saved");
92 } catch (IOException e) {
93 LOGGER.error("Exception Occured while writing Configuration Data"+e);
98 // Here we are adding the extension for the configurations file based on the
99 // config type selection for saving.
100 private String getConfigFile(String filename) {
101 filename = FilenameUtils.removeExtension(filename);
102 if (filename.endsWith(".xml")) {
103 filename = filename.substring(0, filename.length() - 4);
105 String id = policyAdapter.getConfigType();
108 if (id.equalsIgnoreCase(JSON_CONFIG)) {
109 filename = filename + ".json";
111 if (id.equalsIgnoreCase(XML_CONFIG)) {
112 filename = filename + ".xml";
114 if (id.equalsIgnoreCase(PROPERTIES_CONFIG)) {
115 filename = filename + ".properties";
117 if (id.equalsIgnoreCase(OTHER_CONFIG)) {
118 filename = filename + ".txt";
125 // Validations for Config form
127 * FORM VALIDATION WILL BE DONE BY THE PAP-ADMIN before creating JSON object...
128 * BODY VALIDATION WILL BE DONE BY THE PAP-REST after receiving and deserializing the JSON object
130 public boolean validateConfigForm() {
135 * Validate Text Area Body
137 configBodyData = policyAdapter.getConfigBodyData();
138 String id = policyAdapter.getConfigType();
140 if (id.equals(JSON_CONFIG)) {
141 if (!PolicyUtils.isJSONValid(configBodyData)) {
144 } else if (id.equals(XML_CONFIG)) {
145 if (!PolicyUtils.isXMLValid(configBodyData)) {
148 } else if (id.equals(PROPERTIES_CONFIG)) {
149 if (!PolicyUtils.isPropValid(configBodyData)||configBodyData.equals("")) {
152 } else if (id.equals(OTHER_CONFIG)) {
153 if (configBodyData.equals("")) {
163 public Map<String, String> savePolicies() throws PAPException {
165 Map<String, String> successMap = new HashMap<>();
166 if(isPolicyExists()){
167 successMap.put("EXISTS", "This Policy already exist on the PAP");
171 if(!isPreparedToSave()){
172 //Prep and configure the policy for saving
176 // Until here we prepared the data and here calling the method to create xml.
177 Path newPolicyPath = null;
178 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
179 successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject());
183 //This is the method for preparing the policy for saving. We have broken it out
184 //separately because the fully configured policy is used for multiple things
186 public boolean prepareToSave() throws PAPException{
188 if(isPreparedToSave()){
193 String policyID = policyAdapter.getPolicyID();
194 version = policyAdapter.getHighestVersion();
196 // Create the Instance for pojo, PolicyType object is used in marshalling.
197 if (policyAdapter.getPolicyType().equals("Config")) {
198 PolicyType policyConfig = new PolicyType();
200 policyConfig.setVersion(Integer.toString(version));
201 policyConfig.setPolicyId(policyID);
202 policyConfig.setTarget(new TargetType());
203 policyAdapter.setData(policyConfig);
206 policyName = policyAdapter.getNewFileName();
207 configBodyData = policyAdapter.getConfigBodyData();
208 saveConfigurations(policyName);
210 if (policyAdapter.getData() != null) {
211 PolicyType configPolicy = (PolicyType) policyAdapter.getData();
213 configPolicy.setDescription(policyAdapter.getPolicyDescription());
215 configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
216 AllOfType allOfOne = new AllOfType();
218 String fileName = policyAdapter.getNewFileName();
219 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
220 if ((name == null) || (name.equals(""))) {
221 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
223 allOfOne.getMatch().add(createMatch("PolicyName", name));
224 AllOfType allOf = new AllOfType();
226 // Adding the matches to AllOfType element Match for Onap
227 allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
228 // Match for riskType
229 allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
230 // Match for riskLevel
231 allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
232 // Match for riskguard
233 allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
235 allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
236 // Match for ConfigName
237 allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
239 Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
241 // If there is any dynamic field create the matches here
242 for (String keyField : dynamicFieldConfigAttributes.keySet()) {
243 String key = keyField;
244 String value = dynamicFieldConfigAttributes.get(key);
245 MatchType dynamicMatch = createDynamicMatch(key, value);
246 allOf.getMatch().add(dynamicMatch);
249 AnyOfType anyOf = new AnyOfType();
250 anyOf.getAllOf().add(allOfOne);
251 anyOf.getAllOf().add(allOf);
253 TargetType target = new TargetType();
254 ((TargetType) target).getAnyOf().add(anyOf);
256 // Adding the target to the policy element
257 configPolicy.setTarget((TargetType) target);
259 RuleType rule = new RuleType();
260 rule.setRuleId(policyAdapter.getRuleID());
261 rule.setEffect(EffectType.PERMIT);
263 // Create Target in Rule
264 AllOfType allOfInRule = new AllOfType();
266 // Creating match for ACCESS in rule target
267 MatchType accessMatch = new MatchType();
268 AttributeValueType accessAttributeValue = new AttributeValueType();
269 accessAttributeValue.setDataType(STRING_DATATYPE);
270 accessAttributeValue.getContent().add("ACCESS");
271 accessMatch.setAttributeValue(accessAttributeValue);
272 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
273 URI accessURI = null;
275 accessURI = new URI(ACTION_ID);
276 }catch(URISyntaxException e){
277 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "ConfigPolicy", "Exception creating ACCESS URI");
279 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
280 accessAttributeDesignator.setDataType(STRING_DATATYPE);
281 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
282 accessMatch.setAttributeDesignator(accessAttributeDesignator);
283 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
285 // Creating Config Match in rule Target
286 MatchType configMatch = new MatchType();
287 AttributeValueType configAttributeValue = new AttributeValueType();
288 configAttributeValue.setDataType(STRING_DATATYPE);
289 configAttributeValue.getContent().add("Config");
290 configMatch.setAttributeValue(configAttributeValue);
291 AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
292 URI configURI = null;
294 configURI = new URI(RESOURCE_ID);
295 }catch(URISyntaxException e){
296 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "ConfigPolicy", "Exception creating Config URI");
298 configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
299 configAttributeDesignator.setDataType(STRING_DATATYPE);
300 configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
301 configMatch.setAttributeDesignator(configAttributeDesignator);
302 configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
304 allOfInRule.getMatch().add(accessMatch);
305 allOfInRule.getMatch().add(configMatch);
307 AnyOfType anyOfInRule = new AnyOfType();
308 anyOfInRule.getAllOf().add(allOfInRule);
310 TargetType targetInRule = new TargetType();
311 targetInRule.getAnyOf().add(anyOfInRule);
313 rule.setTarget(targetInRule);
314 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
316 configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
317 policyAdapter.setPolicyData(configPolicy);
320 PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
322 setPreparedToSave(true);
326 // Data required for Advice part is setting here.
327 private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
328 AdviceExpressionsType advices = new AdviceExpressionsType();
329 AdviceExpressionType advice = new AdviceExpressionType();
330 advice.setAdviceId("configID");
331 advice.setAppliesTo(EffectType.PERMIT);
334 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
335 assignment1.setAttributeId("type");
336 assignment1.setCategory(CATEGORY_RESOURCE);
337 assignment1.setIssuer("");
339 AttributeValueType configNameAttributeValue = new AttributeValueType();
340 configNameAttributeValue.setDataType(STRING_DATATYPE);
341 configNameAttributeValue.getContent().add("Configuration");
342 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
344 advice.getAttributeAssignmentExpression().add(assignment1);
346 // For Config file Url if configurations are provided.
347 if (policyAdapter.getConfigType() != null) {
348 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
349 assignment2.setAttributeId("URLID");
350 assignment2.setCategory(CATEGORY_RESOURCE);
351 assignment2.setIssuer("");
353 AttributeValueType AttributeValue = new AttributeValueType();
354 AttributeValue.setDataType(URI_DATATYPE);
355 String content = "$URL" + "/Config/" + getConfigFile(policyName);
356 AttributeValue.getContent().add(content);
357 assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
359 advice.getAttributeAssignmentExpression().add(assignment2);
360 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
361 assignment3.setAttributeId("PolicyName");
362 assignment3.setCategory(CATEGORY_RESOURCE);
363 assignment3.setIssuer("");
365 AttributeValueType attributeValue3 = new AttributeValueType();
366 attributeValue3.setDataType(STRING_DATATYPE);
368 fileName = FilenameUtils.removeExtension(fileName);
369 fileName = fileName + ".xml";
370 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
371 if ((name == null) || (name.equals(""))) {
372 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
374 attributeValue3.getContent().add(name);
375 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
376 advice.getAttributeAssignmentExpression().add(assignment3);
378 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
379 assignment4.setAttributeId("VersionNumber");
380 assignment4.setCategory(CATEGORY_RESOURCE);
381 assignment4.setIssuer("");
383 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
384 configNameAttributeValue4.setDataType(STRING_DATATYPE);
385 configNameAttributeValue4.getContent().add(Integer.toString(version));
386 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
388 advice.getAttributeAssignmentExpression().add(assignment4);
390 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
391 assignment5.setAttributeId("matching:" + ONAPID);
392 assignment5.setCategory(CATEGORY_RESOURCE);
393 assignment5.setIssuer("");
395 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
396 configNameAttributeValue5.setDataType(STRING_DATATYPE);
397 configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
398 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
400 advice.getAttributeAssignmentExpression().add(assignment5);
402 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
403 assignment6.setAttributeId("matching:" + CONFIGID);
404 assignment6.setCategory(CATEGORY_RESOURCE);
405 assignment6.setIssuer("");
407 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
408 configNameAttributeValue6.setDataType(STRING_DATATYPE);
409 configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
410 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
412 advice.getAttributeAssignmentExpression().add(assignment6);
414 Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
415 for (String keyField : dynamicFieldConfigAttributes.keySet()) {
416 String key = keyField;
417 String value = dynamicFieldConfigAttributes.get(key);
418 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
419 assignment7.setAttributeId("matching:" + key);
420 assignment7.setCategory(CATEGORY_RESOURCE);
421 assignment7.setIssuer("");
423 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
424 configNameAttributeValue7.setDataType(STRING_DATATYPE);
425 configNameAttributeValue7.getContent().add(value);
426 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
428 advice.getAttributeAssignmentExpression().add(assignment7);
433 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
434 assignment8.setAttributeId("RiskType");
435 assignment8.setCategory(CATEGORY_RESOURCE);
436 assignment8.setIssuer("");
438 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
439 configNameAttributeValue8.setDataType(STRING_DATATYPE);
440 configNameAttributeValue8.getContent().add(policyAdapter.getRiskType());
441 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
443 advice.getAttributeAssignmentExpression().add(assignment8);
445 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
446 assignment9.setAttributeId("RiskLevel");
447 assignment9.setCategory(CATEGORY_RESOURCE);
448 assignment9.setIssuer("");
450 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
451 configNameAttributeValue9.setDataType(STRING_DATATYPE);
452 configNameAttributeValue9.getContent().add(policyAdapter.getRiskLevel());
453 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
455 advice.getAttributeAssignmentExpression().add(assignment9);
457 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
458 assignment10.setAttributeId("guard");
459 assignment10.setCategory(CATEGORY_RESOURCE);
460 assignment10.setIssuer("");
462 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
463 configNameAttributeValue10.setDataType(STRING_DATATYPE);
464 configNameAttributeValue10.getContent().add(policyAdapter.getGuard());
465 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
467 advice.getAttributeAssignmentExpression().add(assignment10);
469 AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
470 assignment11.setAttributeId("TTLDate");
471 assignment11.setCategory(CATEGORY_RESOURCE);
472 assignment11.setIssuer("");
474 AttributeValueType configNameAttributeValue11 = new AttributeValueType();
475 configNameAttributeValue11.setDataType(STRING_DATATYPE);
476 configNameAttributeValue11.getContent().add(policyAdapter.getTtlDate());
477 assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11));
479 advice.getAttributeAssignmentExpression().add(assignment11);
481 advices.getAdviceExpression().add(advice);
486 public Object getCorrectPolicyDataObject() {
487 return policyAdapter.getPolicyData();