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.api.pap.PAPException;
67 import com.att.research.xacml.std.IdentifierImpl;
69 public class ConfigPolicy extends Policy {
74 private static final Logger LOGGER = FlexLogger.getLogger(ConfigPolicy.class);
76 public static final String JSON_CONFIG = "JSON";
77 public static final String XML_CONFIG = "XML";
78 public static final String PROPERTIES_CONFIG = "PROPERTIES";
79 public static final String OTHER_CONFIG = "OTHER";
81 private String configBodyData;
83 public ConfigPolicy() {
87 public ConfigPolicy(PolicyRestAdapter policyAdapter){
88 this.policyAdapter = policyAdapter;
91 // Saving the Configurations file at server location for config policy.
92 protected void saveConfigurations(String policyName) {
94 String fileName = getConfigFile(policyName);
95 FileWriter fw = new FileWriter(CONFIG_HOME + File.separator + fileName);
96 BufferedWriter bw = new BufferedWriter(fw);
97 bw.write(configBodyData);
99 if (LOGGER.isDebugEnabled()) {
100 LOGGER.debug("Configuration is succesfully saved");
102 } catch (IOException e) {
103 LOGGER.error("Exception Occured while writing Configuration Data"+e);
108 // Here we are adding the extension for the configurations file based on the
109 // config type selection for saving.
110 private String getConfigFile(String filename) {
111 filename = FilenameUtils.removeExtension(filename);
112 if (filename.endsWith(".xml")) {
113 filename = filename.substring(0, filename.length() - 4);
115 String id = policyAdapter.getConfigType();
118 if (id.equalsIgnoreCase(JSON_CONFIG)) {
119 filename = filename + ".json";
121 if (id.equalsIgnoreCase(XML_CONFIG)) {
122 filename = filename + ".xml";
124 if (id.equalsIgnoreCase(PROPERTIES_CONFIG)) {
125 filename = filename + ".properties";
127 if (id.equalsIgnoreCase(OTHER_CONFIG)) {
128 filename = filename + ".txt";
135 // Validations for Config form
137 * FORM VALIDATION WILL BE DONE BY THE PAP-ADMIN before creating JSON object...
138 * BODY VALIDATION WILL BE DONE BY THE PAP-REST after receiving and deserializing the JSON object
140 public boolean validateConfigForm() {
145 * Validate Text Area Body
147 configBodyData = policyAdapter.getConfigBodyData();
148 String id = policyAdapter.getConfigType();
150 if (id.equals(JSON_CONFIG)) {
151 if (!isJSONValid(configBodyData)) {
154 } else if (id.equals(XML_CONFIG)) {
155 if (!isXMLValid(configBodyData)) {
158 } else if (id.equals(PROPERTIES_CONFIG)) {
159 if (!isPropValid(configBodyData)||configBodyData.equals("")) {
162 } else if (id.equals(OTHER_CONFIG)) {
163 if (configBodyData.equals("")) {
172 // Validation for XML.
173 private boolean isXMLValid(String data) {
175 SAXParserFactory factory = SAXParserFactory.newInstance();
176 factory.setValidating(false);
177 factory.setNamespaceAware(true);
179 SAXParser parser = factory.newSAXParser();
180 XMLReader reader = parser.getXMLReader();
181 reader.setErrorHandler(new XMLErrorHandler());
182 reader.parse(new InputSource(new StringReader(data)));
183 } catch (ParserConfigurationException | SAXException | IOException e) {
191 // Validation for Properties file.
192 public boolean isPropValid(String prop) {
194 Scanner scanner = new Scanner(prop);
195 while (scanner.hasNextLine()) {
196 String line = scanner.nextLine();
197 line.replaceAll("\\s+", "");
198 if (line.startsWith("#")) {
201 if (line.contains("=")) {
202 String[] parts = line.split("=");
203 if (parts.length < 2) {
218 public class XMLErrorHandler implements ErrorHandler {
220 public void warning(SAXParseException e) throws SAXException {
221 System.out.println(e.getMessage());
224 public void error(SAXParseException e) throws SAXException {
225 System.out.println(e.getMessage());
228 public void fatalError(SAXParseException e) throws SAXException {
229 System.out.println(e.getMessage());
235 public Map<String, String> savePolicies() throws PAPException {
237 Map<String, String> successMap = new HashMap<>();
238 if(isPolicyExists()){
239 successMap.put("EXISTS", "This Policy already exist on the PAP");
243 if(!isPreparedToSave()){
244 //Prep and configure the policy for saving
248 // Until here we prepared the data and here calling the method to create xml.
249 Path newPolicyPath = null;
250 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
251 successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject());
255 //This is the method for preparing the policy for saving. We have broken it out
256 //separately because the fully configured policy is used for multiple things
258 public boolean prepareToSave() throws PAPException{
260 if(isPreparedToSave()){
265 String policyID = policyAdapter.getPolicyID();
266 version = policyAdapter.getHighestVersion();
268 // Create the Instance for pojo, PolicyType object is used in marshalling.
269 if (policyAdapter.getPolicyType().equals("Config")) {
270 PolicyType policyConfig = new PolicyType();
272 policyConfig.setVersion(Integer.toString(version));
273 policyConfig.setPolicyId(policyID);
274 policyConfig.setTarget(new TargetType());
275 policyAdapter.setData(policyConfig);
278 policyName = policyAdapter.getNewFileName();
279 configBodyData = policyAdapter.getConfigBodyData();
280 saveConfigurations(policyName);
282 if (policyAdapter.getData() != null) {
283 PolicyType configPolicy = (PolicyType) policyAdapter.getData();
285 configPolicy.setDescription(policyAdapter.getPolicyDescription());
287 configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
288 AllOfType allOfOne = new AllOfType();
290 String fileName = policyAdapter.getNewFileName();
291 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
292 if ((name == null) || (name.equals(""))) {
293 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
295 allOfOne.getMatch().add(createMatch("PolicyName", name));
296 AllOfType allOf = new AllOfType();
298 // Adding the matches to AllOfType element Match for Onap
299 allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
300 // Match for riskType
301 allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
302 // Match for riskLevel
303 allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
304 // Match for riskguard
305 allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
307 allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
308 // Match for ConfigName
309 allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
311 Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
313 // If there is any dynamic field create the matches here
314 for (String keyField : dynamicFieldConfigAttributes.keySet()) {
315 String key = keyField;
316 String value = dynamicFieldConfigAttributes.get(key);
317 MatchType dynamicMatch = createDynamicMatch(key, value);
318 allOf.getMatch().add(dynamicMatch);
321 AnyOfType anyOf = new AnyOfType();
322 anyOf.getAllOf().add(allOfOne);
323 anyOf.getAllOf().add(allOf);
325 TargetType target = new TargetType();
326 ((TargetType) target).getAnyOf().add(anyOf);
328 // Adding the target to the policy element
329 configPolicy.setTarget((TargetType) target);
331 RuleType rule = new RuleType();
332 rule.setRuleId(policyAdapter.getRuleID());
333 rule.setEffect(EffectType.PERMIT);
335 // Create Target in Rule
336 AllOfType allOfInRule = new AllOfType();
338 // Creating match for ACCESS in rule target
339 MatchType accessMatch = new MatchType();
340 AttributeValueType accessAttributeValue = new AttributeValueType();
341 accessAttributeValue.setDataType(STRING_DATATYPE);
342 accessAttributeValue.getContent().add("ACCESS");
343 accessMatch.setAttributeValue(accessAttributeValue);
344 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
345 URI accessURI = null;
347 accessURI = new URI(ACTION_ID);
348 }catch(URISyntaxException e){
349 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "ConfigPolicy", "Exception creating ACCESS URI");
351 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
352 accessAttributeDesignator.setDataType(STRING_DATATYPE);
353 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
354 accessMatch.setAttributeDesignator(accessAttributeDesignator);
355 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
357 // Creating Config Match in rule Target
358 MatchType configMatch = new MatchType();
359 AttributeValueType configAttributeValue = new AttributeValueType();
360 configAttributeValue.setDataType(STRING_DATATYPE);
361 configAttributeValue.getContent().add("Config");
362 configMatch.setAttributeValue(configAttributeValue);
363 AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
364 URI configURI = null;
366 configURI = new URI(RESOURCE_ID);
367 }catch(URISyntaxException e){
368 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "ConfigPolicy", "Exception creating Config URI");
370 configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
371 configAttributeDesignator.setDataType(STRING_DATATYPE);
372 configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
373 configMatch.setAttributeDesignator(configAttributeDesignator);
374 configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
376 allOfInRule.getMatch().add(accessMatch);
377 allOfInRule.getMatch().add(configMatch);
379 AnyOfType anyOfInRule = new AnyOfType();
380 anyOfInRule.getAllOf().add(allOfInRule);
382 TargetType targetInRule = new TargetType();
383 targetInRule.getAnyOf().add(anyOfInRule);
385 rule.setTarget(targetInRule);
386 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
388 configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
389 policyAdapter.setPolicyData(configPolicy);
392 PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
394 setPreparedToSave(true);
398 // Data required for Advice part is setting here.
399 private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
400 AdviceExpressionsType advices = new AdviceExpressionsType();
401 AdviceExpressionType advice = new AdviceExpressionType();
402 advice.setAdviceId("configID");
403 advice.setAppliesTo(EffectType.PERMIT);
406 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
407 assignment1.setAttributeId("type");
408 assignment1.setCategory(CATEGORY_RESOURCE);
409 assignment1.setIssuer("");
411 AttributeValueType configNameAttributeValue = new AttributeValueType();
412 configNameAttributeValue.setDataType(STRING_DATATYPE);
413 configNameAttributeValue.getContent().add("Configuration");
414 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
416 advice.getAttributeAssignmentExpression().add(assignment1);
418 // For Config file Url if configurations are provided.
419 if (policyAdapter.getConfigType() != null) {
420 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
421 assignment2.setAttributeId("URLID");
422 assignment2.setCategory(CATEGORY_RESOURCE);
423 assignment2.setIssuer("");
425 AttributeValueType AttributeValue = new AttributeValueType();
426 AttributeValue.setDataType(URI_DATATYPE);
427 String content = "$URL" + "/Config/" + getConfigFile(policyName);
428 AttributeValue.getContent().add(content);
429 assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
431 advice.getAttributeAssignmentExpression().add(assignment2);
432 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
433 assignment3.setAttributeId("PolicyName");
434 assignment3.setCategory(CATEGORY_RESOURCE);
435 assignment3.setIssuer("");
437 AttributeValueType attributeValue3 = new AttributeValueType();
438 attributeValue3.setDataType(STRING_DATATYPE);
440 fileName = FilenameUtils.removeExtension(fileName);
441 fileName = fileName + ".xml";
442 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
443 if ((name == null) || (name.equals(""))) {
444 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
446 attributeValue3.getContent().add(name);
447 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
448 advice.getAttributeAssignmentExpression().add(assignment3);
450 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
451 assignment4.setAttributeId("VersionNumber");
452 assignment4.setCategory(CATEGORY_RESOURCE);
453 assignment4.setIssuer("");
455 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
456 configNameAttributeValue4.setDataType(STRING_DATATYPE);
457 configNameAttributeValue4.getContent().add(Integer.toString(version));
458 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
460 advice.getAttributeAssignmentExpression().add(assignment4);
462 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
463 assignment5.setAttributeId("matching:" + ONAPID);
464 assignment5.setCategory(CATEGORY_RESOURCE);
465 assignment5.setIssuer("");
467 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
468 configNameAttributeValue5.setDataType(STRING_DATATYPE);
469 configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
470 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
472 advice.getAttributeAssignmentExpression().add(assignment5);
474 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
475 assignment6.setAttributeId("matching:" + CONFIGID);
476 assignment6.setCategory(CATEGORY_RESOURCE);
477 assignment6.setIssuer("");
479 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
480 configNameAttributeValue6.setDataType(STRING_DATATYPE);
481 configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
482 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
484 advice.getAttributeAssignmentExpression().add(assignment6);
486 Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
487 for (String keyField : dynamicFieldConfigAttributes.keySet()) {
488 String key = keyField;
489 String value = dynamicFieldConfigAttributes.get(key);
490 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
491 assignment7.setAttributeId("matching:" + key);
492 assignment7.setCategory(CATEGORY_RESOURCE);
493 assignment7.setIssuer("");
495 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
496 configNameAttributeValue7.setDataType(STRING_DATATYPE);
497 configNameAttributeValue7.getContent().add(value);
498 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
500 advice.getAttributeAssignmentExpression().add(assignment7);
505 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
506 assignment8.setAttributeId("RiskType");
507 assignment8.setCategory(CATEGORY_RESOURCE);
508 assignment8.setIssuer("");
510 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
511 configNameAttributeValue8.setDataType(STRING_DATATYPE);
512 configNameAttributeValue8.getContent().add(policyAdapter.getRiskType());
513 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
515 advice.getAttributeAssignmentExpression().add(assignment8);
517 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
518 assignment9.setAttributeId("RiskLevel");
519 assignment9.setCategory(CATEGORY_RESOURCE);
520 assignment9.setIssuer("");
522 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
523 configNameAttributeValue9.setDataType(STRING_DATATYPE);
524 configNameAttributeValue9.getContent().add(policyAdapter.getRiskLevel());
525 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
527 advice.getAttributeAssignmentExpression().add(assignment9);
529 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
530 assignment10.setAttributeId("guard");
531 assignment10.setCategory(CATEGORY_RESOURCE);
532 assignment10.setIssuer("");
534 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
535 configNameAttributeValue10.setDataType(STRING_DATATYPE);
536 configNameAttributeValue10.getContent().add(policyAdapter.getGuard());
537 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
539 advice.getAttributeAssignmentExpression().add(assignment10);
541 AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
542 assignment11.setAttributeId("TTLDate");
543 assignment11.setCategory(CATEGORY_RESOURCE);
544 assignment11.setIssuer("");
546 AttributeValueType configNameAttributeValue11 = new AttributeValueType();
547 configNameAttributeValue11.setDataType(STRING_DATATYPE);
548 configNameAttributeValue11.getContent().add(policyAdapter.getTtlDate());
549 assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11));
551 advice.getAttributeAssignmentExpression().add(assignment11);
553 advices.getAdviceExpression().add(advice);
558 public Object getCorrectPolicyDataObject() {
559 return policyAdapter.getPolicyData();