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> matchMap = new HashMap<>();
71 public MicroServiceConfigPolicy() {
75 public MicroServiceConfigPolicy(PolicyRestAdapter policyAdapter){
76 this.policyAdapter = policyAdapter;
79 //save configuration of the policy based on the policyname
80 private void saveConfigurations(String policyName, String jsonBody) {
82 if(policyName.endsWith(".xml")){
83 policyName = policyName.replace(".xml", "");
85 PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName +".json");
86 out.println(jsonBody);
88 } catch (Exception e) {
89 LOGGER.error("Exception Occured While writing Configuration data"+e);
95 public Map<String, String> savePolicies() throws Exception {
97 Map<String, String> successMap = new HashMap<>();
99 successMap.put("EXISTS", "This Policy already exist on the PAP");
103 if(!isPreparedToSave()){
104 //Prep and configure the policy for saving
108 // Until here we prepared the data and here calling the method to create xml.
109 Path newPolicyPath = null;
110 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
112 successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject());
117 //This is the method for preparing the policy for saving. We have broken it out
118 //separately because the fully configured policy is used for multiple things
120 public boolean prepareToSave() throws Exception{
122 if(isPreparedToSave()){
123 //we have already done this
128 String policyID = policyAdapter.getPolicyID();
129 version = policyAdapter.getHighestVersion();
131 // Create the Instance for pojo, PolicyType object is used in marshalling.
132 if (policyAdapter.getPolicyType().equals("Config")) {
133 PolicyType policyConfig = new PolicyType();
135 policyConfig.setVersion(Integer.toString(version));
136 policyConfig.setPolicyId(policyID);
137 policyConfig.setTarget(new TargetType());
138 policyAdapter.setData(policyConfig);
140 policyName = policyAdapter.getNewFileName();
141 if (policyAdapter.getData() != null) {
142 // Save the Configurations file with the policy name with extention based on selection.
143 String jsonBody = policyAdapter.getJsonBody();
144 saveConfigurations(policyName, jsonBody);
146 // Make sure the filename ends with an extension
147 if (policyName.endsWith(".xml") == false) {
148 policyName = policyName + ".xml";
152 PolicyType configPolicy = (PolicyType) policyAdapter.getData();
154 configPolicy.setDescription(policyAdapter.getPolicyDescription());
156 configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
158 AllOfType allOfOne = new AllOfType();
159 String fileName = policyAdapter.getNewFileName();
160 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
161 if ((name == null) || (name.equals(""))) {
162 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
165 //setup values for pulling out matching attributes
166 ObjectMapper mapper = new ObjectMapper();
167 JsonNode rootNode = mapper.readTree(policyAdapter.getJsonBody());
168 String matching = null;
170 if (policyAdapter.getTtlDate()==null){
171 policyAdapter.setTtlDate("NA");
173 if (policyAdapter.getServiceType().contains("-v")){
174 matching = getValueFromDictionary(policyAdapter.getServiceType());
176 String jsonVersion = StringUtils.replaceEach(rootNode.get("version").toString(), new String[]{"\""}, new String[]{""});
177 matching = getValueFromDictionary(policyAdapter.getServiceType() + "-v" + jsonVersion);
180 if (matching != null && !matching.isEmpty()){
181 matchMap = Splitter.on(",").withKeyValueSeparator("=").split(matching);
182 if(policyAdapter.getJsonBody() != null){
183 pullMatchValue(rootNode);
187 // Match for policyName
188 allOfOne.getMatch().add(createMatch("PolicyName", name));
190 AllOfType allOf = new AllOfType();
192 // Adding the matches to AllOfType element Match for Onap
193 allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
194 if (matchMap==null || matchMap.isEmpty()){
195 // Match for ConfigName
196 allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
198 allOf.getMatch().add(createDynamicMatch("service", policyAdapter.getServiceType()));
200 allOf.getMatch().add(createDynamicMatch("uuid", policyAdapter.getUuid()));
201 // Match for location
202 allOf.getMatch().add(createDynamicMatch("location", policyAdapter.getLocation()));
204 for (Entry<String, String> matchValue : matchMap.entrySet()){
205 String value = matchValue.getValue();
206 String key = matchValue.getKey().trim();
207 if (value.contains("matching-true")){
208 if (mapAttribute.containsKey(key)){
209 allOf.getMatch().add(createDynamicMatch(key, mapAttribute.get(key)));
214 // Match for riskType
215 allOf.getMatch().add(
216 createDynamicMatch("RiskType", policyAdapter.getRiskType()));
217 // Match for riskLevel
218 allOf.getMatch().add(
219 createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
220 // Match for riskguard
221 allOf.getMatch().add(
222 createDynamicMatch("guard", policyAdapter.getGuard()));
224 allOf.getMatch().add(
225 createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
227 AnyOfType anyOf = new AnyOfType();
228 anyOf.getAllOf().add(allOfOne);
229 anyOf.getAllOf().add(allOf);
231 TargetType target = new TargetType();
232 ((TargetType) target).getAnyOf().add(anyOf);
234 // Adding the target to the policy element
235 configPolicy.setTarget((TargetType) target);
237 RuleType rule = new RuleType();
238 rule.setRuleId(policyAdapter.getRuleID());
240 rule.setEffect(EffectType.PERMIT);
242 // Create Target in Rule
243 AllOfType allOfInRule = new AllOfType();
245 // Creating match for ACCESS in rule target
246 MatchType accessMatch = new MatchType();
247 AttributeValueType accessAttributeValue = new AttributeValueType();
248 accessAttributeValue.setDataType(STRING_DATATYPE);
249 accessAttributeValue.getContent().add("ACCESS");
250 accessMatch.setAttributeValue(accessAttributeValue);
251 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
252 URI accessURI = null;
254 accessURI = new URI(ACTION_ID);
255 } catch (URISyntaxException e) {
256 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy", "Exception creating ACCESS URI");
258 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
259 accessAttributeDesignator.setDataType(STRING_DATATYPE);
260 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
261 accessMatch.setAttributeDesignator(accessAttributeDesignator);
262 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
264 // Creating Config Match in rule Target
265 MatchType configMatch = new MatchType();
266 AttributeValueType configAttributeValue = new AttributeValueType();
267 configAttributeValue.setDataType(STRING_DATATYPE);
268 configAttributeValue.getContent().add("Config");
269 configMatch.setAttributeValue(configAttributeValue);
270 AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
271 URI configURI = null;
273 configURI = new URI(RESOURCE_ID);
274 } catch (URISyntaxException e) {
275 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy", "Exception creating Config URI");
277 configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
278 configAttributeDesignator.setDataType(STRING_DATATYPE);
279 configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
280 configMatch.setAttributeDesignator(configAttributeDesignator);
281 configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
283 allOfInRule.getMatch().add(accessMatch);
284 allOfInRule.getMatch().add(configMatch);
286 AnyOfType anyOfInRule = new AnyOfType();
287 anyOfInRule.getAllOf().add(allOfInRule);
289 TargetType targetInRule = new TargetType();
290 targetInRule.getAnyOf().add(anyOfInRule);
292 rule.setTarget(targetInRule);
293 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
295 configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
296 policyAdapter.setPolicyData(configPolicy);
299 PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
301 setPreparedToSave(true);
305 private void pullMatchValue(JsonNode rootNode) {
306 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
307 String newValue = null;
308 while (fieldsIterator.hasNext()) {
309 Map.Entry<String, JsonNode> field = fieldsIterator.next();
310 final String key = field.getKey();
311 final JsonNode value = field.getValue();
312 if (value.isContainerNode() && !value.isArray()) {
313 pullMatchValue(value); // RECURSIVE CALL
315 newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, new String[]{"", "", ""});
316 mapAttribute.put(key, newValue);
322 private String getValueFromDictionary(String service){
323 String ruleTemplate=null;
324 String modelName = service.split("-v")[0];
325 String modelVersion = service.split("-v")[1];
327 CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
328 List<Object> result = dbConnection.getDataById(MicroServiceModels.class, "modelName:version", modelName+":"+modelVersion);
329 if(result != null && !result.isEmpty()){
330 MicroServiceModels model = (MicroServiceModels) result.get(0);
331 ruleTemplate = model.getAnnotation();
336 // Data required for Advice part is setting here.
337 private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
338 AdviceExpressionsType advices = new AdviceExpressionsType();
339 AdviceExpressionType advice = new AdviceExpressionType();
340 advice.setAdviceId("MSID");
341 advice.setAppliesTo(EffectType.PERMIT);
343 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
344 assignment1.setAttributeId("type");
345 assignment1.setCategory(CATEGORY_RESOURCE);
346 assignment1.setIssuer("");
348 AttributeValueType configNameAttributeValue = new AttributeValueType();
349 configNameAttributeValue.setDataType(STRING_DATATYPE);
350 configNameAttributeValue.getContent().add("Configuration");
351 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
353 advice.getAttributeAssignmentExpression().add(assignment1);
354 // For Config file Url if configurations are provided.
355 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
356 assignment2.setAttributeId("URLID");
357 assignment2.setCategory(CATEGORY_RESOURCE);
358 assignment2.setIssuer("");
360 AttributeValueType AttributeValue = new AttributeValueType();
361 AttributeValue.setDataType(URI_DATATYPE);
363 if(policyName.endsWith(".xml")){
364 configName = policyName.replace(".xml", "");
366 configName = policyName;
368 String content = CONFIG_URL +"/Config/" + configName + ".json";
369 AttributeValue.getContent().add(content);
370 assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
372 advice.getAttributeAssignmentExpression().add(assignment2);
373 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
374 assignment3.setAttributeId("PolicyName");
375 assignment3.setCategory(CATEGORY_RESOURCE);
376 assignment3.setIssuer("");
378 AttributeValueType attributeValue3 = new AttributeValueType();
379 attributeValue3.setDataType(STRING_DATATYPE);
380 fileName = FilenameUtils.removeExtension(fileName);
381 fileName = fileName + ".xml";
382 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
383 if ((name == null) || (name.equals(""))) {
384 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
386 attributeValue3.getContent().add(name);
387 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
388 advice.getAttributeAssignmentExpression().add(assignment3);
390 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
391 assignment4.setAttributeId("VersionNumber");
392 assignment4.setCategory(CATEGORY_RESOURCE);
393 assignment4.setIssuer("");
395 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
396 configNameAttributeValue4.setDataType(STRING_DATATYPE);
397 configNameAttributeValue4.getContent().add(Integer.toString(version));
398 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
400 advice.getAttributeAssignmentExpression().add(assignment4);
402 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
403 assignment5.setAttributeId("matching:" + ONAPID);
404 assignment5.setCategory(CATEGORY_RESOURCE);
405 assignment5.setIssuer("");
407 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
408 configNameAttributeValue5.setDataType(STRING_DATATYPE);
409 configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
410 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
412 advice.getAttributeAssignmentExpression().add(assignment5);
414 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
415 assignment7.setAttributeId("matching:service");
416 assignment7.setCategory(CATEGORY_RESOURCE);
417 assignment7.setIssuer("");
419 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
420 configNameAttributeValue7.setDataType(STRING_DATATYPE);
421 configNameAttributeValue7.getContent().add(policyAdapter.getServiceType());
422 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
424 advice.getAttributeAssignmentExpression().add(assignment7);
426 if (matchMap==null || matchMap.isEmpty()){
427 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
428 assignment6.setAttributeId("matching:" + CONFIGID);
429 assignment6.setCategory(CATEGORY_RESOURCE);
430 assignment6.setIssuer("");
432 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
433 configNameAttributeValue6.setDataType(STRING_DATATYPE);
434 configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
435 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
437 advice.getAttributeAssignmentExpression().add(assignment6);
440 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
441 assignment8.setAttributeId("matching:uuid");
442 assignment8.setCategory(CATEGORY_RESOURCE);
443 assignment8.setIssuer("");
445 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
446 configNameAttributeValue8.setDataType(STRING_DATATYPE);
447 configNameAttributeValue8.getContent().add(policyAdapter.getUuid());
448 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
450 advice.getAttributeAssignmentExpression().add(assignment8);
452 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
453 assignment9.setAttributeId("matching:Location");
454 assignment9.setCategory(CATEGORY_RESOURCE);
455 assignment9.setIssuer("");
457 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
458 configNameAttributeValue9.setDataType(STRING_DATATYPE);
459 configNameAttributeValue9.getContent().add(policyAdapter.getLocation());
460 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
462 advice.getAttributeAssignmentExpression().add(assignment9);
464 for (Entry<String, String> matchValue : matchMap.entrySet()){
465 String value = matchValue.getValue();
466 String key = matchValue.getKey().trim();
467 if (value.contains("matching-true")){
468 if (mapAttribute.containsKey(key)){
469 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
470 assignment9.setAttributeId("matching:" + key);
471 assignment9.setCategory(CATEGORY_RESOURCE);
472 assignment9.setIssuer("");
474 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
475 configNameAttributeValue9.setDataType(STRING_DATATYPE);
476 configNameAttributeValue9.getContent().add(mapAttribute.get(key));
477 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
479 advice.getAttributeAssignmentExpression().add(assignment9);
486 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
487 assignment10.setAttributeId("Priority");
488 assignment10.setCategory(CATEGORY_RESOURCE);
489 assignment10.setIssuer("");
491 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
492 configNameAttributeValue10.setDataType(STRING_DATATYPE);
493 configNameAttributeValue10.getContent().add(policyAdapter.getPriority());
494 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
496 advice.getAttributeAssignmentExpression().add(assignment10);
499 AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
500 assignment11.setAttributeId("RiskType");
501 assignment11.setCategory(CATEGORY_RESOURCE);
502 assignment11.setIssuer("");
504 AttributeValueType configNameAttributeValue11 = new AttributeValueType();
505 configNameAttributeValue11.setDataType(STRING_DATATYPE);
506 configNameAttributeValue11.getContent().add(policyAdapter.getRiskType());
507 assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11));
509 advice.getAttributeAssignmentExpression().add(assignment11);
511 AttributeAssignmentExpressionType assignment12 = new AttributeAssignmentExpressionType();
512 assignment12.setAttributeId("RiskLevel");
513 assignment12.setCategory(CATEGORY_RESOURCE);
514 assignment12.setIssuer("");
516 AttributeValueType configNameAttributeValue12 = new AttributeValueType();
517 configNameAttributeValue12.setDataType(STRING_DATATYPE);
518 configNameAttributeValue12.getContent().add(policyAdapter.getRiskLevel());
519 assignment12.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue12));
521 advice.getAttributeAssignmentExpression().add(assignment12);
523 AttributeAssignmentExpressionType assignment13 = new AttributeAssignmentExpressionType();
524 assignment13.setAttributeId("guard");
525 assignment13.setCategory(CATEGORY_RESOURCE);
526 assignment13.setIssuer("");
528 AttributeValueType configNameAttributeValue13 = new AttributeValueType();
529 configNameAttributeValue13.setDataType(STRING_DATATYPE);
530 configNameAttributeValue13.getContent().add(policyAdapter.getGuard());
531 assignment13.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue13));
533 advice.getAttributeAssignmentExpression().add(assignment13);
535 AttributeAssignmentExpressionType assignment14 = new AttributeAssignmentExpressionType();
536 assignment14.setAttributeId("TTLDate");
537 assignment14.setCategory(CATEGORY_RESOURCE);
538 assignment14.setIssuer("");
540 AttributeValueType configNameAttributeValue14 = new AttributeValueType();
541 configNameAttributeValue14.setDataType(STRING_DATATYPE);
542 configNameAttributeValue14.getContent().add(policyAdapter.getTtlDate());
543 assignment14.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue14));
545 advice.getAttributeAssignmentExpression().add(assignment14);
547 advices.getAdviceExpression().add(advice);
552 public Object getCorrectPolicyDataObject() {
553 return policyAdapter.getPolicyData();