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;
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.MicroServiceModels;
66 public class MicroServiceConfigPolicy extends Policy {
68 private static final Logger LOGGER = FlexLogger.getLogger(MicroServiceConfigPolicy.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 MicroServiceConfigPolicy() {
85 public MicroServiceConfigPolicy(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 if (policyName.endsWith(".xml")) {
92 policyName = policyName.replace(".xml", "");
94 try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".json")) {
95 out.println(jsonBody);
96 } catch (Exception e) {
97 LOGGER.error("Exception Occured While writing Configuration data" + e);
102 public Map<String, String> savePolicies() throws PAPException {
104 Map<String, String> successMap = new HashMap<>();
105 if (isPolicyExists()) {
106 successMap.put("EXISTS", "This Policy already exist on the PAP");
110 if (!isPreparedToSave()) {
111 // Prep and configure the policy for saving
115 // Until here we prepared the data and here calling the method to create xml.
116 Path newPolicyPath = null;
117 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
119 successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject());
124 // This is the method for preparing the policy for saving. We have broken it out
125 // separately because the fully configured policy is used for multiple things
127 public boolean prepareToSave() throws PAPException {
129 if (isPreparedToSave()) {
130 // we have already done this
135 String policyID = policyAdapter.getPolicyID();
136 version = policyAdapter.getHighestVersion();
138 // Create the Instance for pojo, PolicyType object is used in marshalling.
139 if (policyAdapter.getPolicyType().equals("Config")) {
140 PolicyType policyConfig = new PolicyType();
142 policyConfig.setVersion(Integer.toString(version));
143 policyConfig.setPolicyId(policyID);
144 policyConfig.setTarget(new TargetType());
145 policyAdapter.setData(policyConfig);
147 policyName = policyAdapter.getNewFileName();
148 if (policyAdapter.getData() != null) {
149 // Save the Configurations file with the policy name with extention based on selection.
150 String jsonBody = policyAdapter.getJsonBody();
151 saveConfigurations(policyName, jsonBody);
153 // Make sure the filename ends with an extension
154 if (policyName.endsWith(".xml") == false) {
155 policyName = policyName + ".xml";
158 PolicyType configPolicy = (PolicyType) policyAdapter.getData();
160 configPolicy.setDescription(policyAdapter.getPolicyDescription());
162 configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
164 AllOfType allOfOne = new AllOfType();
165 String fileName = policyAdapter.getNewFileName();
166 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
167 if ((name == null) || (name.equals(""))) {
168 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
171 // setup values for pulling out matching attributes
172 ObjectMapper mapper = new ObjectMapper();
173 String matching = null;
174 Map<String, String> matchMap = null;
176 JsonNode rootNode = mapper.readTree(policyAdapter.getJsonBody());
177 if (policyAdapter.getTtlDate() == null) {
178 policyAdapter.setTtlDate("NA");
180 if (policyAdapter.getServiceType().contains("-v")) {
181 matching = getValueFromDictionary(policyAdapter.getServiceType());
183 String jsonVersion = StringUtils.replaceEach(rootNode.get("version").toString(),
184 new String[] {"\""}, new String[] {""});
185 matching = getValueFromDictionary(policyAdapter.getServiceType() + "-v" + jsonVersion);
187 if (matching != null && !matching.isEmpty()) {
188 matchMap = Splitter.on(",").withKeyValueSeparator("=").split(matching);
189 setMatchMap(matchMap);
190 if (policyAdapter.getJsonBody() != null) {
191 pullMatchValue(rootNode);
194 } catch (IOException e1) {
195 throw new PAPException(e1);
198 // Match for policyName
199 allOfOne.getMatch().add(createMatch("PolicyName", name));
201 AllOfType allOf = new AllOfType();
203 // Adding the matches to AllOfType element Match for Onap
204 allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
205 if (matchMap == null || matchMap.isEmpty()) {
206 // Match for ConfigName
207 allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
209 allOf.getMatch().add(createDynamicMatch("service", policyAdapter.getServiceType()));
211 allOf.getMatch().add(createDynamicMatch("uuid", policyAdapter.getUuid()));
212 // Match for location
213 allOf.getMatch().add(createDynamicMatch("location", policyAdapter.getLocation()));
215 for (Entry<String, String> matchValue : matchMap.entrySet()) {
216 String value = matchValue.getValue();
217 String key = matchValue.getKey().trim();
218 if (value.contains("matching-true")) {
219 if (mapAttribute.containsKey(key)) {
220 allOf.getMatch().add(createDynamicMatch(key, mapAttribute.get(key)));
225 // Match for riskType
226 allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
227 // Match for riskLevel
228 allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
229 // Match for riskguard
230 allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
232 allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
234 AnyOfType anyOf = new AnyOfType();
235 anyOf.getAllOf().add(allOfOne);
236 anyOf.getAllOf().add(allOf);
238 TargetType target = new TargetType();
239 ((TargetType) target).getAnyOf().add(anyOf);
241 // Adding the target to the policy element
242 configPolicy.setTarget((TargetType) target);
244 RuleType rule = new RuleType();
245 rule.setRuleId(policyAdapter.getRuleID());
247 rule.setEffect(EffectType.PERMIT);
249 // Create Target in Rule
250 AllOfType allOfInRule = new AllOfType();
252 // Creating match for ACCESS in rule target
253 MatchType accessMatch = new MatchType();
254 AttributeValueType accessAttributeValue = new AttributeValueType();
255 accessAttributeValue.setDataType(STRING_DATATYPE);
256 accessAttributeValue.getContent().add("ACCESS");
257 accessMatch.setAttributeValue(accessAttributeValue);
258 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
259 URI accessURI = null;
261 accessURI = new URI(ACTION_ID);
262 } catch (URISyntaxException e) {
263 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy",
264 "Exception creating ACCESS URI");
266 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
267 accessAttributeDesignator.setDataType(STRING_DATATYPE);
268 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
269 accessMatch.setAttributeDesignator(accessAttributeDesignator);
270 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
272 // Creating Config Match in rule Target
273 MatchType configMatch = new MatchType();
274 AttributeValueType configAttributeValue = new AttributeValueType();
275 configAttributeValue.setDataType(STRING_DATATYPE);
276 configAttributeValue.getContent().add("Config");
277 configMatch.setAttributeValue(configAttributeValue);
278 AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
279 URI configURI = null;
281 configURI = new URI(RESOURCE_ID);
282 } catch (URISyntaxException e) {
283 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy",
284 "Exception creating Config URI");
286 configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
287 configAttributeDesignator.setDataType(STRING_DATATYPE);
288 configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
289 configMatch.setAttributeDesignator(configAttributeDesignator);
290 configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
292 allOfInRule.getMatch().add(accessMatch);
293 allOfInRule.getMatch().add(configMatch);
295 AnyOfType anyOfInRule = new AnyOfType();
296 anyOfInRule.getAllOf().add(allOfInRule);
298 TargetType targetInRule = new TargetType();
299 targetInRule.getAnyOf().add(anyOfInRule);
301 rule.setTarget(targetInRule);
302 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
304 configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
305 policyAdapter.setPolicyData(configPolicy);
308 PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
310 setPreparedToSave(true);
314 private void pullMatchValue(JsonNode rootNode) {
315 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
316 String newValue = null;
317 while (fieldsIterator.hasNext()) {
318 Map.Entry<String, JsonNode> field = fieldsIterator.next();
319 final String key = field.getKey();
320 final JsonNode value = field.getValue();
321 if (value.isContainerNode() && !value.isArray()) {
322 pullMatchValue(value); // RECURSIVE CALL
324 newValue = StringUtils.replaceEach(value.toString(), new String[] {"[", "]", "\""},
325 new String[] {"", "", ""});
326 mapAttribute.put(key, newValue);
332 private String getValueFromDictionary(String service) {
333 String ruleTemplate = null;
334 String modelName = service.split("-v")[0];
335 String modelVersion = service.split("-v")[1];
337 CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
338 List<Object> result =
339 dbConnection.getDataById(MicroServiceModels.class, "modelName:version", modelName + ":" + modelVersion);
340 if (result != null && !result.isEmpty()) {
341 MicroServiceModels model = (MicroServiceModels) result.get(0);
342 ruleTemplate = model.getAnnotation();
347 // Data required for Advice part is setting here.
348 private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
349 AdviceExpressionsType advices = new AdviceExpressionsType();
350 AdviceExpressionType advice = new AdviceExpressionType();
351 advice.setAdviceId("MSID");
352 advice.setAppliesTo(EffectType.PERMIT);
354 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
355 assignment1.setAttributeId("type");
356 assignment1.setCategory(CATEGORY_RESOURCE);
357 assignment1.setIssuer("");
359 AttributeValueType configNameAttributeValue = new AttributeValueType();
360 configNameAttributeValue.setDataType(STRING_DATATYPE);
361 configNameAttributeValue.getContent().add("Configuration");
362 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
364 advice.getAttributeAssignmentExpression().add(assignment1);
365 // For Config file Url if configurations are provided.
366 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
367 assignment2.setAttributeId("URLID");
368 assignment2.setCategory(CATEGORY_RESOURCE);
369 assignment2.setIssuer("");
371 AttributeValueType AttributeValue = new AttributeValueType();
372 AttributeValue.setDataType(URI_DATATYPE);
374 if (policyName.endsWith(".xml")) {
375 configName = policyName.replace(".xml", "");
377 configName = policyName;
379 String content = CONFIG_URL + "/Config/" + configName + ".json";
380 AttributeValue.getContent().add(content);
381 assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
383 advice.getAttributeAssignmentExpression().add(assignment2);
384 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
385 assignment3.setAttributeId("PolicyName");
386 assignment3.setCategory(CATEGORY_RESOURCE);
387 assignment3.setIssuer("");
389 AttributeValueType attributeValue3 = new AttributeValueType();
390 attributeValue3.setDataType(STRING_DATATYPE);
391 fileName = FilenameUtils.removeExtension(fileName);
392 fileName = fileName + ".xml";
393 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
394 if ((name == null) || (name.equals(""))) {
395 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
397 attributeValue3.getContent().add(name);
398 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
399 advice.getAttributeAssignmentExpression().add(assignment3);
401 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
402 assignment4.setAttributeId("VersionNumber");
403 assignment4.setCategory(CATEGORY_RESOURCE);
404 assignment4.setIssuer("");
406 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
407 configNameAttributeValue4.setDataType(STRING_DATATYPE);
408 configNameAttributeValue4.getContent().add(Integer.toString(version));
409 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
411 advice.getAttributeAssignmentExpression().add(assignment4);
413 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
414 assignment5.setAttributeId("matching:" + ONAPID);
415 assignment5.setCategory(CATEGORY_RESOURCE);
416 assignment5.setIssuer("");
418 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
419 configNameAttributeValue5.setDataType(STRING_DATATYPE);
420 configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
421 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
423 advice.getAttributeAssignmentExpression().add(assignment5);
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 Map<String, String> matchMap = getMatchMap();
438 if (matchMap == null || matchMap.isEmpty()) {
439 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
440 assignment6.setAttributeId("matching:" + CONFIGID);
441 assignment6.setCategory(CATEGORY_RESOURCE);
442 assignment6.setIssuer("");
444 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
445 configNameAttributeValue6.setDataType(STRING_DATATYPE);
446 configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
447 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
449 advice.getAttributeAssignmentExpression().add(assignment6);
451 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
452 assignment8.setAttributeId("matching:uuid");
453 assignment8.setCategory(CATEGORY_RESOURCE);
454 assignment8.setIssuer("");
456 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
457 configNameAttributeValue8.setDataType(STRING_DATATYPE);
458 configNameAttributeValue8.getContent().add(policyAdapter.getUuid());
459 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
461 advice.getAttributeAssignmentExpression().add(assignment8);
463 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
464 assignment9.setAttributeId("matching:Location");
465 assignment9.setCategory(CATEGORY_RESOURCE);
466 assignment9.setIssuer("");
468 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
469 configNameAttributeValue9.setDataType(STRING_DATATYPE);
470 configNameAttributeValue9.getContent().add(policyAdapter.getLocation());
471 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
473 advice.getAttributeAssignmentExpression().add(assignment9);
475 for (Entry<String, String> matchValue : matchMap.entrySet()) {
476 String value = matchValue.getValue();
477 String key = matchValue.getKey().trim();
478 if (value.contains("matching-true")) {
479 if (mapAttribute.containsKey(key)) {
480 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
481 assignment9.setAttributeId("matching:" + key);
482 assignment9.setCategory(CATEGORY_RESOURCE);
483 assignment9.setIssuer("");
485 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
486 configNameAttributeValue9.setDataType(STRING_DATATYPE);
487 configNameAttributeValue9.getContent().add(mapAttribute.get(key));
488 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
490 advice.getAttributeAssignmentExpression().add(assignment9);
497 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
498 assignment10.setAttributeId("Priority");
499 assignment10.setCategory(CATEGORY_RESOURCE);
500 assignment10.setIssuer("");
502 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
503 configNameAttributeValue10.setDataType(STRING_DATATYPE);
504 configNameAttributeValue10.getContent().add(policyAdapter.getPriority());
505 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
507 advice.getAttributeAssignmentExpression().add(assignment10);
510 AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
511 assignment11.setAttributeId("RiskType");
512 assignment11.setCategory(CATEGORY_RESOURCE);
513 assignment11.setIssuer("");
515 AttributeValueType configNameAttributeValue11 = new AttributeValueType();
516 configNameAttributeValue11.setDataType(STRING_DATATYPE);
517 configNameAttributeValue11.getContent().add(policyAdapter.getRiskType());
518 assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11));
520 advice.getAttributeAssignmentExpression().add(assignment11);
522 AttributeAssignmentExpressionType assignment12 = new AttributeAssignmentExpressionType();
523 assignment12.setAttributeId("RiskLevel");
524 assignment12.setCategory(CATEGORY_RESOURCE);
525 assignment12.setIssuer("");
527 AttributeValueType configNameAttributeValue12 = new AttributeValueType();
528 configNameAttributeValue12.setDataType(STRING_DATATYPE);
529 configNameAttributeValue12.getContent().add(policyAdapter.getRiskLevel());
530 assignment12.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue12));
532 advice.getAttributeAssignmentExpression().add(assignment12);
534 AttributeAssignmentExpressionType assignment13 = new AttributeAssignmentExpressionType();
535 assignment13.setAttributeId("guard");
536 assignment13.setCategory(CATEGORY_RESOURCE);
537 assignment13.setIssuer("");
539 AttributeValueType configNameAttributeValue13 = new AttributeValueType();
540 configNameAttributeValue13.setDataType(STRING_DATATYPE);
541 configNameAttributeValue13.getContent().add(policyAdapter.getGuard());
542 assignment13.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue13));
544 advice.getAttributeAssignmentExpression().add(assignment13);
546 AttributeAssignmentExpressionType assignment14 = new AttributeAssignmentExpressionType();
547 assignment14.setAttributeId("TTLDate");
548 assignment14.setCategory(CATEGORY_RESOURCE);
549 assignment14.setIssuer("");
551 AttributeValueType configNameAttributeValue14 = new AttributeValueType();
552 configNameAttributeValue14.setDataType(STRING_DATATYPE);
553 configNameAttributeValue14.getContent().add(policyAdapter.getTtlDate());
554 assignment14.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue14));
556 advice.getAttributeAssignmentExpression().add(assignment14);
558 advices.getAdviceExpression().add(advice);
563 public Object getCorrectPolicyDataObject() {
564 return policyAdapter.getPolicyData();