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) {
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);
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") == false) {
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 // Match for ConfigName
208 allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
210 allOf.getMatch().add(createDynamicMatch("service", policyAdapter.getServiceType()));
212 allOf.getMatch().add(createDynamicMatch("uuid", policyAdapter.getUuid()));
213 // Match for location
214 allOf.getMatch().add(createDynamicMatch("location", policyAdapter.getLocation()));
216 for (Entry<String, String> matchValue : matchMap.entrySet()){
217 String value = matchValue.getValue();
218 String key = matchValue.getKey().trim();
219 if (value.contains("matching-true")){
220 if (mapAttribute.containsKey(key)){
221 allOf.getMatch().add(createDynamicMatch(key, mapAttribute.get(key)));
226 // Match for riskType
227 allOf.getMatch().add(
228 createDynamicMatch("RiskType", policyAdapter.getRiskType()));
229 // Match for riskLevel
230 allOf.getMatch().add(
231 createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
232 // Match for riskguard
233 allOf.getMatch().add(
234 createDynamicMatch("guard", policyAdapter.getGuard()));
236 allOf.getMatch().add(
237 createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
239 AnyOfType anyOf = new AnyOfType();
240 anyOf.getAllOf().add(allOfOne);
241 anyOf.getAllOf().add(allOf);
243 TargetType target = new TargetType();
244 ((TargetType) target).getAnyOf().add(anyOf);
246 // Adding the target to the policy element
247 configPolicy.setTarget((TargetType) target);
249 RuleType rule = new RuleType();
250 rule.setRuleId(policyAdapter.getRuleID());
252 rule.setEffect(EffectType.PERMIT);
254 // Create Target in Rule
255 AllOfType allOfInRule = new AllOfType();
257 // Creating match for ACCESS in rule target
258 MatchType accessMatch = new MatchType();
259 AttributeValueType accessAttributeValue = new AttributeValueType();
260 accessAttributeValue.setDataType(STRING_DATATYPE);
261 accessAttributeValue.getContent().add("ACCESS");
262 accessMatch.setAttributeValue(accessAttributeValue);
263 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
264 URI accessURI = null;
266 accessURI = new URI(ACTION_ID);
267 } catch (URISyntaxException e) {
268 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy", "Exception creating ACCESS URI");
270 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
271 accessAttributeDesignator.setDataType(STRING_DATATYPE);
272 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
273 accessMatch.setAttributeDesignator(accessAttributeDesignator);
274 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
276 // Creating Config Match in rule Target
277 MatchType configMatch = new MatchType();
278 AttributeValueType configAttributeValue = new AttributeValueType();
279 configAttributeValue.setDataType(STRING_DATATYPE);
280 configAttributeValue.getContent().add("Config");
281 configMatch.setAttributeValue(configAttributeValue);
282 AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
283 URI configURI = null;
285 configURI = new URI(RESOURCE_ID);
286 } catch (URISyntaxException e) {
287 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy", "Exception creating Config URI");
289 configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
290 configAttributeDesignator.setDataType(STRING_DATATYPE);
291 configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
292 configMatch.setAttributeDesignator(configAttributeDesignator);
293 configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
295 allOfInRule.getMatch().add(accessMatch);
296 allOfInRule.getMatch().add(configMatch);
298 AnyOfType anyOfInRule = new AnyOfType();
299 anyOfInRule.getAllOf().add(allOfInRule);
301 TargetType targetInRule = new TargetType();
302 targetInRule.getAnyOf().add(anyOfInRule);
304 rule.setTarget(targetInRule);
305 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
307 configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
308 policyAdapter.setPolicyData(configPolicy);
311 PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
313 setPreparedToSave(true);
317 private void pullMatchValue(JsonNode rootNode) {
318 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
319 String newValue = null;
320 while (fieldsIterator.hasNext()) {
321 Map.Entry<String, JsonNode> field = fieldsIterator.next();
322 final String key = field.getKey();
323 final JsonNode value = field.getValue();
324 if (value.isContainerNode() && !value.isArray()) {
325 pullMatchValue(value); // RECURSIVE CALL
327 newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, new String[]{"", "", ""});
328 mapAttribute.put(key, newValue);
334 private String getValueFromDictionary(String service){
335 String ruleTemplate=null;
336 String modelName = service.split("-v")[0];
337 String modelVersion = service.split("-v")[1];
339 CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
340 List<Object> result = dbConnection.getDataById(MicroServiceModels.class, "modelName:version", modelName+":"+modelVersion);
341 if(result != null && !result.isEmpty()){
342 MicroServiceModels model = (MicroServiceModels) result.get(0);
343 ruleTemplate = model.getAnnotation();
348 // Data required for Advice part is setting here.
349 private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
350 AdviceExpressionsType advices = new AdviceExpressionsType();
351 AdviceExpressionType advice = new AdviceExpressionType();
352 advice.setAdviceId("MSID");
353 advice.setAppliesTo(EffectType.PERMIT);
355 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
356 assignment1.setAttributeId("type");
357 assignment1.setCategory(CATEGORY_RESOURCE);
358 assignment1.setIssuer("");
360 AttributeValueType configNameAttributeValue = new AttributeValueType();
361 configNameAttributeValue.setDataType(STRING_DATATYPE);
362 configNameAttributeValue.getContent().add("Configuration");
363 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
365 advice.getAttributeAssignmentExpression().add(assignment1);
366 // For Config file Url if configurations are provided.
367 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
368 assignment2.setAttributeId("URLID");
369 assignment2.setCategory(CATEGORY_RESOURCE);
370 assignment2.setIssuer("");
372 AttributeValueType AttributeValue = new AttributeValueType();
373 AttributeValue.setDataType(URI_DATATYPE);
375 if(policyName.endsWith(".xml")){
376 configName = policyName.replace(".xml", "");
378 configName = policyName;
380 String content = CONFIG_URL +"/Config/" + configName + ".json";
381 AttributeValue.getContent().add(content);
382 assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
384 advice.getAttributeAssignmentExpression().add(assignment2);
385 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
386 assignment3.setAttributeId("PolicyName");
387 assignment3.setCategory(CATEGORY_RESOURCE);
388 assignment3.setIssuer("");
390 AttributeValueType attributeValue3 = new AttributeValueType();
391 attributeValue3.setDataType(STRING_DATATYPE);
392 fileName = FilenameUtils.removeExtension(fileName);
393 fileName = fileName + ".xml";
394 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
395 if ((name == null) || (name.equals(""))) {
396 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
398 attributeValue3.getContent().add(name);
399 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
400 advice.getAttributeAssignmentExpression().add(assignment3);
402 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
403 assignment4.setAttributeId("VersionNumber");
404 assignment4.setCategory(CATEGORY_RESOURCE);
405 assignment4.setIssuer("");
407 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
408 configNameAttributeValue4.setDataType(STRING_DATATYPE);
409 configNameAttributeValue4.getContent().add(Integer.toString(version));
410 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
412 advice.getAttributeAssignmentExpression().add(assignment4);
414 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
415 assignment5.setAttributeId("matching:" + ONAPID);
416 assignment5.setCategory(CATEGORY_RESOURCE);
417 assignment5.setIssuer("");
419 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
420 configNameAttributeValue5.setDataType(STRING_DATATYPE);
421 configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
422 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
424 advice.getAttributeAssignmentExpression().add(assignment5);
426 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
427 assignment7.setAttributeId("matching:service");
428 assignment7.setCategory(CATEGORY_RESOURCE);
429 assignment7.setIssuer("");
431 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
432 configNameAttributeValue7.setDataType(STRING_DATATYPE);
433 configNameAttributeValue7.getContent().add(policyAdapter.getServiceType());
434 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
436 advice.getAttributeAssignmentExpression().add(assignment7);
438 Map<String, String> matchMap = getMatchMap();
439 if (matchMap==null || matchMap.isEmpty()){
440 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
441 assignment6.setAttributeId("matching:" + CONFIGID);
442 assignment6.setCategory(CATEGORY_RESOURCE);
443 assignment6.setIssuer("");
445 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
446 configNameAttributeValue6.setDataType(STRING_DATATYPE);
447 configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
448 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
450 advice.getAttributeAssignmentExpression().add(assignment6);
453 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
454 assignment8.setAttributeId("matching:uuid");
455 assignment8.setCategory(CATEGORY_RESOURCE);
456 assignment8.setIssuer("");
458 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
459 configNameAttributeValue8.setDataType(STRING_DATATYPE);
460 configNameAttributeValue8.getContent().add(policyAdapter.getUuid());
461 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
463 advice.getAttributeAssignmentExpression().add(assignment8);
465 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
466 assignment9.setAttributeId("matching:Location");
467 assignment9.setCategory(CATEGORY_RESOURCE);
468 assignment9.setIssuer("");
470 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
471 configNameAttributeValue9.setDataType(STRING_DATATYPE);
472 configNameAttributeValue9.getContent().add(policyAdapter.getLocation());
473 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
475 advice.getAttributeAssignmentExpression().add(assignment9);
477 for (Entry<String, String> matchValue : matchMap.entrySet()){
478 String value = matchValue.getValue();
479 String key = matchValue.getKey().trim();
480 if (value.contains("matching-true")){
481 if (mapAttribute.containsKey(key)){
482 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
483 assignment9.setAttributeId("matching:" + key);
484 assignment9.setCategory(CATEGORY_RESOURCE);
485 assignment9.setIssuer("");
487 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
488 configNameAttributeValue9.setDataType(STRING_DATATYPE);
489 configNameAttributeValue9.getContent().add(mapAttribute.get(key));
490 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
492 advice.getAttributeAssignmentExpression().add(assignment9);
499 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
500 assignment10.setAttributeId("Priority");
501 assignment10.setCategory(CATEGORY_RESOURCE);
502 assignment10.setIssuer("");
504 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
505 configNameAttributeValue10.setDataType(STRING_DATATYPE);
506 configNameAttributeValue10.getContent().add(policyAdapter.getPriority());
507 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
509 advice.getAttributeAssignmentExpression().add(assignment10);
512 AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
513 assignment11.setAttributeId("RiskType");
514 assignment11.setCategory(CATEGORY_RESOURCE);
515 assignment11.setIssuer("");
517 AttributeValueType configNameAttributeValue11 = new AttributeValueType();
518 configNameAttributeValue11.setDataType(STRING_DATATYPE);
519 configNameAttributeValue11.getContent().add(policyAdapter.getRiskType());
520 assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11));
522 advice.getAttributeAssignmentExpression().add(assignment11);
524 AttributeAssignmentExpressionType assignment12 = new AttributeAssignmentExpressionType();
525 assignment12.setAttributeId("RiskLevel");
526 assignment12.setCategory(CATEGORY_RESOURCE);
527 assignment12.setIssuer("");
529 AttributeValueType configNameAttributeValue12 = new AttributeValueType();
530 configNameAttributeValue12.setDataType(STRING_DATATYPE);
531 configNameAttributeValue12.getContent().add(policyAdapter.getRiskLevel());
532 assignment12.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue12));
534 advice.getAttributeAssignmentExpression().add(assignment12);
536 AttributeAssignmentExpressionType assignment13 = new AttributeAssignmentExpressionType();
537 assignment13.setAttributeId("guard");
538 assignment13.setCategory(CATEGORY_RESOURCE);
539 assignment13.setIssuer("");
541 AttributeValueType configNameAttributeValue13 = new AttributeValueType();
542 configNameAttributeValue13.setDataType(STRING_DATATYPE);
543 configNameAttributeValue13.getContent().add(policyAdapter.getGuard());
544 assignment13.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue13));
546 advice.getAttributeAssignmentExpression().add(assignment13);
548 AttributeAssignmentExpressionType assignment14 = new AttributeAssignmentExpressionType();
549 assignment14.setAttributeId("TTLDate");
550 assignment14.setCategory(CATEGORY_RESOURCE);
551 assignment14.setIssuer("");
553 AttributeValueType configNameAttributeValue14 = new AttributeValueType();
554 configNameAttributeValue14.setDataType(STRING_DATATYPE);
555 configNameAttributeValue14.getContent().add(policyAdapter.getTtlDate());
556 assignment14.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue14));
558 advice.getAttributeAssignmentExpression().add(assignment14);
560 advices.getAdviceExpression().add(advice);
565 public Object getCorrectPolicyDataObject() {
566 return policyAdapter.getPolicyData();