2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017, 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;
29 import java.io.IOException;
30 import java.io.PrintWriter;
32 import java.net.URISyntaxException;
33 import java.nio.file.Path;
34 import java.nio.file.Paths;
35 import java.util.HashMap;
36 import java.util.Iterator;
37 import java.util.List;
39 import java.util.Map.Entry;
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;
53 import org.apache.commons.io.FilenameUtils;
54 import org.apache.commons.lang.StringUtils;
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.pap.xacml.rest.daoimpl.CommonClassDaoImpl;
60 import org.onap.policy.rest.adapter.PolicyRestAdapter;
61 import org.onap.policy.rest.jpa.MicroServiceModels;
63 public class MicroServiceConfigPolicy extends Policy {
65 private static final Logger LOGGER = FlexLogger.getLogger(MicroServiceConfigPolicy.class);
67 private static Map<String, String> mapAttribute = new HashMap<>();
68 private static Map<String, String> mapMatch = new HashMap<>();
70 private static synchronized Map<String, String> getMatchMap() {
74 private static synchronized void setMatchMap(Map<String, String> mm) {
78 public MicroServiceConfigPolicy() {
82 public MicroServiceConfigPolicy(PolicyRestAdapter policyAdapter) {
83 this.policyAdapter = policyAdapter;
86 // save configuration of the policy based on the policyname
87 private void saveConfigurations(String policyName, String jsonBody) {
88 if (policyName.endsWith(".xml")) {
89 policyName = policyName.replace(".xml", "");
91 try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".json")) {
92 out.println(jsonBody);
93 } catch (Exception e) {
94 LOGGER.error("Exception Occured While writing Configuration data" + e);
99 public Map<String, String> savePolicies() throws PAPException {
101 Map<String, String> successMap = new HashMap<>();
102 if (isPolicyExists()) {
103 successMap.put("EXISTS", "This Policy already exist on the PAP");
107 if (!isPreparedToSave()) {
108 // Prep and configure the policy for saving
112 // Until here we prepared the data and here calling the method to create xml.
113 Path newPolicyPath = null;
114 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
116 successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject());
121 // This is the method for preparing the policy for saving. We have broken it out
122 // separately because the fully configured policy is used for multiple things
124 public boolean prepareToSave() throws PAPException {
126 if (isPreparedToSave()) {
127 // we have already done this
132 String policyID = policyAdapter.getPolicyID();
133 version = policyAdapter.getHighestVersion();
135 // Create the Instance for pojo, PolicyType object is used in marshalling.
136 if (policyAdapter.getPolicyType().equals("Config")) {
137 PolicyType policyConfig = new PolicyType();
139 policyConfig.setVersion(Integer.toString(version));
140 policyConfig.setPolicyId(policyID);
141 policyConfig.setTarget(new TargetType());
142 policyAdapter.setData(policyConfig);
144 policyName = policyAdapter.getNewFileName();
145 if (policyAdapter.getData() != null) {
146 // Save the Configurations file with the policy name with extention based on selection.
147 String jsonBody = policyAdapter.getJsonBody();
148 saveConfigurations(policyName, jsonBody);
150 // Make sure the filename ends with an extension
151 if (policyName.endsWith(".xml") == false) {
152 policyName = policyName + ".xml";
155 PolicyType configPolicy = (PolicyType) policyAdapter.getData();
157 configPolicy.setDescription(policyAdapter.getPolicyDescription());
159 configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
161 AllOfType allOfOne = new AllOfType();
162 String fileName = policyAdapter.getNewFileName();
163 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
164 if ((name == null) || (name.equals(""))) {
165 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
168 // setup values for pulling out matching attributes
169 ObjectMapper mapper = new ObjectMapper();
170 String matching = null;
171 Map<String, String> matchMap = null;
173 JsonNode rootNode = mapper.readTree(policyAdapter.getJsonBody());
174 if (policyAdapter.getTtlDate() == null) {
175 policyAdapter.setTtlDate("NA");
177 if (policyAdapter.getServiceType().contains("-v")) {
178 matching = getValueFromDictionary(policyAdapter.getServiceType());
180 String jsonVersion = StringUtils.replaceEach(rootNode.get("version").toString(),
181 new String[] {"\""}, new String[] {""});
182 matching = getValueFromDictionary(policyAdapter.getServiceType() + "-v" + jsonVersion);
184 if (matching != null && !matching.isEmpty()) {
185 matchMap = Splitter.on(",").withKeyValueSeparator("=").split(matching);
186 setMatchMap(matchMap);
187 if (policyAdapter.getJsonBody() != null) {
188 pullMatchValue(rootNode);
191 } catch (IOException e1) {
192 throw new PAPException(e1);
195 // Match for policyName
196 allOfOne.getMatch().add(createMatch("PolicyName", name));
198 AllOfType allOf = new AllOfType();
200 // Adding the matches to AllOfType element Match for Onap
201 allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
202 if (matchMap == null || matchMap.isEmpty()) {
203 // Match for ConfigName
204 allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
206 allOf.getMatch().add(createDynamicMatch("service", policyAdapter.getServiceType()));
208 allOf.getMatch().add(createDynamicMatch("uuid", policyAdapter.getUuid()));
209 // Match for location
210 allOf.getMatch().add(createDynamicMatch("location", policyAdapter.getLocation()));
212 for (Entry<String, String> matchValue : matchMap.entrySet()) {
213 String value = matchValue.getValue();
214 String key = matchValue.getKey().trim();
215 if (value.contains("matching-true")) {
216 if (mapAttribute.containsKey(key)) {
217 allOf.getMatch().add(createDynamicMatch(key, mapAttribute.get(key)));
222 // Match for riskType
223 allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
224 // Match for riskLevel
225 allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
226 // Match for riskguard
227 allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
229 allOf.getMatch().add(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 ((TargetType) 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, "MicroServiceConfigPolicy",
261 "Exception creating ACCESS URI");
263 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
264 accessAttributeDesignator.setDataType(STRING_DATATYPE);
265 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
266 accessMatch.setAttributeDesignator(accessAttributeDesignator);
267 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
269 // Creating Config Match in rule Target
270 MatchType configMatch = new MatchType();
271 AttributeValueType configAttributeValue = new AttributeValueType();
272 configAttributeValue.setDataType(STRING_DATATYPE);
273 configAttributeValue.getContent().add("Config");
274 configMatch.setAttributeValue(configAttributeValue);
275 AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
276 URI configURI = null;
278 configURI = new URI(RESOURCE_ID);
279 } catch (URISyntaxException e) {
280 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy",
281 "Exception creating Config URI");
283 configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
284 configAttributeDesignator.setDataType(STRING_DATATYPE);
285 configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
286 configMatch.setAttributeDesignator(configAttributeDesignator);
287 configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
289 allOfInRule.getMatch().add(accessMatch);
290 allOfInRule.getMatch().add(configMatch);
292 AnyOfType anyOfInRule = new AnyOfType();
293 anyOfInRule.getAllOf().add(allOfInRule);
295 TargetType targetInRule = new TargetType();
296 targetInRule.getAnyOf().add(anyOfInRule);
298 rule.setTarget(targetInRule);
299 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
301 configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
302 policyAdapter.setPolicyData(configPolicy);
305 PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
307 setPreparedToSave(true);
311 private void pullMatchValue(JsonNode rootNode) {
312 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
313 String newValue = null;
314 while (fieldsIterator.hasNext()) {
315 Map.Entry<String, JsonNode> field = fieldsIterator.next();
316 final String key = field.getKey();
317 final JsonNode value = field.getValue();
318 if (value.isContainerNode() && !value.isArray()) {
319 pullMatchValue(value); // RECURSIVE CALL
322 StringUtils.replaceEach(value.toString(), new String[] {"[", "]", "\""}, new String[] {"", "", ""});
323 mapAttribute.put(key, newValue);
329 private String getValueFromDictionary(String service) {
330 String ruleTemplate = null;
331 String modelName = service.split("-v")[0];
332 String modelVersion = service.split("-v")[1];
334 CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
335 List<Object> result =
336 dbConnection.getDataById(MicroServiceModels.class, "modelName:version", modelName + ":" + modelVersion);
337 if (result != null && !result.isEmpty()) {
338 MicroServiceModels model = (MicroServiceModels) result.get(0);
339 ruleTemplate = model.getAnnotation();
344 // Data required for Advice part is setting here.
345 protected AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
346 AdviceExpressionsType advices = new AdviceExpressionsType();
347 AdviceExpressionType advice = new AdviceExpressionType();
348 advice.setAdviceId("MSID");
349 advice.setAppliesTo(EffectType.PERMIT);
351 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
352 assignment1.setAttributeId("type");
353 assignment1.setCategory(CATEGORY_RESOURCE);
354 assignment1.setIssuer("");
356 AttributeValueType configNameAttributeValue = new AttributeValueType();
357 configNameAttributeValue.setDataType(STRING_DATATYPE);
358 configNameAttributeValue.getContent().add("Configuration");
359 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
361 advice.getAttributeAssignmentExpression().add(assignment1);
362 // For Config file Url if configurations are provided.
363 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
364 assignment2.setAttributeId("URLID");
365 assignment2.setCategory(CATEGORY_RESOURCE);
366 assignment2.setIssuer("");
368 AttributeValueType AttributeValue = new AttributeValueType();
369 AttributeValue.setDataType(URI_DATATYPE);
371 if (policyName.endsWith(".xml")) {
372 configName = policyName.replace(".xml", "");
374 configName = policyName;
376 String content = CONFIG_URL + "/Config/" + configName + ".json";
377 AttributeValue.getContent().add(content);
378 assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
380 advice.getAttributeAssignmentExpression().add(assignment2);
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 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 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 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
423 assignment7.setAttributeId("matching:service");
424 assignment7.setCategory(CATEGORY_RESOURCE);
425 assignment7.setIssuer("");
427 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
428 configNameAttributeValue7.setDataType(STRING_DATATYPE);
429 configNameAttributeValue7.getContent().add(policyAdapter.getServiceType());
430 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
432 advice.getAttributeAssignmentExpression().add(assignment7);
434 Map<String, String> matchMap = getMatchMap();
435 if (matchMap == null || matchMap.isEmpty()) {
436 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
437 assignment6.setAttributeId("matching:" + CONFIGID);
438 assignment6.setCategory(CATEGORY_RESOURCE);
439 assignment6.setIssuer("");
441 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
442 configNameAttributeValue6.setDataType(STRING_DATATYPE);
443 configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
444 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
446 advice.getAttributeAssignmentExpression().add(assignment6);
448 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
449 assignment8.setAttributeId("matching:uuid");
450 assignment8.setCategory(CATEGORY_RESOURCE);
451 assignment8.setIssuer("");
453 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
454 configNameAttributeValue8.setDataType(STRING_DATATYPE);
455 configNameAttributeValue8.getContent().add(policyAdapter.getUuid());
456 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
458 advice.getAttributeAssignmentExpression().add(assignment8);
460 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
461 assignment9.setAttributeId("matching:Location");
462 assignment9.setCategory(CATEGORY_RESOURCE);
463 assignment9.setIssuer("");
465 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
466 configNameAttributeValue9.setDataType(STRING_DATATYPE);
467 configNameAttributeValue9.getContent().add(policyAdapter.getLocation());
468 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
470 advice.getAttributeAssignmentExpression().add(assignment9);
472 for (Entry<String, String> matchValue : matchMap.entrySet()) {
473 String value = matchValue.getValue();
474 String key = matchValue.getKey().trim();
475 if (value.contains("matching-true")) {
476 if (mapAttribute.containsKey(key)) {
477 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
478 assignment9.setAttributeId("matching:" + key);
479 assignment9.setCategory(CATEGORY_RESOURCE);
480 assignment9.setIssuer("");
482 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
483 configNameAttributeValue9.setDataType(STRING_DATATYPE);
484 configNameAttributeValue9.getContent().add(mapAttribute.get(key));
485 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
487 advice.getAttributeAssignmentExpression().add(assignment9);
494 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
495 assignment10.setAttributeId("Priority");
496 assignment10.setCategory(CATEGORY_RESOURCE);
497 assignment10.setIssuer("");
499 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
500 configNameAttributeValue10.setDataType(STRING_DATATYPE);
501 configNameAttributeValue10.getContent().add(policyAdapter.getPriority());
502 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
504 advice.getAttributeAssignmentExpression().add(assignment10);
507 AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
508 assignment11.setAttributeId("RiskType");
509 assignment11.setCategory(CATEGORY_RESOURCE);
510 assignment11.setIssuer("");
512 AttributeValueType configNameAttributeValue11 = new AttributeValueType();
513 configNameAttributeValue11.setDataType(STRING_DATATYPE);
514 configNameAttributeValue11.getContent().add(policyAdapter.getRiskType());
515 assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11));
517 advice.getAttributeAssignmentExpression().add(assignment11);
519 AttributeAssignmentExpressionType assignment12 = new AttributeAssignmentExpressionType();
520 assignment12.setAttributeId("RiskLevel");
521 assignment12.setCategory(CATEGORY_RESOURCE);
522 assignment12.setIssuer("");
524 AttributeValueType configNameAttributeValue12 = new AttributeValueType();
525 configNameAttributeValue12.setDataType(STRING_DATATYPE);
526 configNameAttributeValue12.getContent().add(policyAdapter.getRiskLevel());
527 assignment12.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue12));
529 advice.getAttributeAssignmentExpression().add(assignment12);
531 AttributeAssignmentExpressionType assignment13 = new AttributeAssignmentExpressionType();
532 assignment13.setAttributeId("guard");
533 assignment13.setCategory(CATEGORY_RESOURCE);
534 assignment13.setIssuer("");
536 AttributeValueType configNameAttributeValue13 = new AttributeValueType();
537 configNameAttributeValue13.setDataType(STRING_DATATYPE);
538 configNameAttributeValue13.getContent().add(policyAdapter.getGuard());
539 assignment13.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue13));
541 advice.getAttributeAssignmentExpression().add(assignment13);
543 AttributeAssignmentExpressionType assignment14 = new AttributeAssignmentExpressionType();
544 assignment14.setAttributeId("TTLDate");
545 assignment14.setCategory(CATEGORY_RESOURCE);
546 assignment14.setIssuer("");
548 AttributeValueType configNameAttributeValue14 = new AttributeValueType();
549 configNameAttributeValue14.setDataType(STRING_DATATYPE);
550 configNameAttributeValue14.getContent().add(policyAdapter.getTtlDate());
551 assignment14.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue14));
553 advice.getAttributeAssignmentExpression().add(assignment14);
555 advices.getAdviceExpression().add(advice);
560 public Object getCorrectPolicyDataObject() {
561 return policyAdapter.getPolicyData();