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;
27 import java.io.StringReader;
29 import java.net.URISyntaxException;
30 import java.nio.file.Path;
31 import java.nio.file.Paths;
32 import java.util.HashMap;
34 import java.util.Scanner;
36 import javax.xml.parsers.ParserConfigurationException;
37 import javax.xml.parsers.SAXParser;
38 import javax.xml.parsers.SAXParserFactory;
40 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
41 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
42 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
43 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
44 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
51 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
52 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
54 import org.apache.commons.io.FilenameUtils;
55 import org.onap.policy.common.logging.eelf.MessageCodes;
56 import org.onap.policy.common.logging.eelf.PolicyLogger;
57 import org.onap.policy.common.logging.flexlogger.FlexLogger;
58 import org.onap.policy.common.logging.flexlogger.Logger;
59 import org.onap.policy.rest.adapter.PolicyRestAdapter;
60 import org.xml.sax.ErrorHandler;
61 import org.xml.sax.InputSource;
62 import org.xml.sax.SAXException;
63 import org.xml.sax.SAXParseException;
64 import org.xml.sax.XMLReader;
66 import com.att.research.xacml.std.IdentifierImpl;
68 public class ConfigPolicy extends Policy {
73 private static final Logger LOGGER = FlexLogger.getLogger(ConfigPolicy.class);
75 public static final String JSON_CONFIG = "JSON";
76 public static final String XML_CONFIG = "XML";
77 public static final String PROPERTIES_CONFIG = "PROPERTIES";
78 public static final String OTHER_CONFIG = "OTHER";
80 private String configBodyData;
82 public ConfigPolicy() {
86 public ConfigPolicy(PolicyRestAdapter policyAdapter){
87 this.policyAdapter = policyAdapter;
90 // Saving the Configurations file at server location for config policy.
91 protected void saveConfigurations(String policyName) {
93 String fileName = getConfigFile(policyName);
94 FileWriter fw = new FileWriter(CONFIG_HOME + File.separator + fileName);
95 BufferedWriter bw = new BufferedWriter(fw);
96 bw.write(configBodyData);
98 if (LOGGER.isDebugEnabled()) {
99 LOGGER.debug("Configuration is succesfully saved");
101 } catch (IOException e) {
102 LOGGER.error("Exception Occured while writing Configuration Data"+e);
107 // Here we are adding the extension for the configurations file based on the
108 // config type selection for saving.
109 private String getConfigFile(String filename) {
110 filename = FilenameUtils.removeExtension(filename);
111 if (filename.endsWith(".xml")) {
112 filename = filename.substring(0, filename.length() - 4);
114 String id = policyAdapter.getConfigType();
117 if (id.equalsIgnoreCase(JSON_CONFIG)) {
118 filename = filename + ".json";
120 if (id.equalsIgnoreCase(XML_CONFIG)) {
121 filename = filename + ".xml";
123 if (id.equalsIgnoreCase(PROPERTIES_CONFIG)) {
124 filename = filename + ".properties";
126 if (id.equalsIgnoreCase(OTHER_CONFIG)) {
127 filename = filename + ".txt";
134 // Validations for Config form
136 * FORM VALIDATION WILL BE DONE BY THE PAP-ADMIN before creating JSON object...
137 * BODY VALIDATION WILL BE DONE BY THE PAP-REST after receiving and deserializing the JSON object
139 public boolean validateConfigForm() {
144 * Validate Text Area Body
146 configBodyData = policyAdapter.getConfigBodyData();
147 String id = policyAdapter.getConfigType();
149 if (id.equals(JSON_CONFIG)) {
150 if (!isJSONValid(configBodyData)) {
153 } else if (id.equals(XML_CONFIG)) {
154 if (!isXMLValid(configBodyData)) {
157 } else if (id.equals(PROPERTIES_CONFIG)) {
158 if (!isPropValid(configBodyData)||configBodyData.equals("")) {
161 } else if (id.equals(OTHER_CONFIG)) {
162 if (configBodyData.equals("")) {
171 // Validation for XML.
172 private boolean isXMLValid(String data) {
174 SAXParserFactory factory = SAXParserFactory.newInstance();
175 factory.setValidating(false);
176 factory.setNamespaceAware(true);
178 SAXParser parser = factory.newSAXParser();
179 XMLReader reader = parser.getXMLReader();
180 reader.setErrorHandler(new XMLErrorHandler());
181 reader.parse(new InputSource(new StringReader(data)));
182 } catch (ParserConfigurationException | SAXException | IOException e) {
190 // Validation for Properties file.
191 public boolean isPropValid(String prop) {
193 Scanner scanner = new Scanner(prop);
194 while (scanner.hasNextLine()) {
195 String line = scanner.nextLine();
196 line.replaceAll("\\s+", "");
197 if (line.startsWith("#")) {
200 if (line.contains("=")) {
201 String[] parts = line.split("=");
202 if (parts.length < 2) {
217 public class XMLErrorHandler implements ErrorHandler {
219 public void warning(SAXParseException e) throws SAXException {
220 System.out.println(e.getMessage());
223 public void error(SAXParseException e) throws SAXException {
224 System.out.println(e.getMessage());
227 public void fatalError(SAXParseException e) throws SAXException {
228 System.out.println(e.getMessage());
234 public Map<String, String> savePolicies() throws Exception {
236 Map<String, String> successMap = new HashMap<>();
237 if(isPolicyExists()){
238 successMap.put("EXISTS", "This Policy already exist on the PAP");
242 if(!isPreparedToSave()){
243 //Prep and configure the policy for saving
247 // Until here we prepared the data and here calling the method to create xml.
248 Path newPolicyPath = null;
249 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
250 successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject());
254 //This is the method for preparing the policy for saving. We have broken it out
255 //separately because the fully configured policy is used for multiple things
257 public boolean prepareToSave() throws Exception{
259 if(isPreparedToSave()){
264 String policyID = policyAdapter.getPolicyID();
265 version = policyAdapter.getHighestVersion();
267 // Create the Instance for pojo, PolicyType object is used in marshalling.
268 if (policyAdapter.getPolicyType().equals("Config")) {
269 PolicyType policyConfig = new PolicyType();
271 policyConfig.setVersion(Integer.toString(version));
272 policyConfig.setPolicyId(policyID);
273 policyConfig.setTarget(new TargetType());
274 policyAdapter.setData(policyConfig);
277 policyName = policyAdapter.getNewFileName();
278 configBodyData = policyAdapter.getConfigBodyData();
279 saveConfigurations(policyName);
281 if (policyAdapter.getData() != null) {
282 PolicyType configPolicy = (PolicyType) policyAdapter.getData();
284 configPolicy.setDescription(policyAdapter.getPolicyDescription());
286 configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
287 AllOfType allOfOne = new AllOfType();
289 String fileName = policyAdapter.getNewFileName();
290 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
291 if ((name == null) || (name.equals(""))) {
292 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
294 allOfOne.getMatch().add(createMatch("PolicyName", name));
295 AllOfType allOf = new AllOfType();
297 // Adding the matches to AllOfType element Match for Onap
298 allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
299 // Match for riskType
300 allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
301 // Match for riskLevel
302 allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
303 // Match for riskguard
304 allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
306 allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
307 // Match for ConfigName
308 allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
310 Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
312 // If there is any dynamic field create the matches here
313 for (String keyField : dynamicFieldConfigAttributes.keySet()) {
314 String key = keyField;
315 String value = dynamicFieldConfigAttributes.get(key);
316 MatchType dynamicMatch = createDynamicMatch(key, value);
317 allOf.getMatch().add(dynamicMatch);
320 AnyOfType anyOf = new AnyOfType();
321 anyOf.getAllOf().add(allOfOne);
322 anyOf.getAllOf().add(allOf);
324 TargetType target = new TargetType();
325 ((TargetType) target).getAnyOf().add(anyOf);
327 // Adding the target to the policy element
328 configPolicy.setTarget((TargetType) target);
330 RuleType rule = new RuleType();
331 rule.setRuleId(policyAdapter.getRuleID());
332 rule.setEffect(EffectType.PERMIT);
334 // Create Target in Rule
335 AllOfType allOfInRule = new AllOfType();
337 // Creating match for ACCESS in rule target
338 MatchType accessMatch = new MatchType();
339 AttributeValueType accessAttributeValue = new AttributeValueType();
340 accessAttributeValue.setDataType(STRING_DATATYPE);
341 accessAttributeValue.getContent().add("ACCESS");
342 accessMatch.setAttributeValue(accessAttributeValue);
343 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
344 URI accessURI = null;
346 accessURI = new URI(ACTION_ID);
347 }catch(URISyntaxException e){
348 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "ConfigPolicy", "Exception creating ACCESS URI");
350 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
351 accessAttributeDesignator.setDataType(STRING_DATATYPE);
352 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
353 accessMatch.setAttributeDesignator(accessAttributeDesignator);
354 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
356 // Creating Config Match in rule Target
357 MatchType configMatch = new MatchType();
358 AttributeValueType configAttributeValue = new AttributeValueType();
359 configAttributeValue.setDataType(STRING_DATATYPE);
360 configAttributeValue.getContent().add("Config");
361 configMatch.setAttributeValue(configAttributeValue);
362 AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
363 URI configURI = null;
365 configURI = new URI(RESOURCE_ID);
366 }catch(URISyntaxException e){
367 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "ConfigPolicy", "Exception creating Config URI");
369 configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
370 configAttributeDesignator.setDataType(STRING_DATATYPE);
371 configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
372 configMatch.setAttributeDesignator(configAttributeDesignator);
373 configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
375 allOfInRule.getMatch().add(accessMatch);
376 allOfInRule.getMatch().add(configMatch);
378 AnyOfType anyOfInRule = new AnyOfType();
379 anyOfInRule.getAllOf().add(allOfInRule);
381 TargetType targetInRule = new TargetType();
382 targetInRule.getAnyOf().add(anyOfInRule);
384 rule.setTarget(targetInRule);
385 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
387 configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
388 policyAdapter.setPolicyData(configPolicy);
391 PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
393 setPreparedToSave(true);
397 // Data required for Advice part is setting here.
398 private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
399 AdviceExpressionsType advices = new AdviceExpressionsType();
400 AdviceExpressionType advice = new AdviceExpressionType();
401 advice.setAdviceId("configID");
402 advice.setAppliesTo(EffectType.PERMIT);
405 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
406 assignment1.setAttributeId("type");
407 assignment1.setCategory(CATEGORY_RESOURCE);
408 assignment1.setIssuer("");
410 AttributeValueType configNameAttributeValue = new AttributeValueType();
411 configNameAttributeValue.setDataType(STRING_DATATYPE);
412 configNameAttributeValue.getContent().add("Configuration");
413 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
415 advice.getAttributeAssignmentExpression().add(assignment1);
417 // For Config file Url if configurations are provided.
418 if (policyAdapter.getConfigType() != null) {
419 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
420 assignment2.setAttributeId("URLID");
421 assignment2.setCategory(CATEGORY_RESOURCE);
422 assignment2.setIssuer("");
424 AttributeValueType AttributeValue = new AttributeValueType();
425 AttributeValue.setDataType(URI_DATATYPE);
426 String content = "$URL" + "/Config/" + getConfigFile(policyName);
427 AttributeValue.getContent().add(content);
428 assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
430 advice.getAttributeAssignmentExpression().add(assignment2);
431 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
432 assignment3.setAttributeId("PolicyName");
433 assignment3.setCategory(CATEGORY_RESOURCE);
434 assignment3.setIssuer("");
436 AttributeValueType attributeValue3 = new AttributeValueType();
437 attributeValue3.setDataType(STRING_DATATYPE);
439 fileName = FilenameUtils.removeExtension(fileName);
440 fileName = fileName + ".xml";
441 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
442 if ((name == null) || (name.equals(""))) {
443 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
445 attributeValue3.getContent().add(name);
446 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
447 advice.getAttributeAssignmentExpression().add(assignment3);
449 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
450 assignment4.setAttributeId("VersionNumber");
451 assignment4.setCategory(CATEGORY_RESOURCE);
452 assignment4.setIssuer("");
454 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
455 configNameAttributeValue4.setDataType(STRING_DATATYPE);
456 configNameAttributeValue4.getContent().add(Integer.toString(version));
457 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
459 advice.getAttributeAssignmentExpression().add(assignment4);
461 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
462 assignment5.setAttributeId("matching:" + ONAPID);
463 assignment5.setCategory(CATEGORY_RESOURCE);
464 assignment5.setIssuer("");
466 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
467 configNameAttributeValue5.setDataType(STRING_DATATYPE);
468 configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
469 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
471 advice.getAttributeAssignmentExpression().add(assignment5);
473 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
474 assignment6.setAttributeId("matching:" + CONFIGID);
475 assignment6.setCategory(CATEGORY_RESOURCE);
476 assignment6.setIssuer("");
478 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
479 configNameAttributeValue6.setDataType(STRING_DATATYPE);
480 configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
481 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
483 advice.getAttributeAssignmentExpression().add(assignment6);
485 Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
486 for (String keyField : dynamicFieldConfigAttributes.keySet()) {
487 String key = keyField;
488 String value = dynamicFieldConfigAttributes.get(key);
489 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
490 assignment7.setAttributeId("matching:" + key);
491 assignment7.setCategory(CATEGORY_RESOURCE);
492 assignment7.setIssuer("");
494 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
495 configNameAttributeValue7.setDataType(STRING_DATATYPE);
496 configNameAttributeValue7.getContent().add(value);
497 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
499 advice.getAttributeAssignmentExpression().add(assignment7);
504 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
505 assignment8.setAttributeId("RiskType");
506 assignment8.setCategory(CATEGORY_RESOURCE);
507 assignment8.setIssuer("");
509 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
510 configNameAttributeValue8.setDataType(STRING_DATATYPE);
511 configNameAttributeValue8.getContent().add(policyAdapter.getRiskType());
512 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
514 advice.getAttributeAssignmentExpression().add(assignment8);
516 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
517 assignment9.setAttributeId("RiskLevel");
518 assignment9.setCategory(CATEGORY_RESOURCE);
519 assignment9.setIssuer("");
521 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
522 configNameAttributeValue9.setDataType(STRING_DATATYPE);
523 configNameAttributeValue9.getContent().add(policyAdapter.getRiskLevel());
524 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
526 advice.getAttributeAssignmentExpression().add(assignment9);
528 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
529 assignment10.setAttributeId("guard");
530 assignment10.setCategory(CATEGORY_RESOURCE);
531 assignment10.setIssuer("");
533 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
534 configNameAttributeValue10.setDataType(STRING_DATATYPE);
535 configNameAttributeValue10.getContent().add(policyAdapter.getGuard());
536 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
538 advice.getAttributeAssignmentExpression().add(assignment10);
540 AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
541 assignment11.setAttributeId("TTLDate");
542 assignment11.setCategory(CATEGORY_RESOURCE);
543 assignment11.setIssuer("");
545 AttributeValueType configNameAttributeValue11 = new AttributeValueType();
546 configNameAttributeValue11.setDataType(STRING_DATATYPE);
547 configNameAttributeValue11.getContent().add(policyAdapter.getTtlDate());
548 assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11));
550 advice.getAttributeAssignmentExpression().add(assignment11);
552 advices.getAdviceExpression().add(advice);
557 public Object getCorrectPolicyDataObject() {
558 return policyAdapter.getPolicyData();