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.openecomp.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.openecomp.policy.common.logging.eelf.MessageCodes;
56 import org.openecomp.policy.common.logging.eelf.PolicyLogger;
57 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
58 import org.openecomp.policy.common.logging.flexlogger.Logger;
59 import org.openecomp.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);
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 e) {
185 } catch (SAXException e) {
187 } catch (IOException e) {
194 // Validation for Properties file.
195 public boolean isPropValid(String prop) {
197 Scanner scanner = new Scanner(prop);
198 while (scanner.hasNextLine()) {
199 String line = scanner.nextLine();
200 line.replaceAll("\\s+", "");
201 if (line.startsWith("#")) {
204 if (line.contains("=")) {
205 String[] parts = line.split("=");
206 if (parts.length < 2) {
221 public class XMLErrorHandler implements ErrorHandler {
223 public void warning(SAXParseException e) throws SAXException {
224 System.out.println(e.getMessage());
227 public void error(SAXParseException e) throws SAXException {
228 System.out.println(e.getMessage());
231 public void fatalError(SAXParseException e) throws SAXException {
232 System.out.println(e.getMessage());
238 public Map<String, String> savePolicies() throws Exception {
240 Map<String, String> successMap = new HashMap<String,String>();
241 if(isPolicyExists()){
242 successMap.put("EXISTS", "This Policy already exist on the PAP");
246 if(!isPreparedToSave()){
247 //Prep and configure the policy for saving
251 // Until here we prepared the data and here calling the method to create xml.
252 Path newPolicyPath = null;
253 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
254 successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject());
258 //This is the method for preparing the policy for saving. We have broken it out
259 //separately because the fully configured policy is used for multiple things
261 public boolean prepareToSave() throws Exception{
263 if(isPreparedToSave()){
268 String policyID = policyAdapter.getPolicyID();
269 version = policyAdapter.getHighestVersion();
271 // Create the Instance for pojo, PolicyType object is used in marshalling.
272 if (policyAdapter.getPolicyType().equals("Config")) {
273 PolicyType policyConfig = new PolicyType();
275 policyConfig.setVersion(Integer.toString(version));
276 policyConfig.setPolicyId(policyID);
277 policyConfig.setTarget(new TargetType());
278 policyAdapter.setData(policyConfig);
281 policyName = policyAdapter.getNewFileName();
282 configBodyData = policyAdapter.getConfigBodyData();
283 saveConfigurations(policyName);
285 if (policyAdapter.getData() != null) {
286 PolicyType configPolicy = (PolicyType) policyAdapter.getData();
288 configPolicy.setDescription(policyAdapter.getPolicyDescription());
290 configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
291 AllOfType allOfOne = new AllOfType();
293 String fileName = policyAdapter.getNewFileName();
294 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
295 if ((name == null) || (name.equals(""))) {
296 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
298 allOfOne.getMatch().add(createMatch("PolicyName", name));
299 AllOfType allOf = new AllOfType();
301 // Adding the matches to AllOfType element Match for Ecomp
302 allOf.getMatch().add(createMatch("ECOMPName", policyAdapter.getEcompName()));
303 // Match for riskType
304 allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
305 // Match for riskLevel
306 allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
307 // Match for riskguard
308 allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
310 allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
311 // Match for ConfigName
312 allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
314 Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
316 // If there is any dynamic field create the matches here
317 for (String keyField : dynamicFieldConfigAttributes.keySet()) {
318 String key = keyField;
319 String value = dynamicFieldConfigAttributes.get(key);
320 MatchType dynamicMatch = createDynamicMatch(key, value);
321 allOf.getMatch().add(dynamicMatch);
324 AnyOfType anyOf = new AnyOfType();
325 anyOf.getAllOf().add(allOfOne);
326 anyOf.getAllOf().add(allOf);
328 TargetType target = new TargetType();
329 ((TargetType) target).getAnyOf().add(anyOf);
331 // Adding the target to the policy element
332 configPolicy.setTarget((TargetType) target);
334 RuleType rule = new RuleType();
335 rule.setRuleId(policyAdapter.getRuleID());
336 rule.setEffect(EffectType.PERMIT);
338 // Create Target in Rule
339 AllOfType allOfInRule = new AllOfType();
341 // Creating match for ACCESS in rule target
342 MatchType accessMatch = new MatchType();
343 AttributeValueType accessAttributeValue = new AttributeValueType();
344 accessAttributeValue.setDataType(STRING_DATATYPE);
345 accessAttributeValue.getContent().add("ACCESS");
346 accessMatch.setAttributeValue(accessAttributeValue);
347 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
348 URI accessURI = null;
350 accessURI = new URI(ACTION_ID);
351 }catch(URISyntaxException e){
352 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "ConfigPolicy", "Exception creating ACCESS URI");
354 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
355 accessAttributeDesignator.setDataType(STRING_DATATYPE);
356 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
357 accessMatch.setAttributeDesignator(accessAttributeDesignator);
358 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
360 // Creating Config Match in rule Target
361 MatchType configMatch = new MatchType();
362 AttributeValueType configAttributeValue = new AttributeValueType();
363 configAttributeValue.setDataType(STRING_DATATYPE);
364 configAttributeValue.getContent().add("Config");
365 configMatch.setAttributeValue(configAttributeValue);
366 AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
367 URI configURI = null;
369 configURI = new URI(RESOURCE_ID);
370 }catch(URISyntaxException e){
371 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "ConfigPolicy", "Exception creating Config URI");
373 configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
374 configAttributeDesignator.setDataType(STRING_DATATYPE);
375 configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
376 configMatch.setAttributeDesignator(configAttributeDesignator);
377 configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
379 allOfInRule.getMatch().add(accessMatch);
380 allOfInRule.getMatch().add(configMatch);
382 AnyOfType anyOfInRule = new AnyOfType();
383 anyOfInRule.getAllOf().add(allOfInRule);
385 TargetType targetInRule = new TargetType();
386 targetInRule.getAnyOf().add(anyOfInRule);
388 rule.setTarget(targetInRule);
389 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
391 configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
392 policyAdapter.setPolicyData(configPolicy);
395 PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
397 setPreparedToSave(true);
401 // Data required for Advice part is setting here.
402 private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
403 AdviceExpressionsType advices = new AdviceExpressionsType();
404 AdviceExpressionType advice = new AdviceExpressionType();
405 advice.setAdviceId("configID");
406 advice.setAppliesTo(EffectType.PERMIT);
409 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
410 assignment1.setAttributeId("type");
411 assignment1.setCategory(CATEGORY_RESOURCE);
412 assignment1.setIssuer("");
414 AttributeValueType configNameAttributeValue = new AttributeValueType();
415 configNameAttributeValue.setDataType(STRING_DATATYPE);
416 configNameAttributeValue.getContent().add("Configuration");
417 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
419 advice.getAttributeAssignmentExpression().add(assignment1);
421 // For Config file Url if configurations are provided.
422 if (policyAdapter.getConfigType() != null) {
423 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
424 assignment2.setAttributeId("URLID");
425 assignment2.setCategory(CATEGORY_RESOURCE);
426 assignment2.setIssuer("");
428 AttributeValueType AttributeValue = new AttributeValueType();
429 AttributeValue.setDataType(URI_DATATYPE);
430 String content = "$URL" + "/Config/" + getConfigFile(policyName);
431 AttributeValue.getContent().add(content);
432 assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
434 advice.getAttributeAssignmentExpression().add(assignment2);
435 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
436 assignment3.setAttributeId("PolicyName");
437 assignment3.setCategory(CATEGORY_RESOURCE);
438 assignment3.setIssuer("");
440 AttributeValueType attributeValue3 = new AttributeValueType();
441 attributeValue3.setDataType(STRING_DATATYPE);
443 fileName = FilenameUtils.removeExtension(fileName);
444 fileName = fileName + ".xml";
445 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
446 if ((name == null) || (name.equals(""))) {
447 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
449 attributeValue3.getContent().add(name);
450 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
451 advice.getAttributeAssignmentExpression().add(assignment3);
453 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
454 assignment4.setAttributeId("VersionNumber");
455 assignment4.setCategory(CATEGORY_RESOURCE);
456 assignment4.setIssuer("");
458 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
459 configNameAttributeValue4.setDataType(STRING_DATATYPE);
460 configNameAttributeValue4.getContent().add(Integer.toString(version));
461 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
463 advice.getAttributeAssignmentExpression().add(assignment4);
465 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
466 assignment5.setAttributeId("matching:" + ECOMPID);
467 assignment5.setCategory(CATEGORY_RESOURCE);
468 assignment5.setIssuer("");
470 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
471 configNameAttributeValue5.setDataType(STRING_DATATYPE);
472 configNameAttributeValue5.getContent().add(policyAdapter.getEcompName());
473 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
475 advice.getAttributeAssignmentExpression().add(assignment5);
477 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
478 assignment6.setAttributeId("matching:" + CONFIGID);
479 assignment6.setCategory(CATEGORY_RESOURCE);
480 assignment6.setIssuer("");
482 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
483 configNameAttributeValue6.setDataType(STRING_DATATYPE);
484 configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
485 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
487 advice.getAttributeAssignmentExpression().add(assignment6);
489 Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
490 for (String keyField : dynamicFieldConfigAttributes.keySet()) {
491 String key = keyField;
492 String value = dynamicFieldConfigAttributes.get(key);
493 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
494 assignment7.setAttributeId("matching:" + key);
495 assignment7.setCategory(CATEGORY_RESOURCE);
496 assignment7.setIssuer("");
498 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
499 configNameAttributeValue7.setDataType(STRING_DATATYPE);
500 configNameAttributeValue7.getContent().add(value);
501 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
503 advice.getAttributeAssignmentExpression().add(assignment7);
508 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
509 assignment8.setAttributeId("RiskType");
510 assignment8.setCategory(CATEGORY_RESOURCE);
511 assignment8.setIssuer("");
513 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
514 configNameAttributeValue8.setDataType(STRING_DATATYPE);
515 configNameAttributeValue8.getContent().add(policyAdapter.getRiskType());
516 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
518 advice.getAttributeAssignmentExpression().add(assignment8);
520 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
521 assignment9.setAttributeId("RiskLevel");
522 assignment9.setCategory(CATEGORY_RESOURCE);
523 assignment9.setIssuer("");
525 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
526 configNameAttributeValue9.setDataType(STRING_DATATYPE);
527 configNameAttributeValue9.getContent().add(policyAdapter.getRiskLevel());
528 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
530 advice.getAttributeAssignmentExpression().add(assignment9);
532 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
533 assignment10.setAttributeId("guard");
534 assignment10.setCategory(CATEGORY_RESOURCE);
535 assignment10.setIssuer("");
537 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
538 configNameAttributeValue10.setDataType(STRING_DATATYPE);
539 configNameAttributeValue10.getContent().add(policyAdapter.getGuard());
540 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
542 advice.getAttributeAssignmentExpression().add(assignment10);
544 AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
545 assignment11.setAttributeId("TTLDate");
546 assignment11.setCategory(CATEGORY_RESOURCE);
547 assignment11.setIssuer("");
549 AttributeValueType configNameAttributeValue11 = new AttributeValueType();
550 configNameAttributeValue11.setDataType(STRING_DATATYPE);
551 configNameAttributeValue11.getContent().add(policyAdapter.getTtlDate());
552 assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11));
554 advice.getAttributeAssignmentExpression().add(assignment11);
556 advices.getAdviceExpression().add(advice);
561 public Object getCorrectPolicyDataObject() {
562 return policyAdapter.getPolicyData();