2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 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.MicroServiceModels;
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 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) {
92 if(policyName.endsWith(".xml")){
93 policyName = policyName.replace(".xml", "");
95 PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName +".json");
96 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") == false) {
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 // Match for ConfigName
210 allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
212 allOf.getMatch().add(createDynamicMatch("service", policyAdapter.getServiceType()));
214 allOf.getMatch().add(createDynamicMatch("uuid", policyAdapter.getUuid()));
215 // Match for location
216 allOf.getMatch().add(createDynamicMatch("location", policyAdapter.getLocation()));
218 for (Entry<String, String> matchValue : matchMap.entrySet()){
219 String value = matchValue.getValue();
220 String key = matchValue.getKey().trim();
221 if (value.contains("matching-true")){
222 if (mapAttribute.containsKey(key)){
223 allOf.getMatch().add(createDynamicMatch(key, mapAttribute.get(key)));
228 // Match for riskType
229 allOf.getMatch().add(
230 createDynamicMatch("RiskType", policyAdapter.getRiskType()));
231 // Match for riskLevel
232 allOf.getMatch().add(
233 createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
234 // Match for riskguard
235 allOf.getMatch().add(
236 createDynamicMatch("guard", policyAdapter.getGuard()));
238 allOf.getMatch().add(
239 createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
241 AnyOfType anyOf = new AnyOfType();
242 anyOf.getAllOf().add(allOfOne);
243 anyOf.getAllOf().add(allOf);
245 TargetType target = new TargetType();
246 ((TargetType) target).getAnyOf().add(anyOf);
248 // Adding the target to the policy element
249 configPolicy.setTarget((TargetType) target);
251 RuleType rule = new RuleType();
252 rule.setRuleId(policyAdapter.getRuleID());
254 rule.setEffect(EffectType.PERMIT);
256 // Create Target in Rule
257 AllOfType allOfInRule = new AllOfType();
259 // Creating match for ACCESS in rule target
260 MatchType accessMatch = new MatchType();
261 AttributeValueType accessAttributeValue = new AttributeValueType();
262 accessAttributeValue.setDataType(STRING_DATATYPE);
263 accessAttributeValue.getContent().add("ACCESS");
264 accessMatch.setAttributeValue(accessAttributeValue);
265 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
266 URI accessURI = null;
268 accessURI = new URI(ACTION_ID);
269 } catch (URISyntaxException e) {
270 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy", "Exception creating ACCESS URI");
272 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
273 accessAttributeDesignator.setDataType(STRING_DATATYPE);
274 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
275 accessMatch.setAttributeDesignator(accessAttributeDesignator);
276 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
278 // Creating Config Match in rule Target
279 MatchType configMatch = new MatchType();
280 AttributeValueType configAttributeValue = new AttributeValueType();
281 configAttributeValue.setDataType(STRING_DATATYPE);
282 configAttributeValue.getContent().add("Config");
283 configMatch.setAttributeValue(configAttributeValue);
284 AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
285 URI configURI = null;
287 configURI = new URI(RESOURCE_ID);
288 } catch (URISyntaxException e) {
289 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy", "Exception creating Config URI");
291 configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
292 configAttributeDesignator.setDataType(STRING_DATATYPE);
293 configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
294 configMatch.setAttributeDesignator(configAttributeDesignator);
295 configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
297 allOfInRule.getMatch().add(accessMatch);
298 allOfInRule.getMatch().add(configMatch);
300 AnyOfType anyOfInRule = new AnyOfType();
301 anyOfInRule.getAllOf().add(allOfInRule);
303 TargetType targetInRule = new TargetType();
304 targetInRule.getAnyOf().add(anyOfInRule);
306 rule.setTarget(targetInRule);
307 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
309 configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
310 policyAdapter.setPolicyData(configPolicy);
313 PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
315 setPreparedToSave(true);
319 private void pullMatchValue(JsonNode rootNode) {
320 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
321 String newValue = null;
322 while (fieldsIterator.hasNext()) {
323 Map.Entry<String, JsonNode> field = fieldsIterator.next();
324 final String key = field.getKey();
325 final JsonNode value = field.getValue();
326 if (value.isContainerNode() && !value.isArray()) {
327 pullMatchValue(value); // RECURSIVE CALL
329 newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, new String[]{"", "", ""});
330 mapAttribute.put(key, newValue);
336 private String getValueFromDictionary(String service){
337 String ruleTemplate=null;
338 String modelName = service.split("-v")[0];
339 String modelVersion = service.split("-v")[1];
341 CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
342 List<Object> result = dbConnection.getDataById(MicroServiceModels.class, "modelName:version", modelName+":"+modelVersion);
343 if(result != null && !result.isEmpty()){
344 MicroServiceModels model = (MicroServiceModels) result.get(0);
345 ruleTemplate = model.getAnnotation();
350 // Data required for Advice part is setting here.
351 private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
352 AdviceExpressionsType advices = new AdviceExpressionsType();
353 AdviceExpressionType advice = new AdviceExpressionType();
354 advice.setAdviceId("MSID");
355 advice.setAppliesTo(EffectType.PERMIT);
357 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
358 assignment1.setAttributeId("type");
359 assignment1.setCategory(CATEGORY_RESOURCE);
360 assignment1.setIssuer("");
362 AttributeValueType configNameAttributeValue = new AttributeValueType();
363 configNameAttributeValue.setDataType(STRING_DATATYPE);
364 configNameAttributeValue.getContent().add("Configuration");
365 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
367 advice.getAttributeAssignmentExpression().add(assignment1);
368 // For Config file Url if configurations are provided.
369 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
370 assignment2.setAttributeId("URLID");
371 assignment2.setCategory(CATEGORY_RESOURCE);
372 assignment2.setIssuer("");
374 AttributeValueType AttributeValue = new AttributeValueType();
375 AttributeValue.setDataType(URI_DATATYPE);
377 if(policyName.endsWith(".xml")){
378 configName = policyName.replace(".xml", "");
380 configName = policyName;
382 String content = CONFIG_URL +"/Config/" + configName + ".json";
383 AttributeValue.getContent().add(content);
384 assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
386 advice.getAttributeAssignmentExpression().add(assignment2);
387 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
388 assignment3.setAttributeId("PolicyName");
389 assignment3.setCategory(CATEGORY_RESOURCE);
390 assignment3.setIssuer("");
392 AttributeValueType attributeValue3 = new AttributeValueType();
393 attributeValue3.setDataType(STRING_DATATYPE);
394 fileName = FilenameUtils.removeExtension(fileName);
395 fileName = fileName + ".xml";
396 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
397 if ((name == null) || (name.equals(""))) {
398 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
400 attributeValue3.getContent().add(name);
401 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
402 advice.getAttributeAssignmentExpression().add(assignment3);
404 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
405 assignment4.setAttributeId("VersionNumber");
406 assignment4.setCategory(CATEGORY_RESOURCE);
407 assignment4.setIssuer("");
409 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
410 configNameAttributeValue4.setDataType(STRING_DATATYPE);
411 configNameAttributeValue4.getContent().add(Integer.toString(version));
412 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
414 advice.getAttributeAssignmentExpression().add(assignment4);
416 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
417 assignment5.setAttributeId("matching:" + ONAPID);
418 assignment5.setCategory(CATEGORY_RESOURCE);
419 assignment5.setIssuer("");
421 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
422 configNameAttributeValue5.setDataType(STRING_DATATYPE);
423 configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
424 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
426 advice.getAttributeAssignmentExpression().add(assignment5);
428 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
429 assignment7.setAttributeId("matching:service");
430 assignment7.setCategory(CATEGORY_RESOURCE);
431 assignment7.setIssuer("");
433 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
434 configNameAttributeValue7.setDataType(STRING_DATATYPE);
435 configNameAttributeValue7.getContent().add(policyAdapter.getServiceType());
436 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
438 advice.getAttributeAssignmentExpression().add(assignment7);
440 Map<String, String> matchMap = getMatchMap();
441 if (matchMap==null || matchMap.isEmpty()){
442 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
443 assignment6.setAttributeId("matching:" + CONFIGID);
444 assignment6.setCategory(CATEGORY_RESOURCE);
445 assignment6.setIssuer("");
447 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
448 configNameAttributeValue6.setDataType(STRING_DATATYPE);
449 configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
450 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
452 advice.getAttributeAssignmentExpression().add(assignment6);
455 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
456 assignment8.setAttributeId("matching:uuid");
457 assignment8.setCategory(CATEGORY_RESOURCE);
458 assignment8.setIssuer("");
460 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
461 configNameAttributeValue8.setDataType(STRING_DATATYPE);
462 configNameAttributeValue8.getContent().add(policyAdapter.getUuid());
463 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
465 advice.getAttributeAssignmentExpression().add(assignment8);
467 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
468 assignment9.setAttributeId("matching:Location");
469 assignment9.setCategory(CATEGORY_RESOURCE);
470 assignment9.setIssuer("");
472 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
473 configNameAttributeValue9.setDataType(STRING_DATATYPE);
474 configNameAttributeValue9.getContent().add(policyAdapter.getLocation());
475 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
477 advice.getAttributeAssignmentExpression().add(assignment9);
479 for (Entry<String, String> matchValue : matchMap.entrySet()){
480 String value = matchValue.getValue();
481 String key = matchValue.getKey().trim();
482 if (value.contains("matching-true")){
483 if (mapAttribute.containsKey(key)){
484 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
485 assignment9.setAttributeId("matching:" + key);
486 assignment9.setCategory(CATEGORY_RESOURCE);
487 assignment9.setIssuer("");
489 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
490 configNameAttributeValue9.setDataType(STRING_DATATYPE);
491 configNameAttributeValue9.getContent().add(mapAttribute.get(key));
492 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
494 advice.getAttributeAssignmentExpression().add(assignment9);
501 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
502 assignment10.setAttributeId("Priority");
503 assignment10.setCategory(CATEGORY_RESOURCE);
504 assignment10.setIssuer("");
506 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
507 configNameAttributeValue10.setDataType(STRING_DATATYPE);
508 configNameAttributeValue10.getContent().add(policyAdapter.getPriority());
509 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
511 advice.getAttributeAssignmentExpression().add(assignment10);
514 AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
515 assignment11.setAttributeId("RiskType");
516 assignment11.setCategory(CATEGORY_RESOURCE);
517 assignment11.setIssuer("");
519 AttributeValueType configNameAttributeValue11 = new AttributeValueType();
520 configNameAttributeValue11.setDataType(STRING_DATATYPE);
521 configNameAttributeValue11.getContent().add(policyAdapter.getRiskType());
522 assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11));
524 advice.getAttributeAssignmentExpression().add(assignment11);
526 AttributeAssignmentExpressionType assignment12 = new AttributeAssignmentExpressionType();
527 assignment12.setAttributeId("RiskLevel");
528 assignment12.setCategory(CATEGORY_RESOURCE);
529 assignment12.setIssuer("");
531 AttributeValueType configNameAttributeValue12 = new AttributeValueType();
532 configNameAttributeValue12.setDataType(STRING_DATATYPE);
533 configNameAttributeValue12.getContent().add(policyAdapter.getRiskLevel());
534 assignment12.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue12));
536 advice.getAttributeAssignmentExpression().add(assignment12);
538 AttributeAssignmentExpressionType assignment13 = new AttributeAssignmentExpressionType();
539 assignment13.setAttributeId("guard");
540 assignment13.setCategory(CATEGORY_RESOURCE);
541 assignment13.setIssuer("");
543 AttributeValueType configNameAttributeValue13 = new AttributeValueType();
544 configNameAttributeValue13.setDataType(STRING_DATATYPE);
545 configNameAttributeValue13.getContent().add(policyAdapter.getGuard());
546 assignment13.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue13));
548 advice.getAttributeAssignmentExpression().add(assignment13);
550 AttributeAssignmentExpressionType assignment14 = new AttributeAssignmentExpressionType();
551 assignment14.setAttributeId("TTLDate");
552 assignment14.setCategory(CATEGORY_RESOURCE);
553 assignment14.setIssuer("");
555 AttributeValueType configNameAttributeValue14 = new AttributeValueType();
556 configNameAttributeValue14.setDataType(STRING_DATATYPE);
557 configNameAttributeValue14.getContent().add(policyAdapter.getTtlDate());
558 assignment14.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue14));
560 advice.getAttributeAssignmentExpression().add(assignment14);
562 advices.getAdviceExpression().add(advice);
567 public Object getCorrectPolicyDataObject() {
568 return policyAdapter.getPolicyData();