2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2018 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;
24 import java.io.IOException;
25 import java.io.PrintWriter;
27 import java.net.URISyntaxException;
28 import java.nio.file.Path;
29 import java.nio.file.Paths;
30 import java.util.HashMap;
31 import java.util.Iterator;
32 import java.util.List;
34 import java.util.Map.Entry;
36 import org.apache.commons.io.FilenameUtils;
37 import org.apache.commons.lang.StringUtils;
38 import org.onap.policy.common.logging.eelf.MessageCodes;
39 import org.onap.policy.common.logging.eelf.PolicyLogger;
40 import org.onap.policy.common.logging.flexlogger.FlexLogger;
41 import org.onap.policy.common.logging.flexlogger.Logger;
42 import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl;
43 import org.onap.policy.rest.adapter.PolicyRestAdapter;
44 import org.onap.policy.rest.jpa.OptimizationModels;
46 import com.att.research.xacml.api.pap.PAPException;
47 import com.att.research.xacml.std.IdentifierImpl;
48 import com.fasterxml.jackson.databind.JsonNode;
49 import com.fasterxml.jackson.databind.ObjectMapper;
50 import com.google.common.base.Splitter;
52 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
53 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
54 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
55 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
56 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
57 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
58 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
59 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
60 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
61 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
62 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
63 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
64 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
66 public class OptimizationConfigPolicy extends Policy {
68 private static final Logger LOGGER = FlexLogger.getLogger(OptimizationConfigPolicy.class);
70 private static Map<String, String> mapAttribute = new HashMap<>();
71 private static Map<String, String> mapMatch = new HashMap<>();
73 private static synchronized Map<String, String> getMatchMap () {
77 private static synchronized void setMatchMap(Map<String, String> mm) {
81 public OptimizationConfigPolicy() {
85 public OptimizationConfigPolicy(PolicyRestAdapter policyAdapter){
86 this.policyAdapter = policyAdapter;
89 //save configuration of the policy based on the policyname
90 private void saveConfigurations(String policyName, String jsonBody) {
92 if(policyName.endsWith(".xml")){
93 policyName = policyName.replace(".xml", "");
96 try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName +".json");){
97 out.println(jsonBody);
98 } catch (Exception e) {
99 LOGGER.error("Exception Occured While writing Configuration data"+e);
105 public Map<String, String> savePolicies() throws PAPException {
107 Map<String, String> successMap = new HashMap<>();
108 if(isPolicyExists()){
109 successMap.put("EXISTS", "This Policy already exist on the PAP");
113 if(!isPreparedToSave()){
114 //Prep and configure the policy for saving
118 // Until here we prepared the data and here calling the method to create xml.
119 Path newPolicyPath = null;
120 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
122 successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject());
127 //This is the method for preparing the policy for saving. We have broken it out
128 //separately because the fully configured policy is used for multiple things
130 public boolean prepareToSave() throws PAPException{
132 if(isPreparedToSave()){
133 //we have already done this
138 String policyID = policyAdapter.getPolicyID();
139 version = policyAdapter.getHighestVersion();
141 // Create the Instance for pojo, PolicyType object is used in marshalling.
142 if (policyAdapter.getPolicyType().equals("Config")) {
143 PolicyType policyConfig = new PolicyType();
145 policyConfig.setVersion(Integer.toString(version));
146 policyConfig.setPolicyId(policyID);
147 policyConfig.setTarget(new TargetType());
148 policyAdapter.setData(policyConfig);
150 policyName = policyAdapter.getNewFileName();
151 if (policyAdapter.getData() != null) {
152 // Save the Configurations file with the policy name with extention based on selection.
153 String jsonBody = policyAdapter.getJsonBody();
154 saveConfigurations(policyName, jsonBody);
156 // Make sure the filename ends with an extension
157 if (!policyName.endsWith(".xml")) {
158 policyName = policyName + ".xml";
162 PolicyType configPolicy = (PolicyType) policyAdapter.getData();
164 configPolicy.setDescription(policyAdapter.getPolicyDescription());
166 configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
168 AllOfType allOfOne = new AllOfType();
169 String fileName = policyAdapter.getNewFileName();
170 String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length());
171 if ((name == null) || (name.equals(""))) {
172 name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length());
175 //setup values for pulling out matching attributes
176 ObjectMapper mapper = new ObjectMapper();
177 String matching = null;
178 Map<String, String> matchMap = null;
180 JsonNode rootNode = mapper.readTree(policyAdapter.getJsonBody());
181 if (policyAdapter.getTtlDate()==null){
182 policyAdapter.setTtlDate("NA");
184 if (policyAdapter.getServiceType().contains("-v")){
185 matching = getValueFromDictionary(policyAdapter.getServiceType());
187 String jsonVersion = StringUtils.replaceEach(rootNode.get("version").toString(), new String[]{"\""}, new String[]{""});
188 matching = getValueFromDictionary(policyAdapter.getServiceType() + "-v" + jsonVersion);
190 if (matching != null && !matching.isEmpty()){
191 matchMap = Splitter.on(",").withKeyValueSeparator("=").split(matching);
192 setMatchMap(matchMap);
193 if(policyAdapter.getJsonBody() != null){
194 pullMatchValue(rootNode);
197 } catch (IOException e1) {
198 throw new PAPException(e1);
201 // Match for policyName
202 allOfOne.getMatch().add(createMatch("PolicyName", name));
204 AllOfType allOf = new AllOfType();
206 // Adding the matches to AllOfType element Match for Onap
207 allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
208 if (matchMap!=null && !matchMap.isEmpty()) {
209 for (Entry<String, String> matchValue : matchMap.entrySet()){
210 String value = matchValue.getValue();
211 String key = matchValue.getKey().trim();
212 if (value.contains("matching-true") && mapAttribute.containsKey(key)){
213 allOf.getMatch().add(createDynamicMatch(key, mapAttribute.get(key)));
218 // Match for riskType
219 allOf.getMatch().add(
220 createDynamicMatch("RiskType", policyAdapter.getRiskType()));
221 // Match for riskLevel
222 allOf.getMatch().add(
223 createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
224 // Match for riskguard
225 allOf.getMatch().add(
226 createDynamicMatch("guard", policyAdapter.getGuard()));
228 allOf.getMatch().add(
229 createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
231 AnyOfType anyOf = new AnyOfType();
232 anyOf.getAllOf().add(allOfOne);
233 anyOf.getAllOf().add(allOf);
235 TargetType target = new TargetType();
236 target.getAnyOf().add(anyOf);
238 // Adding the target to the policy element
239 configPolicy.setTarget((TargetType) target);
241 RuleType rule = new RuleType();
242 rule.setRuleId(policyAdapter.getRuleID());
244 rule.setEffect(EffectType.PERMIT);
246 // Create Target in Rule
247 AllOfType allOfInRule = new AllOfType();
249 // Creating match for ACCESS in rule target
250 MatchType accessMatch = new MatchType();
251 AttributeValueType accessAttributeValue = new AttributeValueType();
252 accessAttributeValue.setDataType(STRING_DATATYPE);
253 accessAttributeValue.getContent().add("ACCESS");
254 accessMatch.setAttributeValue(accessAttributeValue);
255 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
256 URI accessURI = null;
258 accessURI = new URI(ACTION_ID);
259 } catch (URISyntaxException e) {
260 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "OptimizationConfigPolicy", "Exception creating ACCESS URI");
262 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
263 accessAttributeDesignator.setDataType(STRING_DATATYPE);
264 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
265 accessMatch.setAttributeDesignator(accessAttributeDesignator);
266 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
268 // Creating Config Match in rule Target
269 MatchType configMatch = new MatchType();
270 AttributeValueType configAttributeValue = new AttributeValueType();
271 configAttributeValue.setDataType(STRING_DATATYPE);
272 configAttributeValue.getContent().add("Config");
273 configMatch.setAttributeValue(configAttributeValue);
274 AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
275 URI configURI = null;
277 configURI = new URI(RESOURCE_ID);
278 } catch (URISyntaxException e) {
279 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "OptimizationConfigPolicy", "Exception creating Config URI");
281 configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
282 configAttributeDesignator.setDataType(STRING_DATATYPE);
283 configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
284 configMatch.setAttributeDesignator(configAttributeDesignator);
285 configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
287 allOfInRule.getMatch().add(accessMatch);
288 allOfInRule.getMatch().add(configMatch);
290 AnyOfType anyOfInRule = new AnyOfType();
291 anyOfInRule.getAllOf().add(allOfInRule);
293 TargetType targetInRule = new TargetType();
294 targetInRule.getAnyOf().add(anyOfInRule);
296 rule.setTarget(targetInRule);
297 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
299 configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
300 policyAdapter.setPolicyData(configPolicy);
303 PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
305 setPreparedToSave(true);
309 private void pullMatchValue(JsonNode rootNode) {
310 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
311 String newValue = null;
312 while (fieldsIterator.hasNext()) {
313 Map.Entry<String, JsonNode> field = fieldsIterator.next();
314 final String key = field.getKey();
315 final JsonNode value = field.getValue();
316 if (value.isContainerNode() && !value.isArray()) {
317 pullMatchValue(value); // RECURSIVE CALL
319 newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, new String[]{"", "", ""});
320 mapAttribute.put(key, newValue);
326 private String getValueFromDictionary(String service){
327 String ruleTemplate=null;
328 String modelName = service.split("-v")[0];
329 String modelVersion = service.split("-v")[1];
331 CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
332 List<Object> result = dbConnection.getDataById(OptimizationModels.class, "modelName:version", modelName+":"+modelVersion);
333 if(result != null && !result.isEmpty()){
334 OptimizationModels model = (OptimizationModels) result.get(0);
335 ruleTemplate = model.getAnnotation();
340 // Data required for Advice part is setting here.
341 private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
342 AdviceExpressionsType advices = new AdviceExpressionsType();
343 AdviceExpressionType advice = new AdviceExpressionType();
344 advice.setAdviceId("OptimizationID");
345 advice.setAppliesTo(EffectType.PERMIT);
348 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
349 assignment1.setAttributeId("type");
350 assignment1.setCategory(CATEGORY_RESOURCE);
351 assignment1.setIssuer("");
353 AttributeValueType configNameAttributeValue = new AttributeValueType();
354 configNameAttributeValue.setDataType(STRING_DATATYPE);
355 configNameAttributeValue.getContent().add("Configuration");
356 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
358 advice.getAttributeAssignmentExpression().add(assignment1);
360 // For Config file Url if configurations are provided.
361 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
362 assignment2.setAttributeId("URLID");
363 assignment2.setCategory(CATEGORY_RESOURCE);
364 assignment2.setIssuer("");
366 AttributeValueType attributeValue = new AttributeValueType();
367 attributeValue.setDataType(URI_DATATYPE);
369 if(policyName.endsWith(".xml")){
370 configName = policyName.replace(".xml", "");
372 configName = policyName;
374 String content = CONFIG_URL +"/Config/" + configName + ".json";
375 attributeValue.getContent().add(content);
376 assignment2.setExpression(new ObjectFactory().createAttributeValue(attributeValue));
378 advice.getAttributeAssignmentExpression().add(assignment2);
380 //PolicyName Attribute Assignment
381 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
382 assignment3.setAttributeId("PolicyName");
383 assignment3.setCategory(CATEGORY_RESOURCE);
384 assignment3.setIssuer("");
386 AttributeValueType attributeValue3 = new AttributeValueType();
387 attributeValue3.setDataType(STRING_DATATYPE);
388 fileName = FilenameUtils.removeExtension(fileName);
389 fileName = fileName + ".xml";
390 String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length());
391 if ((name == null) || (name.equals(""))) {
392 name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length());
394 attributeValue3.getContent().add(name);
395 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
396 advice.getAttributeAssignmentExpression().add(assignment3);
398 //VersionNumber Attribute Assignment
399 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
400 assignment4.setAttributeId("VersionNumber");
401 assignment4.setCategory(CATEGORY_RESOURCE);
402 assignment4.setIssuer("");
404 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
405 configNameAttributeValue4.setDataType(STRING_DATATYPE);
406 configNameAttributeValue4.getContent().add(Integer.toString(version));
407 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
409 advice.getAttributeAssignmentExpression().add(assignment4);
411 //OnapName Attribute Assignment
412 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
413 assignment5.setAttributeId("matching:" + ONAPID);
414 assignment5.setCategory(CATEGORY_RESOURCE);
415 assignment5.setIssuer("");
417 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
418 configNameAttributeValue5.setDataType(STRING_DATATYPE);
419 configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
420 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
422 advice.getAttributeAssignmentExpression().add(assignment5);
424 //ServiceType Attribute Assignment
425 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
426 assignment7.setAttributeId("matching:service");
427 assignment7.setCategory(CATEGORY_RESOURCE);
428 assignment7.setIssuer("");
430 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
431 configNameAttributeValue7.setDataType(STRING_DATATYPE);
432 configNameAttributeValue7.getContent().add(policyAdapter.getServiceType());
433 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
435 advice.getAttributeAssignmentExpression().add(assignment7);
437 // Add matching attribute assignments if exist
438 Map<String, String> matchMap = getMatchMap();
439 if (matchMap!=null && !matchMap.isEmpty()) {
440 for (Entry<String, String> matchValue : matchMap.entrySet()){
441 String value = matchValue.getValue();
442 String key = matchValue.getKey().trim();
443 if (value.contains("matching-true") && mapAttribute.containsKey(key)){
444 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
445 assignment9.setAttributeId("matching:" + key);
446 assignment9.setCategory(CATEGORY_RESOURCE);
447 assignment9.setIssuer("");
449 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
450 configNameAttributeValue9.setDataType(STRING_DATATYPE);
451 configNameAttributeValue9.getContent().add(mapAttribute.get(key));
452 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
454 advice.getAttributeAssignmentExpression().add(assignment9);
459 // Priority Attribute Assignment
460 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
461 assignment10.setAttributeId("Priority");
462 assignment10.setCategory(CATEGORY_RESOURCE);
463 assignment10.setIssuer("");
465 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
466 configNameAttributeValue10.setDataType(STRING_DATATYPE);
467 configNameAttributeValue10.getContent().add(policyAdapter.getPriority());
468 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
470 advice.getAttributeAssignmentExpression().add(assignment10);
472 //RiskType Attribute Assignment
473 AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
474 assignment11.setAttributeId("RiskType");
475 assignment11.setCategory(CATEGORY_RESOURCE);
476 assignment11.setIssuer("");
478 AttributeValueType configNameAttributeValue11 = new AttributeValueType();
479 configNameAttributeValue11.setDataType(STRING_DATATYPE);
480 configNameAttributeValue11.getContent().add(policyAdapter.getRiskType());
481 assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11));
483 advice.getAttributeAssignmentExpression().add(assignment11);
485 //RiskLevel Attribute Assignment
486 AttributeAssignmentExpressionType assignment12 = new AttributeAssignmentExpressionType();
487 assignment12.setAttributeId("RiskLevel");
488 assignment12.setCategory(CATEGORY_RESOURCE);
489 assignment12.setIssuer("");
491 AttributeValueType configNameAttributeValue12 = new AttributeValueType();
492 configNameAttributeValue12.setDataType(STRING_DATATYPE);
493 configNameAttributeValue12.getContent().add(policyAdapter.getRiskLevel());
494 assignment12.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue12));
496 advice.getAttributeAssignmentExpression().add(assignment12);
498 //Guard Attribute Assignment
499 AttributeAssignmentExpressionType assignment13 = new AttributeAssignmentExpressionType();
500 assignment13.setAttributeId("guard");
501 assignment13.setCategory(CATEGORY_RESOURCE);
502 assignment13.setIssuer("");
504 AttributeValueType configNameAttributeValue13 = new AttributeValueType();
505 configNameAttributeValue13.setDataType(STRING_DATATYPE);
506 configNameAttributeValue13.getContent().add(policyAdapter.getGuard());
507 assignment13.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue13));
509 advice.getAttributeAssignmentExpression().add(assignment13);
511 //TTLDate Attribute Assignment
512 AttributeAssignmentExpressionType assignment14 = new AttributeAssignmentExpressionType();
513 assignment14.setAttributeId("TTLDate");
514 assignment14.setCategory(CATEGORY_RESOURCE);
515 assignment14.setIssuer("");
517 AttributeValueType configNameAttributeValue14 = new AttributeValueType();
518 configNameAttributeValue14.setDataType(STRING_DATATYPE);
519 configNameAttributeValue14.getContent().add(policyAdapter.getTtlDate());
520 assignment14.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue14));
522 advice.getAttributeAssignmentExpression().add(assignment14);
524 advices.getAdviceExpression().add(advice);
529 public Object getCorrectPolicyDataObject() {
530 return policyAdapter.getPolicyData();