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) {
91 try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName +".json");){
92 if(policyName.endsWith(".xml")){
93 policyName = policyName.replace(".xml", "");
95 out.println(jsonBody);
96 } catch (Exception e) {
97 LOGGER.error("Exception Occured While writing Configuration data"+e);
103 public Map<String, String> savePolicies() throws PAPException {
105 Map<String, String> successMap = new HashMap<>();
106 if(isPolicyExists()){
107 successMap.put("EXISTS", "This Policy already exist on the PAP");
111 if(!isPreparedToSave()){
112 //Prep and configure the policy for saving
116 // Until here we prepared the data and here calling the method to create xml.
117 Path newPolicyPath = null;
118 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
120 successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject());
125 //This is the method for preparing the policy for saving. We have broken it out
126 //separately because the fully configured policy is used for multiple things
128 public boolean prepareToSave() throws PAPException{
130 if(isPreparedToSave()){
131 //we have already done this
136 String policyID = policyAdapter.getPolicyID();
137 version = policyAdapter.getHighestVersion();
139 // Create the Instance for pojo, PolicyType object is used in marshalling.
140 if (policyAdapter.getPolicyType().equals("Config")) {
141 PolicyType policyConfig = new PolicyType();
143 policyConfig.setVersion(Integer.toString(version));
144 policyConfig.setPolicyId(policyID);
145 policyConfig.setTarget(new TargetType());
146 policyAdapter.setData(policyConfig);
148 policyName = policyAdapter.getNewFileName();
149 if (policyAdapter.getData() != null) {
150 // Save the Configurations file with the policy name with extention based on selection.
151 String jsonBody = policyAdapter.getJsonBody();
152 saveConfigurations(policyName, jsonBody);
154 // Make sure the filename ends with an extension
155 if (!policyName.endsWith(".xml")) {
156 policyName = policyName + ".xml";
160 PolicyType configPolicy = (PolicyType) policyAdapter.getData();
162 configPolicy.setDescription(policyAdapter.getPolicyDescription());
164 configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
166 AllOfType allOfOne = new AllOfType();
167 String fileName = policyAdapter.getNewFileName();
168 String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length());
169 if ((name == null) || (name.equals(""))) {
170 name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length());
173 //setup values for pulling out matching attributes
174 ObjectMapper mapper = new ObjectMapper();
175 String matching = null;
176 Map<String, String> matchMap = null;
178 JsonNode rootNode = mapper.readTree(policyAdapter.getJsonBody());
179 if (policyAdapter.getTtlDate()==null){
180 policyAdapter.setTtlDate("NA");
182 if (policyAdapter.getServiceType().contains("-v")){
183 matching = getValueFromDictionary(policyAdapter.getServiceType());
185 String jsonVersion = StringUtils.replaceEach(rootNode.get("version").toString(), new String[]{"\""}, new String[]{""});
186 matching = getValueFromDictionary(policyAdapter.getServiceType() + "-v" + jsonVersion);
188 if (matching != null && !matching.isEmpty()){
189 matchMap = Splitter.on(",").withKeyValueSeparator("=").split(matching);
190 setMatchMap(matchMap);
191 if(policyAdapter.getJsonBody() != null){
192 pullMatchValue(rootNode);
195 } catch (IOException e1) {
196 throw new PAPException(e1);
199 // Match for policyName
200 allOfOne.getMatch().add(createMatch("PolicyName", name));
202 AllOfType allOf = new AllOfType();
204 // Adding the matches to AllOfType element Match for Onap
205 allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
206 if (matchMap!=null && !matchMap.isEmpty()) {
207 for (Entry<String, String> matchValue : matchMap.entrySet()){
208 String value = matchValue.getValue();
209 String key = matchValue.getKey().trim();
210 if (value.contains("matching-true") && mapAttribute.containsKey(key)){
211 allOf.getMatch().add(createDynamicMatch(key, mapAttribute.get(key)));
216 // Match for riskType
217 allOf.getMatch().add(
218 createDynamicMatch("RiskType", policyAdapter.getRiskType()));
219 // Match for riskLevel
220 allOf.getMatch().add(
221 createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
222 // Match for riskguard
223 allOf.getMatch().add(
224 createDynamicMatch("guard", policyAdapter.getGuard()));
226 allOf.getMatch().add(
227 createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
229 AnyOfType anyOf = new AnyOfType();
230 anyOf.getAllOf().add(allOfOne);
231 anyOf.getAllOf().add(allOf);
233 TargetType target = new TargetType();
234 target.getAnyOf().add(anyOf);
236 // Adding the target to the policy element
237 configPolicy.setTarget((TargetType) target);
239 RuleType rule = new RuleType();
240 rule.setRuleId(policyAdapter.getRuleID());
242 rule.setEffect(EffectType.PERMIT);
244 // Create Target in Rule
245 AllOfType allOfInRule = new AllOfType();
247 // Creating match for ACCESS in rule target
248 MatchType accessMatch = new MatchType();
249 AttributeValueType accessAttributeValue = new AttributeValueType();
250 accessAttributeValue.setDataType(STRING_DATATYPE);
251 accessAttributeValue.getContent().add("ACCESS");
252 accessMatch.setAttributeValue(accessAttributeValue);
253 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
254 URI accessURI = null;
256 accessURI = new URI(ACTION_ID);
257 } catch (URISyntaxException e) {
258 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "OptimizationConfigPolicy", "Exception creating ACCESS URI");
260 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
261 accessAttributeDesignator.setDataType(STRING_DATATYPE);
262 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
263 accessMatch.setAttributeDesignator(accessAttributeDesignator);
264 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
266 // Creating Config Match in rule Target
267 MatchType configMatch = new MatchType();
268 AttributeValueType configAttributeValue = new AttributeValueType();
269 configAttributeValue.setDataType(STRING_DATATYPE);
270 configAttributeValue.getContent().add("Config");
271 configMatch.setAttributeValue(configAttributeValue);
272 AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
273 URI configURI = null;
275 configURI = new URI(RESOURCE_ID);
276 } catch (URISyntaxException e) {
277 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "OptimizationConfigPolicy", "Exception creating Config URI");
279 configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
280 configAttributeDesignator.setDataType(STRING_DATATYPE);
281 configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
282 configMatch.setAttributeDesignator(configAttributeDesignator);
283 configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
285 allOfInRule.getMatch().add(accessMatch);
286 allOfInRule.getMatch().add(configMatch);
288 AnyOfType anyOfInRule = new AnyOfType();
289 anyOfInRule.getAllOf().add(allOfInRule);
291 TargetType targetInRule = new TargetType();
292 targetInRule.getAnyOf().add(anyOfInRule);
294 rule.setTarget(targetInRule);
295 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
297 configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
298 policyAdapter.setPolicyData(configPolicy);
301 PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
303 setPreparedToSave(true);
307 private void pullMatchValue(JsonNode rootNode) {
308 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
309 String newValue = null;
310 while (fieldsIterator.hasNext()) {
311 Map.Entry<String, JsonNode> field = fieldsIterator.next();
312 final String key = field.getKey();
313 final JsonNode value = field.getValue();
314 if (value.isContainerNode() && !value.isArray()) {
315 pullMatchValue(value); // RECURSIVE CALL
317 newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, new String[]{"", "", ""});
318 mapAttribute.put(key, newValue);
324 private String getValueFromDictionary(String service){
325 String ruleTemplate=null;
326 String modelName = service.split("-v")[0];
327 String modelVersion = service.split("-v")[1];
329 CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
330 List<Object> result = dbConnection.getDataById(OptimizationModels.class, "modelName:version", modelName+":"+modelVersion);
331 if(result != null && !result.isEmpty()){
332 OptimizationModels model = (OptimizationModels) result.get(0);
333 ruleTemplate = model.getAnnotation();
338 // Data required for Advice part is setting here.
339 private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
340 AdviceExpressionsType advices = new AdviceExpressionsType();
341 AdviceExpressionType advice = new AdviceExpressionType();
342 advice.setAdviceId("OptimizationID");
343 advice.setAppliesTo(EffectType.PERMIT);
346 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
347 assignment1.setAttributeId("type");
348 assignment1.setCategory(CATEGORY_RESOURCE);
349 assignment1.setIssuer("");
351 AttributeValueType configNameAttributeValue = new AttributeValueType();
352 configNameAttributeValue.setDataType(STRING_DATATYPE);
353 configNameAttributeValue.getContent().add("Configuration");
354 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
356 advice.getAttributeAssignmentExpression().add(assignment1);
358 // For Config file Url if configurations are provided.
359 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
360 assignment2.setAttributeId("URLID");
361 assignment2.setCategory(CATEGORY_RESOURCE);
362 assignment2.setIssuer("");
364 AttributeValueType attributeValue = new AttributeValueType();
365 attributeValue.setDataType(URI_DATATYPE);
367 if(policyName.endsWith(".xml")){
368 configName = policyName.replace(".xml", "");
370 configName = policyName;
372 String content = CONFIG_URL +"/Config/" + configName + ".json";
373 attributeValue.getContent().add(content);
374 assignment2.setExpression(new ObjectFactory().createAttributeValue(attributeValue));
376 advice.getAttributeAssignmentExpression().add(assignment2);
378 //PolicyName Attribute Assignment
379 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
380 assignment3.setAttributeId("PolicyName");
381 assignment3.setCategory(CATEGORY_RESOURCE);
382 assignment3.setIssuer("");
384 AttributeValueType attributeValue3 = new AttributeValueType();
385 attributeValue3.setDataType(STRING_DATATYPE);
386 fileName = FilenameUtils.removeExtension(fileName);
387 fileName = fileName + ".xml";
388 String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length());
389 if ((name == null) || (name.equals(""))) {
390 name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length());
392 attributeValue3.getContent().add(name);
393 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
394 advice.getAttributeAssignmentExpression().add(assignment3);
396 //VersionNumber Attribute Assignment
397 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
398 assignment4.setAttributeId("VersionNumber");
399 assignment4.setCategory(CATEGORY_RESOURCE);
400 assignment4.setIssuer("");
402 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
403 configNameAttributeValue4.setDataType(STRING_DATATYPE);
404 configNameAttributeValue4.getContent().add(Integer.toString(version));
405 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
407 advice.getAttributeAssignmentExpression().add(assignment4);
409 //OnapName Attribute Assignment
410 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
411 assignment5.setAttributeId("matching:" + ONAPID);
412 assignment5.setCategory(CATEGORY_RESOURCE);
413 assignment5.setIssuer("");
415 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
416 configNameAttributeValue5.setDataType(STRING_DATATYPE);
417 configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
418 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
420 advice.getAttributeAssignmentExpression().add(assignment5);
422 //ServiceType Attribute Assignment
423 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
424 assignment7.setAttributeId("matching:service");
425 assignment7.setCategory(CATEGORY_RESOURCE);
426 assignment7.setIssuer("");
428 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
429 configNameAttributeValue7.setDataType(STRING_DATATYPE);
430 configNameAttributeValue7.getContent().add(policyAdapter.getServiceType());
431 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
433 advice.getAttributeAssignmentExpression().add(assignment7);
435 // Add matching attribute assignments if exist
436 Map<String, String> matchMap = getMatchMap();
437 if (matchMap!=null && !matchMap.isEmpty()) {
438 for (Entry<String, String> matchValue : matchMap.entrySet()){
439 String value = matchValue.getValue();
440 String key = matchValue.getKey().trim();
441 if (value.contains("matching-true") && mapAttribute.containsKey(key)){
442 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
443 assignment9.setAttributeId("matching:" + key);
444 assignment9.setCategory(CATEGORY_RESOURCE);
445 assignment9.setIssuer("");
447 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
448 configNameAttributeValue9.setDataType(STRING_DATATYPE);
449 configNameAttributeValue9.getContent().add(mapAttribute.get(key));
450 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
452 advice.getAttributeAssignmentExpression().add(assignment9);
457 // Priority Attribute Assignment
458 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
459 assignment10.setAttributeId("Priority");
460 assignment10.setCategory(CATEGORY_RESOURCE);
461 assignment10.setIssuer("");
463 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
464 configNameAttributeValue10.setDataType(STRING_DATATYPE);
465 configNameAttributeValue10.getContent().add(policyAdapter.getPriority());
466 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
468 advice.getAttributeAssignmentExpression().add(assignment10);
470 //RiskType Attribute Assignment
471 AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
472 assignment11.setAttributeId("RiskType");
473 assignment11.setCategory(CATEGORY_RESOURCE);
474 assignment11.setIssuer("");
476 AttributeValueType configNameAttributeValue11 = new AttributeValueType();
477 configNameAttributeValue11.setDataType(STRING_DATATYPE);
478 configNameAttributeValue11.getContent().add(policyAdapter.getRiskType());
479 assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11));
481 advice.getAttributeAssignmentExpression().add(assignment11);
483 //RiskLevel Attribute Assignment
484 AttributeAssignmentExpressionType assignment12 = new AttributeAssignmentExpressionType();
485 assignment12.setAttributeId("RiskLevel");
486 assignment12.setCategory(CATEGORY_RESOURCE);
487 assignment12.setIssuer("");
489 AttributeValueType configNameAttributeValue12 = new AttributeValueType();
490 configNameAttributeValue12.setDataType(STRING_DATATYPE);
491 configNameAttributeValue12.getContent().add(policyAdapter.getRiskLevel());
492 assignment12.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue12));
494 advice.getAttributeAssignmentExpression().add(assignment12);
496 //Guard Attribute Assignment
497 AttributeAssignmentExpressionType assignment13 = new AttributeAssignmentExpressionType();
498 assignment13.setAttributeId("guard");
499 assignment13.setCategory(CATEGORY_RESOURCE);
500 assignment13.setIssuer("");
502 AttributeValueType configNameAttributeValue13 = new AttributeValueType();
503 configNameAttributeValue13.setDataType(STRING_DATATYPE);
504 configNameAttributeValue13.getContent().add(policyAdapter.getGuard());
505 assignment13.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue13));
507 advice.getAttributeAssignmentExpression().add(assignment13);
509 //TTLDate Attribute Assignment
510 AttributeAssignmentExpressionType assignment14 = new AttributeAssignmentExpressionType();
511 assignment14.setAttributeId("TTLDate");
512 assignment14.setCategory(CATEGORY_RESOURCE);
513 assignment14.setIssuer("");
515 AttributeValueType configNameAttributeValue14 = new AttributeValueType();
516 configNameAttributeValue14.setDataType(STRING_DATATYPE);
517 configNameAttributeValue14.getContent().add(policyAdapter.getTtlDate());
518 assignment14.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue14));
520 advice.getAttributeAssignmentExpression().add(assignment14);
522 advices.getAdviceExpression().add(advice);
527 public Object getCorrectPolicyDataObject() {
528 return policyAdapter.getPolicyData();