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.PrintWriter;
26 import java.net.URISyntaxException;
27 import java.nio.file.Path;
28 import java.nio.file.Paths;
29 import java.util.HashMap;
30 import java.util.Iterator;
31 import java.util.List;
33 import java.util.Map.Entry;
35 import org.apache.commons.io.FilenameUtils;
36 import org.apache.commons.lang.StringUtils;
37 import org.onap.policy.common.logging.eelf.MessageCodes;
38 import org.onap.policy.common.logging.eelf.PolicyLogger;
39 import org.onap.policy.common.logging.flexlogger.FlexLogger;
40 import org.onap.policy.common.logging.flexlogger.Logger;
41 import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl;
42 import org.onap.policy.rest.adapter.PolicyRestAdapter;
43 import org.onap.policy.rest.jpa.MicroServiceModels;
45 import com.att.research.xacml.std.IdentifierImpl;
46 import com.fasterxml.jackson.databind.JsonNode;
47 import com.fasterxml.jackson.databind.ObjectMapper;
48 import com.google.common.base.Splitter;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
51 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
52 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
53 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
54 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
55 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
56 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
57 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
58 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
59 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
60 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
61 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
62 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
64 public class MicroServiceConfigPolicy extends Policy {
66 private static final Logger LOGGER = FlexLogger.getLogger(MicroServiceConfigPolicy.class);
68 private static Map<String, String> mapAttribute = new HashMap<>();
69 private static Map<String, String> mapMatch = new HashMap<>();
71 private static synchronized Map<String, String> getMatchMap () {
75 private static synchronized void setMatchMap(Map<String, String> mm) {
79 public MicroServiceConfigPolicy() {
83 public MicroServiceConfigPolicy(PolicyRestAdapter policyAdapter){
84 this.policyAdapter = policyAdapter;
87 //save configuration of the policy based on the policyname
88 private void saveConfigurations(String policyName, String jsonBody) {
90 if(policyName.endsWith(".xml")){
91 policyName = policyName.replace(".xml", "");
93 PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName +".json");
94 out.println(jsonBody);
96 } catch (Exception e) {
97 LOGGER.error("Exception Occured While writing Configuration data"+e);
103 public Map<String, String> savePolicies() throws Exception {
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 Exception{
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 JsonNode rootNode = mapper.readTree(policyAdapter.getJsonBody());
176 String matching = null;
178 if (policyAdapter.getTtlDate()==null){
179 policyAdapter.setTtlDate("NA");
181 if (policyAdapter.getServiceType().contains("-v")){
182 matching = getValueFromDictionary(policyAdapter.getServiceType());
184 String jsonVersion = StringUtils.replaceEach(rootNode.get("version").toString(), new String[]{"\""}, new String[]{""});
185 matching = getValueFromDictionary(policyAdapter.getServiceType() + "-v" + jsonVersion);
188 Map<String, String> matchMap = null;
189 if (matching != null && !matching.isEmpty()){
190 matchMap = Splitter.on(",").withKeyValueSeparator("=").split(matching);
191 setMatchMap(matchMap);
192 if(policyAdapter.getJsonBody() != null){
193 pullMatchValue(rootNode);
197 // Match for policyName
198 allOfOne.getMatch().add(createMatch("PolicyName", name));
200 AllOfType allOf = new AllOfType();
202 // Adding the matches to AllOfType element Match for Onap
203 allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
204 if (matchMap==null || matchMap.isEmpty()){
205 // Match for ConfigName
206 allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
208 allOf.getMatch().add(createDynamicMatch("service", policyAdapter.getServiceType()));
210 allOf.getMatch().add(createDynamicMatch("uuid", policyAdapter.getUuid()));
211 // Match for location
212 allOf.getMatch().add(createDynamicMatch("location", policyAdapter.getLocation()));
214 for (Entry<String, String> matchValue : matchMap.entrySet()){
215 String value = matchValue.getValue();
216 String key = matchValue.getKey().trim();
217 if (value.contains("matching-true")){
218 if (mapAttribute.containsKey(key)){
219 allOf.getMatch().add(createDynamicMatch(key, mapAttribute.get(key)));
224 // Match for riskType
225 allOf.getMatch().add(
226 createDynamicMatch("RiskType", policyAdapter.getRiskType()));
227 // Match for riskLevel
228 allOf.getMatch().add(
229 createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
230 // Match for riskguard
231 allOf.getMatch().add(
232 createDynamicMatch("guard", policyAdapter.getGuard()));
234 allOf.getMatch().add(
235 createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
237 AnyOfType anyOf = new AnyOfType();
238 anyOf.getAllOf().add(allOfOne);
239 anyOf.getAllOf().add(allOf);
241 TargetType target = new TargetType();
242 ((TargetType) target).getAnyOf().add(anyOf);
244 // Adding the target to the policy element
245 configPolicy.setTarget((TargetType) target);
247 RuleType rule = new RuleType();
248 rule.setRuleId(policyAdapter.getRuleID());
250 rule.setEffect(EffectType.PERMIT);
252 // Create Target in Rule
253 AllOfType allOfInRule = new AllOfType();
255 // Creating match for ACCESS in rule target
256 MatchType accessMatch = new MatchType();
257 AttributeValueType accessAttributeValue = new AttributeValueType();
258 accessAttributeValue.setDataType(STRING_DATATYPE);
259 accessAttributeValue.getContent().add("ACCESS");
260 accessMatch.setAttributeValue(accessAttributeValue);
261 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
262 URI accessURI = null;
264 accessURI = new URI(ACTION_ID);
265 } catch (URISyntaxException e) {
266 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy", "Exception creating ACCESS URI");
268 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
269 accessAttributeDesignator.setDataType(STRING_DATATYPE);
270 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
271 accessMatch.setAttributeDesignator(accessAttributeDesignator);
272 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
274 // Creating Config Match in rule Target
275 MatchType configMatch = new MatchType();
276 AttributeValueType configAttributeValue = new AttributeValueType();
277 configAttributeValue.setDataType(STRING_DATATYPE);
278 configAttributeValue.getContent().add("Config");
279 configMatch.setAttributeValue(configAttributeValue);
280 AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
281 URI configURI = null;
283 configURI = new URI(RESOURCE_ID);
284 } catch (URISyntaxException e) {
285 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy", "Exception creating Config URI");
287 configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
288 configAttributeDesignator.setDataType(STRING_DATATYPE);
289 configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
290 configMatch.setAttributeDesignator(configAttributeDesignator);
291 configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
293 allOfInRule.getMatch().add(accessMatch);
294 allOfInRule.getMatch().add(configMatch);
296 AnyOfType anyOfInRule = new AnyOfType();
297 anyOfInRule.getAllOf().add(allOfInRule);
299 TargetType targetInRule = new TargetType();
300 targetInRule.getAnyOf().add(anyOfInRule);
302 rule.setTarget(targetInRule);
303 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
305 configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
306 policyAdapter.setPolicyData(configPolicy);
309 PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
311 setPreparedToSave(true);
315 private void pullMatchValue(JsonNode rootNode) {
316 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
317 String newValue = null;
318 while (fieldsIterator.hasNext()) {
319 Map.Entry<String, JsonNode> field = fieldsIterator.next();
320 final String key = field.getKey();
321 final JsonNode value = field.getValue();
322 if (value.isContainerNode() && !value.isArray()) {
323 pullMatchValue(value); // RECURSIVE CALL
325 newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, 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 = dbConnection.getDataById(MicroServiceModels.class, "modelName:version", modelName+":"+modelVersion);
339 if(result != null && !result.isEmpty()){
340 MicroServiceModels model = (MicroServiceModels) result.get(0);
341 ruleTemplate = model.getAnnotation();
346 // Data required for Advice part is setting here.
347 private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
348 AdviceExpressionsType advices = new AdviceExpressionsType();
349 AdviceExpressionType advice = new AdviceExpressionType();
350 advice.setAdviceId("MSID");
351 advice.setAppliesTo(EffectType.PERMIT);
353 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
354 assignment1.setAttributeId("type");
355 assignment1.setCategory(CATEGORY_RESOURCE);
356 assignment1.setIssuer("");
358 AttributeValueType configNameAttributeValue = new AttributeValueType();
359 configNameAttributeValue.setDataType(STRING_DATATYPE);
360 configNameAttributeValue.getContent().add("Configuration");
361 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
363 advice.getAttributeAssignmentExpression().add(assignment1);
364 // For Config file Url if configurations are provided.
365 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
366 assignment2.setAttributeId("URLID");
367 assignment2.setCategory(CATEGORY_RESOURCE);
368 assignment2.setIssuer("");
370 AttributeValueType AttributeValue = new AttributeValueType();
371 AttributeValue.setDataType(URI_DATATYPE);
373 if(policyName.endsWith(".xml")){
374 configName = policyName.replace(".xml", "");
376 configName = policyName;
378 String content = CONFIG_URL +"/Config/" + configName + ".json";
379 AttributeValue.getContent().add(content);
380 assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
382 advice.getAttributeAssignmentExpression().add(assignment2);
383 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
384 assignment3.setAttributeId("PolicyName");
385 assignment3.setCategory(CATEGORY_RESOURCE);
386 assignment3.setIssuer("");
388 AttributeValueType attributeValue3 = new AttributeValueType();
389 attributeValue3.setDataType(STRING_DATATYPE);
390 fileName = FilenameUtils.removeExtension(fileName);
391 fileName = fileName + ".xml";
392 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
393 if ((name == null) || (name.equals(""))) {
394 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
396 attributeValue3.getContent().add(name);
397 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
398 advice.getAttributeAssignmentExpression().add(assignment3);
400 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
401 assignment4.setAttributeId("VersionNumber");
402 assignment4.setCategory(CATEGORY_RESOURCE);
403 assignment4.setIssuer("");
405 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
406 configNameAttributeValue4.setDataType(STRING_DATATYPE);
407 configNameAttributeValue4.getContent().add(Integer.toString(version));
408 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
410 advice.getAttributeAssignmentExpression().add(assignment4);
412 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
413 assignment5.setAttributeId("matching:" + ONAPID);
414 assignment5.setCategory(CATEGORY_RESOURCE);
415 assignment5.setIssuer("");
417 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
418 configNameAttributeValue5.setDataType(STRING_DATATYPE);
419 configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
420 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
422 advice.getAttributeAssignmentExpression().add(assignment5);
424 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
425 assignment7.setAttributeId("matching:service");
426 assignment7.setCategory(CATEGORY_RESOURCE);
427 assignment7.setIssuer("");
429 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
430 configNameAttributeValue7.setDataType(STRING_DATATYPE);
431 configNameAttributeValue7.getContent().add(policyAdapter.getServiceType());
432 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
434 advice.getAttributeAssignmentExpression().add(assignment7);
436 Map<String, String> matchMap = getMatchMap();
437 if (matchMap==null || matchMap.isEmpty()){
438 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
439 assignment6.setAttributeId("matching:" + CONFIGID);
440 assignment6.setCategory(CATEGORY_RESOURCE);
441 assignment6.setIssuer("");
443 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
444 configNameAttributeValue6.setDataType(STRING_DATATYPE);
445 configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
446 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
448 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();