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 String fileName = getConfigFile(policyName);
84 try(BufferedWriter bw = new BufferedWriter(new FileWriter(CONFIG_HOME + File.separator + fileName))) {
85 bw.write(configBodyData);
86 if (LOGGER.isDebugEnabled()) {
87 LOGGER.debug("Configuration is succesfully saved");
89 } catch (IOException e) {
90 LOGGER.error("Exception Occured while writing Configuration Data"+e);
95 // Here we are adding the extension for the configurations file based on the
96 // config type selection for saving.
97 private String getConfigFile(String filename) {
98 filename = FilenameUtils.removeExtension(filename);
99 if (filename.endsWith(".xml")) {
100 filename = filename.substring(0, filename.length() - 4);
102 String id = policyAdapter.getConfigType();
105 if (id.equalsIgnoreCase(JSON_CONFIG)) {
106 filename = filename + ".json";
108 if (id.equalsIgnoreCase(XML_CONFIG)) {
109 filename = filename + ".xml";
111 if (id.equalsIgnoreCase(PROPERTIES_CONFIG)) {
112 filename = filename + ".properties";
114 if (id.equalsIgnoreCase(OTHER_CONFIG)) {
115 filename = filename + ".txt";
122 // Validations for Config form
124 * FORM VALIDATION WILL BE DONE BY THE PAP-ADMIN before creating JSON object...
125 * BODY VALIDATION WILL BE DONE BY THE PAP-REST after receiving and deserializing the JSON object
127 public boolean validateConfigForm() {
132 * Validate Text Area Body
134 configBodyData = policyAdapter.getConfigBodyData();
135 String id = policyAdapter.getConfigType();
137 if (id.equals(JSON_CONFIG)) {
138 if (!PolicyUtils.isJSONValid(configBodyData)) {
141 } else if (id.equals(XML_CONFIG)) {
142 if (!PolicyUtils.isXMLValid(configBodyData)) {
145 } else if (id.equals(PROPERTIES_CONFIG)) {
146 if (!PolicyUtils.isPropValid(configBodyData)||configBodyData.equals("")) {
149 } else if (id.equals(OTHER_CONFIG)) {
150 if (configBodyData.equals("")) {
160 public Map<String, String> savePolicies() throws PAPException {
162 Map<String, String> successMap = new HashMap<>();
163 if(isPolicyExists()){
164 successMap.put("EXISTS", "This Policy already exist on the PAP");
168 if(!isPreparedToSave()){
169 //Prep and configure the policy for saving
173 // Until here we prepared the data and here calling the method to create xml.
174 Path newPolicyPath = null;
175 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
176 successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject());
180 //This is the method for preparing the policy for saving. We have broken it out
181 //separately because the fully configured policy is used for multiple things
183 public boolean prepareToSave() throws PAPException{
185 if(isPreparedToSave()){
190 String policyID = policyAdapter.getPolicyID();
191 version = policyAdapter.getHighestVersion();
193 // Create the Instance for pojo, PolicyType object is used in marshalling.
194 if (policyAdapter.getPolicyType().equals("Config")) {
195 PolicyType policyConfig = new PolicyType();
197 policyConfig.setVersion(Integer.toString(version));
198 policyConfig.setPolicyId(policyID);
199 policyConfig.setTarget(new TargetType());
200 policyAdapter.setData(policyConfig);
203 policyName = policyAdapter.getNewFileName();
204 configBodyData = policyAdapter.getConfigBodyData();
205 saveConfigurations(policyName);
207 if (policyAdapter.getData() != null) {
208 PolicyType configPolicy = (PolicyType) policyAdapter.getData();
210 configPolicy.setDescription(policyAdapter.getPolicyDescription());
212 configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
213 AllOfType allOfOne = new AllOfType();
215 String fileName = policyAdapter.getNewFileName();
216 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
217 if ((name == null) || (name.equals(""))) {
218 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
220 allOfOne.getMatch().add(createMatch("PolicyName", name));
221 AllOfType allOf = new AllOfType();
223 // Adding the matches to AllOfType element Match for Onap
224 allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
225 // Match for riskType
226 allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
227 // Match for riskLevel
228 allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
229 // Match for riskguard
230 allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
232 allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
233 // Match for ConfigName
234 allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
236 Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
238 // If there is any dynamic field create the matches here
239 for (String keyField : dynamicFieldConfigAttributes.keySet()) {
240 String key = keyField;
241 String value = dynamicFieldConfigAttributes.get(key);
242 MatchType dynamicMatch = createDynamicMatch(key, value);
243 allOf.getMatch().add(dynamicMatch);
246 AnyOfType anyOf = new AnyOfType();
247 anyOf.getAllOf().add(allOfOne);
248 anyOf.getAllOf().add(allOf);
250 TargetType target = new TargetType();
251 ((TargetType) target).getAnyOf().add(anyOf);
253 // Adding the target to the policy element
254 configPolicy.setTarget((TargetType) target);
256 RuleType rule = new RuleType();
257 rule.setRuleId(policyAdapter.getRuleID());
258 rule.setEffect(EffectType.PERMIT);
260 // Create Target in Rule
261 AllOfType allOfInRule = new AllOfType();
263 // Creating match for ACCESS in rule target
264 MatchType accessMatch = new MatchType();
265 AttributeValueType accessAttributeValue = new AttributeValueType();
266 accessAttributeValue.setDataType(STRING_DATATYPE);
267 accessAttributeValue.getContent().add("ACCESS");
268 accessMatch.setAttributeValue(accessAttributeValue);
269 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
270 URI accessURI = null;
272 accessURI = new URI(ACTION_ID);
273 }catch(URISyntaxException e){
274 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "ConfigPolicy", "Exception creating ACCESS URI");
276 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
277 accessAttributeDesignator.setDataType(STRING_DATATYPE);
278 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
279 accessMatch.setAttributeDesignator(accessAttributeDesignator);
280 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
282 // Creating Config Match in rule Target
283 MatchType configMatch = new MatchType();
284 AttributeValueType configAttributeValue = new AttributeValueType();
285 configAttributeValue.setDataType(STRING_DATATYPE);
286 configAttributeValue.getContent().add("Config");
287 configMatch.setAttributeValue(configAttributeValue);
288 AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
289 URI configURI = null;
291 configURI = new URI(RESOURCE_ID);
292 }catch(URISyntaxException e){
293 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "ConfigPolicy", "Exception creating Config URI");
295 configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
296 configAttributeDesignator.setDataType(STRING_DATATYPE);
297 configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
298 configMatch.setAttributeDesignator(configAttributeDesignator);
299 configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
301 allOfInRule.getMatch().add(accessMatch);
302 allOfInRule.getMatch().add(configMatch);
304 AnyOfType anyOfInRule = new AnyOfType();
305 anyOfInRule.getAllOf().add(allOfInRule);
307 TargetType targetInRule = new TargetType();
308 targetInRule.getAnyOf().add(anyOfInRule);
310 rule.setTarget(targetInRule);
311 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
313 configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
314 policyAdapter.setPolicyData(configPolicy);
317 PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
319 setPreparedToSave(true);
323 // Data required for Advice part is setting here.
324 private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
325 AdviceExpressionsType advices = new AdviceExpressionsType();
326 AdviceExpressionType advice = new AdviceExpressionType();
327 advice.setAdviceId("configID");
328 advice.setAppliesTo(EffectType.PERMIT);
331 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
332 assignment1.setAttributeId("type");
333 assignment1.setCategory(CATEGORY_RESOURCE);
334 assignment1.setIssuer("");
336 AttributeValueType configNameAttributeValue = new AttributeValueType();
337 configNameAttributeValue.setDataType(STRING_DATATYPE);
338 configNameAttributeValue.getContent().add("Configuration");
339 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
341 advice.getAttributeAssignmentExpression().add(assignment1);
343 // For Config file Url if configurations are provided.
344 if (policyAdapter.getConfigType() != null) {
345 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
346 assignment2.setAttributeId("URLID");
347 assignment2.setCategory(CATEGORY_RESOURCE);
348 assignment2.setIssuer("");
350 AttributeValueType AttributeValue = new AttributeValueType();
351 AttributeValue.setDataType(URI_DATATYPE);
352 String content = "$URL" + "/Config/" + getConfigFile(policyName);
353 AttributeValue.getContent().add(content);
354 assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
356 advice.getAttributeAssignmentExpression().add(assignment2);
357 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
358 assignment3.setAttributeId("PolicyName");
359 assignment3.setCategory(CATEGORY_RESOURCE);
360 assignment3.setIssuer("");
362 AttributeValueType attributeValue3 = new AttributeValueType();
363 attributeValue3.setDataType(STRING_DATATYPE);
365 fileName = FilenameUtils.removeExtension(fileName);
366 fileName = fileName + ".xml";
367 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
368 if ((name == null) || (name.equals(""))) {
369 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
371 attributeValue3.getContent().add(name);
372 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
373 advice.getAttributeAssignmentExpression().add(assignment3);
375 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
376 assignment4.setAttributeId("VersionNumber");
377 assignment4.setCategory(CATEGORY_RESOURCE);
378 assignment4.setIssuer("");
380 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
381 configNameAttributeValue4.setDataType(STRING_DATATYPE);
382 configNameAttributeValue4.getContent().add(Integer.toString(version));
383 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
385 advice.getAttributeAssignmentExpression().add(assignment4);
387 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
388 assignment5.setAttributeId("matching:" + ONAPID);
389 assignment5.setCategory(CATEGORY_RESOURCE);
390 assignment5.setIssuer("");
392 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
393 configNameAttributeValue5.setDataType(STRING_DATATYPE);
394 configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
395 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
397 advice.getAttributeAssignmentExpression().add(assignment5);
399 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
400 assignment6.setAttributeId("matching:" + CONFIGID);
401 assignment6.setCategory(CATEGORY_RESOURCE);
402 assignment6.setIssuer("");
404 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
405 configNameAttributeValue6.setDataType(STRING_DATATYPE);
406 configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
407 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
409 advice.getAttributeAssignmentExpression().add(assignment6);
411 Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
412 for (String keyField : dynamicFieldConfigAttributes.keySet()) {
413 String key = keyField;
414 String value = dynamicFieldConfigAttributes.get(key);
415 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
416 assignment7.setAttributeId("matching:" + key);
417 assignment7.setCategory(CATEGORY_RESOURCE);
418 assignment7.setIssuer("");
420 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
421 configNameAttributeValue7.setDataType(STRING_DATATYPE);
422 configNameAttributeValue7.getContent().add(value);
423 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
425 advice.getAttributeAssignmentExpression().add(assignment7);
430 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
431 assignment8.setAttributeId("RiskType");
432 assignment8.setCategory(CATEGORY_RESOURCE);
433 assignment8.setIssuer("");
435 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
436 configNameAttributeValue8.setDataType(STRING_DATATYPE);
437 configNameAttributeValue8.getContent().add(policyAdapter.getRiskType());
438 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
440 advice.getAttributeAssignmentExpression().add(assignment8);
442 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
443 assignment9.setAttributeId("RiskLevel");
444 assignment9.setCategory(CATEGORY_RESOURCE);
445 assignment9.setIssuer("");
447 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
448 configNameAttributeValue9.setDataType(STRING_DATATYPE);
449 configNameAttributeValue9.getContent().add(policyAdapter.getRiskLevel());
450 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
452 advice.getAttributeAssignmentExpression().add(assignment9);
454 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
455 assignment10.setAttributeId("guard");
456 assignment10.setCategory(CATEGORY_RESOURCE);
457 assignment10.setIssuer("");
459 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
460 configNameAttributeValue10.setDataType(STRING_DATATYPE);
461 configNameAttributeValue10.getContent().add(policyAdapter.getGuard());
462 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
464 advice.getAttributeAssignmentExpression().add(assignment10);
466 AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
467 assignment11.setAttributeId("TTLDate");
468 assignment11.setCategory(CATEGORY_RESOURCE);
469 assignment11.setIssuer("");
471 AttributeValueType configNameAttributeValue11 = new AttributeValueType();
472 configNameAttributeValue11.setDataType(STRING_DATATYPE);
473 configNameAttributeValue11.getContent().add(policyAdapter.getTtlDate());
474 assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11));
476 advice.getAttributeAssignmentExpression().add(assignment11);
478 advices.getAdviceExpression().add(advice);
483 public Object getCorrectPolicyDataObject() {
484 return policyAdapter.getPolicyData();