2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2018-2019 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 com.att.research.xacml.api.pap.PAPException;
24 import com.att.research.xacml.std.IdentifierImpl;
25 import com.fasterxml.jackson.databind.JsonNode;
26 import com.fasterxml.jackson.databind.ObjectMapper;
27 import com.google.common.base.Splitter;
30 import java.io.IOException;
31 import java.io.PrintWriter;
33 import java.net.URISyntaxException;
34 import java.nio.file.Path;
35 import java.nio.file.Paths;
36 import java.util.HashMap;
37 import java.util.Iterator;
38 import java.util.List;
40 import java.util.Map.Entry;
42 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
43 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
44 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
51 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
52 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
53 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
54 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
56 import org.apache.commons.io.FilenameUtils;
57 import org.apache.commons.lang.StringUtils;
58 import org.onap.policy.common.logging.eelf.MessageCodes;
59 import org.onap.policy.common.logging.eelf.PolicyLogger;
60 import org.onap.policy.common.logging.flexlogger.FlexLogger;
61 import org.onap.policy.common.logging.flexlogger.Logger;
62 import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl;
63 import org.onap.policy.rest.adapter.PolicyRestAdapter;
64 import org.onap.policy.rest.jpa.OptimizationModels;
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);
104 public Map<String, String> savePolicies() throws PAPException {
106 Map<String, String> successMap = new HashMap<>();
107 if (isPolicyExists()) {
108 successMap.put("EXISTS", "This Policy already exist on the PAP");
112 if (!isPreparedToSave()) {
113 // Prep and configure the policy for saving
117 // Until here we prepared the data and here calling the method to create xml.
118 Path newPolicyPath = null;
119 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
121 successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject());
126 // This is the method for preparing the policy for saving. We have broken it out
127 // separately because the fully configured policy is used for multiple things
129 public boolean prepareToSave() throws PAPException {
131 if (isPreparedToSave()) {
132 // we have already done this
137 String policyID = policyAdapter.getPolicyID();
138 version = policyAdapter.getHighestVersion();
140 // Create the Instance for pojo, PolicyType object is used in marshalling.
141 if (policyAdapter.getPolicyType().equals("Config")) {
142 PolicyType policyConfig = new PolicyType();
144 policyConfig.setVersion(Integer.toString(version));
145 policyConfig.setPolicyId(policyID);
146 policyConfig.setTarget(new TargetType());
147 policyAdapter.setData(policyConfig);
149 policyName = policyAdapter.getNewFileName();
150 if (policyAdapter.getData() != null) {
151 // Save the Configurations file with the policy name with extention based on selection.
152 String jsonBody = policyAdapter.getJsonBody();
153 saveConfigurations(policyName, jsonBody);
155 // Make sure the filename ends with an extension
156 if (!policyName.endsWith(".xml")) {
157 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(),
186 new String[] {"\""}, new String[] {""});
187 matching = getValueFromDictionary(policyAdapter.getServiceType() + "-v" + jsonVersion);
189 if (matching != null && !matching.isEmpty()) {
190 matchMap = Splitter.on(",").withKeyValueSeparator("=").split(matching);
191 setMatchMap(matchMap);
192 if (policyAdapter.getJsonBody() != null) {
193 pullMatchValue(rootNode);
196 } catch (IOException e1) {
197 throw new PAPException(e1);
200 // Match for policyName
201 allOfOne.getMatch().add(createMatch("PolicyName", name));
203 AllOfType allOf = new AllOfType();
205 // Adding the matches to AllOfType element Match for Onap
206 allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
207 if (matchMap != null && !matchMap.isEmpty()) {
208 for (Entry<String, String> matchValue : matchMap.entrySet()) {
209 String value = matchValue.getValue();
210 String key = matchValue.getKey().trim();
211 if (value.contains("matching-true") && mapAttribute.containsKey(key)) {
212 allOf.getMatch().add(createDynamicMatch(key, mapAttribute.get(key)));
217 // Match for riskType
218 allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
219 // Match for riskLevel
220 allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
221 // Match for riskguard
222 allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
224 allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
226 AnyOfType anyOf = new AnyOfType();
227 anyOf.getAllOf().add(allOfOne);
228 anyOf.getAllOf().add(allOf);
230 TargetType target = new TargetType();
231 target.getAnyOf().add(anyOf);
233 // Adding the target to the policy element
234 configPolicy.setTarget((TargetType) target);
236 RuleType rule = new RuleType();
237 rule.setRuleId(policyAdapter.getRuleID());
239 rule.setEffect(EffectType.PERMIT);
241 // Create Target in Rule
242 AllOfType allOfInRule = new AllOfType();
244 // Creating match for ACCESS in rule target
245 MatchType accessMatch = new MatchType();
246 AttributeValueType accessAttributeValue = new AttributeValueType();
247 accessAttributeValue.setDataType(STRING_DATATYPE);
248 accessAttributeValue.getContent().add("ACCESS");
249 accessMatch.setAttributeValue(accessAttributeValue);
250 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
251 URI accessURI = null;
253 accessURI = new URI(ACTION_ID);
254 } catch (URISyntaxException e) {
255 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "OptimizationConfigPolicy",
256 "Exception creating ACCESS URI");
258 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
259 accessAttributeDesignator.setDataType(STRING_DATATYPE);
260 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
261 accessMatch.setAttributeDesignator(accessAttributeDesignator);
262 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
264 // Creating Config Match in rule Target
265 MatchType configMatch = new MatchType();
266 AttributeValueType configAttributeValue = new AttributeValueType();
267 configAttributeValue.setDataType(STRING_DATATYPE);
268 configAttributeValue.getContent().add("Config");
269 configMatch.setAttributeValue(configAttributeValue);
270 AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
271 URI configURI = null;
273 configURI = new URI(RESOURCE_ID);
274 } catch (URISyntaxException e) {
275 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "OptimizationConfigPolicy",
276 "Exception creating Config URI");
278 configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
279 configAttributeDesignator.setDataType(STRING_DATATYPE);
280 configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
281 configMatch.setAttributeDesignator(configAttributeDesignator);
282 configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
284 allOfInRule.getMatch().add(accessMatch);
285 allOfInRule.getMatch().add(configMatch);
287 AnyOfType anyOfInRule = new AnyOfType();
288 anyOfInRule.getAllOf().add(allOfInRule);
290 TargetType targetInRule = new TargetType();
291 targetInRule.getAnyOf().add(anyOfInRule);
293 rule.setTarget(targetInRule);
294 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
296 configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
297 policyAdapter.setPolicyData(configPolicy);
300 PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
302 setPreparedToSave(true);
306 private void pullMatchValue(JsonNode rootNode) {
307 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
308 String newValue = null;
309 while (fieldsIterator.hasNext()) {
310 Map.Entry<String, JsonNode> field = fieldsIterator.next();
311 final String key = field.getKey();
312 final JsonNode value = field.getValue();
313 if (value.isContainerNode() && !value.isArray()) {
314 pullMatchValue(value); // RECURSIVE CALL
316 newValue = StringUtils.replaceEach(value.toString(), new String[] {"[", "]", "\""},
317 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 =
331 dbConnection.getDataById(OptimizationModels.class, "modelName:version", modelName + ":" + modelVersion);
332 if (result != null && !result.isEmpty()) {
333 OptimizationModels model = (OptimizationModels) result.get(0);
334 ruleTemplate = model.getAnnotation();
339 // Data required for Advice part is setting here.
340 private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
341 AdviceExpressionsType advices = new AdviceExpressionsType();
342 AdviceExpressionType advice = new AdviceExpressionType();
343 advice.setAdviceId("OptimizationID");
344 advice.setAppliesTo(EffectType.PERMIT);
347 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
348 assignment1.setAttributeId("type");
349 assignment1.setCategory(CATEGORY_RESOURCE);
350 assignment1.setIssuer("");
352 AttributeValueType configNameAttributeValue = new AttributeValueType();
353 configNameAttributeValue.setDataType(STRING_DATATYPE);
354 configNameAttributeValue.getContent().add("Configuration");
355 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
357 advice.getAttributeAssignmentExpression().add(assignment1);
359 // For Config file Url if configurations are provided.
360 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
361 assignment2.setAttributeId("URLID");
362 assignment2.setCategory(CATEGORY_RESOURCE);
363 assignment2.setIssuer("");
365 AttributeValueType attributeValue = new AttributeValueType();
366 attributeValue.setDataType(URI_DATATYPE);
368 if (policyName.endsWith(".xml")) {
369 configName = policyName.replace(".xml", "");
371 configName = policyName;
373 String content = CONFIG_URL + "/Config/" + configName + ".json";
374 attributeValue.getContent().add(content);
375 assignment2.setExpression(new ObjectFactory().createAttributeValue(attributeValue));
377 advice.getAttributeAssignmentExpression().add(assignment2);
379 // PolicyName Attribute Assignment
380 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
381 assignment3.setAttributeId("PolicyName");
382 assignment3.setCategory(CATEGORY_RESOURCE);
383 assignment3.setIssuer("");
385 AttributeValueType attributeValue3 = new AttributeValueType();
386 attributeValue3.setDataType(STRING_DATATYPE);
387 fileName = FilenameUtils.removeExtension(fileName);
388 fileName = fileName + ".xml";
389 String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length());
390 if ((name == null) || (name.equals(""))) {
391 name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length());
393 attributeValue3.getContent().add(name);
394 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
395 advice.getAttributeAssignmentExpression().add(assignment3);
397 // VersionNumber Attribute Assignment
398 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
399 assignment4.setAttributeId("VersionNumber");
400 assignment4.setCategory(CATEGORY_RESOURCE);
401 assignment4.setIssuer("");
403 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
404 configNameAttributeValue4.setDataType(STRING_DATATYPE);
405 configNameAttributeValue4.getContent().add(Integer.toString(version));
406 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
408 advice.getAttributeAssignmentExpression().add(assignment4);
410 // OnapName Attribute Assignment
411 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
412 assignment5.setAttributeId("matching:" + ONAPID);
413 assignment5.setCategory(CATEGORY_RESOURCE);
414 assignment5.setIssuer("");
416 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
417 configNameAttributeValue5.setDataType(STRING_DATATYPE);
418 configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
419 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
421 advice.getAttributeAssignmentExpression().add(assignment5);
423 // ServiceType Attribute Assignment
424 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
425 assignment7.setAttributeId("matching:service");
426 assignment7.setCategory(CATEGORY_RESOURCE);
427 assignment7.setIssuer("");
429 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
430 configNameAttributeValue7.setDataType(STRING_DATATYPE);
431 configNameAttributeValue7.getContent().add(policyAdapter.getServiceType());
432 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
434 advice.getAttributeAssignmentExpression().add(assignment7);
436 // Add matching attribute assignments if exist
437 Map<String, String> matchMap = getMatchMap();
438 if (matchMap != null && !matchMap.isEmpty()) {
439 for (Entry<String, String> matchValue : matchMap.entrySet()) {
440 String value = matchValue.getValue();
441 String key = matchValue.getKey().trim();
442 if (value.contains("matching-true") && mapAttribute.containsKey(key)) {
443 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
444 assignment9.setAttributeId("matching:" + key);
445 assignment9.setCategory(CATEGORY_RESOURCE);
446 assignment9.setIssuer("");
448 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
449 configNameAttributeValue9.setDataType(STRING_DATATYPE);
450 configNameAttributeValue9.getContent().add(mapAttribute.get(key));
451 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
453 advice.getAttributeAssignmentExpression().add(assignment9);
458 // Priority Attribute Assignment
459 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
460 assignment10.setAttributeId("Priority");
461 assignment10.setCategory(CATEGORY_RESOURCE);
462 assignment10.setIssuer("");
464 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
465 configNameAttributeValue10.setDataType(STRING_DATATYPE);
466 configNameAttributeValue10.getContent().add(policyAdapter.getPriority());
467 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
469 advice.getAttributeAssignmentExpression().add(assignment10);
471 // RiskType Attribute Assignment
472 AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
473 assignment11.setAttributeId("RiskType");
474 assignment11.setCategory(CATEGORY_RESOURCE);
475 assignment11.setIssuer("");
477 AttributeValueType configNameAttributeValue11 = new AttributeValueType();
478 configNameAttributeValue11.setDataType(STRING_DATATYPE);
479 configNameAttributeValue11.getContent().add(policyAdapter.getRiskType());
480 assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11));
482 advice.getAttributeAssignmentExpression().add(assignment11);
484 // RiskLevel Attribute Assignment
485 AttributeAssignmentExpressionType assignment12 = new AttributeAssignmentExpressionType();
486 assignment12.setAttributeId("RiskLevel");
487 assignment12.setCategory(CATEGORY_RESOURCE);
488 assignment12.setIssuer("");
490 AttributeValueType configNameAttributeValue12 = new AttributeValueType();
491 configNameAttributeValue12.setDataType(STRING_DATATYPE);
492 configNameAttributeValue12.getContent().add(policyAdapter.getRiskLevel());
493 assignment12.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue12));
495 advice.getAttributeAssignmentExpression().add(assignment12);
497 // Guard Attribute Assignment
498 AttributeAssignmentExpressionType assignment13 = new AttributeAssignmentExpressionType();
499 assignment13.setAttributeId("guard");
500 assignment13.setCategory(CATEGORY_RESOURCE);
501 assignment13.setIssuer("");
503 AttributeValueType configNameAttributeValue13 = new AttributeValueType();
504 configNameAttributeValue13.setDataType(STRING_DATATYPE);
505 configNameAttributeValue13.getContent().add(policyAdapter.getGuard());
506 assignment13.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue13));
508 advice.getAttributeAssignmentExpression().add(assignment13);
510 // TTLDate Attribute Assignment
511 AttributeAssignmentExpressionType assignment14 = new AttributeAssignmentExpressionType();
512 assignment14.setAttributeId("TTLDate");
513 assignment14.setCategory(CATEGORY_RESOURCE);
514 assignment14.setIssuer("");
516 AttributeValueType configNameAttributeValue14 = new AttributeValueType();
517 configNameAttributeValue14.setDataType(STRING_DATATYPE);
518 configNameAttributeValue14.getContent().add(policyAdapter.getTtlDate());
519 assignment14.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue14));
521 advice.getAttributeAssignmentExpression().add(assignment14);
523 advices.getAdviceExpression().add(advice);
528 public Object getCorrectPolicyDataObject() {
529 return policyAdapter.getPolicyData();