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 e) {
184 } catch (SAXException e) {
186 } catch (IOException e) {
193 // Validation for Properties file.
194 public boolean isPropValid(String prop) {
196 Scanner scanner = new Scanner(prop);
197 while (scanner.hasNextLine()) {
198 String line = scanner.nextLine();
199 line.replaceAll("\\s+", "");
200 if (line.startsWith("#")) {
203 if (line.contains("=")) {
204 String[] parts = line.split("=");
205 if (parts.length < 2) {
220 public class XMLErrorHandler implements ErrorHandler {
222 public void warning(SAXParseException e) throws SAXException {
223 System.out.println(e.getMessage());
226 public void error(SAXParseException e) throws SAXException {
227 System.out.println(e.getMessage());
230 public void fatalError(SAXParseException e) throws SAXException {
231 System.out.println(e.getMessage());
237 public Map<String, String> savePolicies() throws Exception {
239 Map<String, String> successMap = new HashMap<>();
240 if(isPolicyExists()){
241 successMap.put("EXISTS", "This Policy already exist on the PAP");
245 if(!isPreparedToSave()){
246 //Prep and configure the policy for saving
250 // Until here we prepared the data and here calling the method to create xml.
251 Path newPolicyPath = null;
252 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
253 successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject());
257 //This is the method for preparing the policy for saving. We have broken it out
258 //separately because the fully configured policy is used for multiple things
260 public boolean prepareToSave() throws Exception{
262 if(isPreparedToSave()){
267 String policyID = policyAdapter.getPolicyID();
268 version = policyAdapter.getHighestVersion();
270 // Create the Instance for pojo, PolicyType object is used in marshalling.
271 if (policyAdapter.getPolicyType().equals("Config")) {
272 PolicyType policyConfig = new PolicyType();
274 policyConfig.setVersion(Integer.toString(version));
275 policyConfig.setPolicyId(policyID);
276 policyConfig.setTarget(new TargetType());
277 policyAdapter.setData(policyConfig);
280 policyName = policyAdapter.getNewFileName();
281 configBodyData = policyAdapter.getConfigBodyData();
282 saveConfigurations(policyName);
284 if (policyAdapter.getData() != null) {
285 PolicyType configPolicy = (PolicyType) policyAdapter.getData();
287 configPolicy.setDescription(policyAdapter.getPolicyDescription());
289 configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
290 AllOfType allOfOne = new AllOfType();
292 String fileName = policyAdapter.getNewFileName();
293 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
294 if ((name == null) || (name.equals(""))) {
295 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
297 allOfOne.getMatch().add(createMatch("PolicyName", name));
298 AllOfType allOf = new AllOfType();
300 // Adding the matches to AllOfType element Match for Onap
301 allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
302 // Match for riskType
303 allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
304 // Match for riskLevel
305 allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
306 // Match for riskguard
307 allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
309 allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
310 // Match for ConfigName
311 allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
313 Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
315 // If there is any dynamic field create the matches here
316 for (String keyField : dynamicFieldConfigAttributes.keySet()) {
317 String key = keyField;
318 String value = dynamicFieldConfigAttributes.get(key);
319 MatchType dynamicMatch = createDynamicMatch(key, value);
320 allOf.getMatch().add(dynamicMatch);
323 AnyOfType anyOf = new AnyOfType();
324 anyOf.getAllOf().add(allOfOne);
325 anyOf.getAllOf().add(allOf);
327 TargetType target = new TargetType();
328 ((TargetType) target).getAnyOf().add(anyOf);
330 // Adding the target to the policy element
331 configPolicy.setTarget((TargetType) target);
333 RuleType rule = new RuleType();
334 rule.setRuleId(policyAdapter.getRuleID());
335 rule.setEffect(EffectType.PERMIT);
337 // Create Target in Rule
338 AllOfType allOfInRule = new AllOfType();
340 // Creating match for ACCESS in rule target
341 MatchType accessMatch = new MatchType();
342 AttributeValueType accessAttributeValue = new AttributeValueType();
343 accessAttributeValue.setDataType(STRING_DATATYPE);
344 accessAttributeValue.getContent().add("ACCESS");
345 accessMatch.setAttributeValue(accessAttributeValue);
346 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
347 URI accessURI = null;
349 accessURI = new URI(ACTION_ID);
350 }catch(URISyntaxException e){
351 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "ConfigPolicy", "Exception creating ACCESS URI");
353 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
354 accessAttributeDesignator.setDataType(STRING_DATATYPE);
355 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
356 accessMatch.setAttributeDesignator(accessAttributeDesignator);
357 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
359 // Creating Config Match in rule Target
360 MatchType configMatch = new MatchType();
361 AttributeValueType configAttributeValue = new AttributeValueType();
362 configAttributeValue.setDataType(STRING_DATATYPE);
363 configAttributeValue.getContent().add("Config");
364 configMatch.setAttributeValue(configAttributeValue);
365 AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
366 URI configURI = null;
368 configURI = new URI(RESOURCE_ID);
369 }catch(URISyntaxException e){
370 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "ConfigPolicy", "Exception creating Config URI");
372 configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
373 configAttributeDesignator.setDataType(STRING_DATATYPE);
374 configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
375 configMatch.setAttributeDesignator(configAttributeDesignator);
376 configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
378 allOfInRule.getMatch().add(accessMatch);
379 allOfInRule.getMatch().add(configMatch);
381 AnyOfType anyOfInRule = new AnyOfType();
382 anyOfInRule.getAllOf().add(allOfInRule);
384 TargetType targetInRule = new TargetType();
385 targetInRule.getAnyOf().add(anyOfInRule);
387 rule.setTarget(targetInRule);
388 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
390 configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
391 policyAdapter.setPolicyData(configPolicy);
394 PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
396 setPreparedToSave(true);
400 // Data required for Advice part is setting here.
401 private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
402 AdviceExpressionsType advices = new AdviceExpressionsType();
403 AdviceExpressionType advice = new AdviceExpressionType();
404 advice.setAdviceId("configID");
405 advice.setAppliesTo(EffectType.PERMIT);
408 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
409 assignment1.setAttributeId("type");
410 assignment1.setCategory(CATEGORY_RESOURCE);
411 assignment1.setIssuer("");
413 AttributeValueType configNameAttributeValue = new AttributeValueType();
414 configNameAttributeValue.setDataType(STRING_DATATYPE);
415 configNameAttributeValue.getContent().add("Configuration");
416 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
418 advice.getAttributeAssignmentExpression().add(assignment1);
420 // For Config file Url if configurations are provided.
421 if (policyAdapter.getConfigType() != null) {
422 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
423 assignment2.setAttributeId("URLID");
424 assignment2.setCategory(CATEGORY_RESOURCE);
425 assignment2.setIssuer("");
427 AttributeValueType AttributeValue = new AttributeValueType();
428 AttributeValue.setDataType(URI_DATATYPE);
429 String content = "$URL" + "/Config/" + getConfigFile(policyName);
430 AttributeValue.getContent().add(content);
431 assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
433 advice.getAttributeAssignmentExpression().add(assignment2);
434 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
435 assignment3.setAttributeId("PolicyName");
436 assignment3.setCategory(CATEGORY_RESOURCE);
437 assignment3.setIssuer("");
439 AttributeValueType attributeValue3 = new AttributeValueType();
440 attributeValue3.setDataType(STRING_DATATYPE);
442 fileName = FilenameUtils.removeExtension(fileName);
443 fileName = fileName + ".xml";
444 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
445 if ((name == null) || (name.equals(""))) {
446 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
448 attributeValue3.getContent().add(name);
449 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
450 advice.getAttributeAssignmentExpression().add(assignment3);
452 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
453 assignment4.setAttributeId("VersionNumber");
454 assignment4.setCategory(CATEGORY_RESOURCE);
455 assignment4.setIssuer("");
457 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
458 configNameAttributeValue4.setDataType(STRING_DATATYPE);
459 configNameAttributeValue4.getContent().add(Integer.toString(version));
460 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
462 advice.getAttributeAssignmentExpression().add(assignment4);
464 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
465 assignment5.setAttributeId("matching:" + ONAPID);
466 assignment5.setCategory(CATEGORY_RESOURCE);
467 assignment5.setIssuer("");
469 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
470 configNameAttributeValue5.setDataType(STRING_DATATYPE);
471 configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
472 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
474 advice.getAttributeAssignmentExpression().add(assignment5);
476 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
477 assignment6.setAttributeId("matching:" + CONFIGID);
478 assignment6.setCategory(CATEGORY_RESOURCE);
479 assignment6.setIssuer("");
481 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
482 configNameAttributeValue6.setDataType(STRING_DATATYPE);
483 configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
484 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
486 advice.getAttributeAssignmentExpression().add(assignment6);
488 Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
489 for (String keyField : dynamicFieldConfigAttributes.keySet()) {
490 String key = keyField;
491 String value = dynamicFieldConfigAttributes.get(key);
492 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
493 assignment7.setAttributeId("matching:" + key);
494 assignment7.setCategory(CATEGORY_RESOURCE);
495 assignment7.setIssuer("");
497 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
498 configNameAttributeValue7.setDataType(STRING_DATATYPE);
499 configNameAttributeValue7.getContent().add(value);
500 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
502 advice.getAttributeAssignmentExpression().add(assignment7);
507 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
508 assignment8.setAttributeId("RiskType");
509 assignment8.setCategory(CATEGORY_RESOURCE);
510 assignment8.setIssuer("");
512 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
513 configNameAttributeValue8.setDataType(STRING_DATATYPE);
514 configNameAttributeValue8.getContent().add(policyAdapter.getRiskType());
515 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
517 advice.getAttributeAssignmentExpression().add(assignment8);
519 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
520 assignment9.setAttributeId("RiskLevel");
521 assignment9.setCategory(CATEGORY_RESOURCE);
522 assignment9.setIssuer("");
524 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
525 configNameAttributeValue9.setDataType(STRING_DATATYPE);
526 configNameAttributeValue9.getContent().add(policyAdapter.getRiskLevel());
527 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
529 advice.getAttributeAssignmentExpression().add(assignment9);
531 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
532 assignment10.setAttributeId("guard");
533 assignment10.setCategory(CATEGORY_RESOURCE);
534 assignment10.setIssuer("");
536 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
537 configNameAttributeValue10.setDataType(STRING_DATATYPE);
538 configNameAttributeValue10.getContent().add(policyAdapter.getGuard());
539 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
541 advice.getAttributeAssignmentExpression().add(assignment10);
543 AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
544 assignment11.setAttributeId("TTLDate");
545 assignment11.setCategory(CATEGORY_RESOURCE);
546 assignment11.setIssuer("");
548 AttributeValueType configNameAttributeValue11 = new AttributeValueType();
549 configNameAttributeValue11.setDataType(STRING_DATATYPE);
550 configNameAttributeValue11.getContent().add(policyAdapter.getTtlDate());
551 assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11));
553 advice.getAttributeAssignmentExpression().add(assignment11);
555 advices.getAdviceExpression().add(advice);
560 public Object getCorrectPolicyDataObject() {
561 return policyAdapter.getPolicyData();