JUnit additions for PAP-REST, checkstyle fixes
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / rest / components / OptimizationConfigPolicy.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-PAP-REST
4  * ================================================================================
5  * Copyright (C) 2018-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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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=========================================================
19  */
20
21 package org.onap.policy.pap.xacml.rest.components;
22
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;
28 import java.io.File;
29 import java.io.IOException;
30 import java.io.PrintWriter;
31 import java.net.URI;
32 import java.net.URISyntaxException;
33 import java.nio.file.Path;
34 import java.nio.file.Paths;
35 import java.util.HashMap;
36 import java.util.Iterator;
37 import java.util.List;
38 import java.util.Map;
39 import java.util.Map.Entry;
40 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
41 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
42 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
43 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
44 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
51 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
52 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
53 import org.apache.commons.io.FilenameUtils;
54 import org.apache.commons.lang.StringUtils;
55 import org.onap.policy.common.logging.eelf.MessageCodes;
56 import org.onap.policy.common.logging.eelf.PolicyLogger;
57 import org.onap.policy.common.logging.flexlogger.FlexLogger;
58 import org.onap.policy.common.logging.flexlogger.Logger;
59 import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl;
60 import org.onap.policy.rest.adapter.PolicyRestAdapter;
61 import org.onap.policy.rest.jpa.OptimizationModels;
62
63 public class OptimizationConfigPolicy extends Policy {
64
65     private static final Logger LOGGER = FlexLogger.getLogger(OptimizationConfigPolicy.class);
66
67     private static Map<String, String> mapAttribute = new HashMap<>();
68     private static Map<String, String> mapMatch = new HashMap<>();
69
70     private static synchronized Map<String, String> getMatchMap() {
71         return mapMatch;
72     }
73
74     private static synchronized void setMatchMap(Map<String, String> mm) {
75         mapMatch = mm;
76     }
77
78     public OptimizationConfigPolicy() {
79         super();
80     }
81
82     public OptimizationConfigPolicy(PolicyRestAdapter policyAdapter) {
83         this.policyAdapter = policyAdapter;
84     }
85
86     // save configuration of the policy based on the policyname
87     private void saveConfigurations(String policyName, String jsonBody) {
88
89         if (policyName.endsWith(".xml")) {
90             policyName = policyName.replace(".xml", "");
91         }
92
93         try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".json");) {
94             out.println(jsonBody);
95         } catch (Exception e) {
96             LOGGER.error("Exception Occured While writing Configuration data" + e);
97         }
98     }
99
100     @Override
101     public Map<String, String> savePolicies() throws PAPException {
102
103         Map<String, String> successMap = new HashMap<>();
104         if (isPolicyExists()) {
105             successMap.put("EXISTS", "This Policy already exist on the PAP");
106             return successMap;
107         }
108
109         if (!isPreparedToSave()) {
110             // Prep and configure the policy for saving
111             prepareToSave();
112         }
113
114         // Until here we prepared the data and here calling the method to create xml.
115         Path newPolicyPath = null;
116         newPolicyPath = Paths.get(policyAdapter.getNewFileName());
117
118         successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject());
119
120         return successMap;
121     }
122
123     // This is the method for preparing the policy for saving. We have broken it out
124     // separately because the fully configured policy is used for multiple things
125     @Override
126     public boolean prepareToSave() throws PAPException {
127
128         if (isPreparedToSave()) {
129             // we have already done this
130             return true;
131         }
132
133         int version = 0;
134         String policyID = policyAdapter.getPolicyID();
135         version = policyAdapter.getHighestVersion();
136
137         // Create the Instance for pojo, PolicyType object is used in marshalling.
138         if (policyAdapter.getPolicyType().equals("Config")) {
139             PolicyType policyConfig = new PolicyType();
140
141             policyConfig.setVersion(Integer.toString(version));
142             policyConfig.setPolicyId(policyID);
143             policyConfig.setTarget(new TargetType());
144             policyAdapter.setData(policyConfig);
145         }
146         policyName = policyAdapter.getNewFileName();
147         if (policyAdapter.getData() != null) {
148             // Save the Configurations file with the policy name with extention based on selection.
149             String jsonBody = policyAdapter.getJsonBody();
150             saveConfigurations(policyName, jsonBody);
151
152             // Make sure the filename ends with an extension
153             if (!policyName.endsWith(".xml")) {
154                 policyName = policyName + ".xml";
155             }
156
157             PolicyType configPolicy = (PolicyType) policyAdapter.getData();
158
159             configPolicy.setDescription(policyAdapter.getPolicyDescription());
160
161             configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
162
163             AllOfType allOfOne = new AllOfType();
164             String fileName = policyAdapter.getNewFileName();
165             String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length());
166             if ((name == null) || (name.equals(""))) {
167                 name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length());
168             }
169
170             // setup values for pulling out matching attributes
171             ObjectMapper mapper = new ObjectMapper();
172             String matching = null;
173             Map<String, String> matchMap = null;
174             try {
175                 JsonNode rootNode = mapper.readTree(policyAdapter.getJsonBody());
176                 if (policyAdapter.getTtlDate() == null) {
177                     policyAdapter.setTtlDate("NA");
178                 }
179                 if (policyAdapter.getServiceType().contains("-v")) {
180                     matching = getValueFromDictionary(policyAdapter.getServiceType());
181                 } else {
182                     String jsonVersion = StringUtils.replaceEach(rootNode.get("version").toString(),
183                         new String[] {"\""}, new String[] {""});
184                     matching = getValueFromDictionary(policyAdapter.getServiceType() + "-v" + jsonVersion);
185                 }
186                 if (matching != null && !matching.isEmpty()) {
187                     matchMap = Splitter.on(",").withKeyValueSeparator("=").split(matching);
188                     setMatchMap(matchMap);
189                     if (policyAdapter.getJsonBody() != null) {
190                         pullMatchValue(rootNode);
191                     }
192                 }
193             } catch (IOException e1) {
194                 throw new PAPException(e1);
195             }
196
197             // Match for policyName
198             allOfOne.getMatch().add(createMatch("PolicyName", name));
199
200             AllOfType allOf = new AllOfType();
201
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                 for (Entry<String, String> matchValue : matchMap.entrySet()) {
206                     String value = matchValue.getValue();
207                     String key = matchValue.getKey().trim();
208                     if (value.contains("matching-true") && mapAttribute.containsKey(key)) {
209                         allOf.getMatch().add(createDynamicMatch(key, mapAttribute.get(key)));
210                     }
211                 }
212             }
213
214             // Match for riskType
215             allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
216             // Match for riskLevel
217             allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
218             // Match for riskguard
219             allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
220             // Match for ttlDate
221             allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
222
223             AnyOfType anyOf = new AnyOfType();
224             anyOf.getAllOf().add(allOfOne);
225             anyOf.getAllOf().add(allOf);
226
227             TargetType target = new TargetType();
228             target.getAnyOf().add(anyOf);
229
230             // Adding the target to the policy element
231             configPolicy.setTarget((TargetType) target);
232
233             RuleType rule = new RuleType();
234             rule.setRuleId(policyAdapter.getRuleID());
235
236             rule.setEffect(EffectType.PERMIT);
237
238             // Create Target in Rule
239             AllOfType allOfInRule = new AllOfType();
240
241             // Creating match for ACCESS in rule target
242             MatchType accessMatch = new MatchType();
243             AttributeValueType accessAttributeValue = new AttributeValueType();
244             accessAttributeValue.setDataType(STRING_DATATYPE);
245             accessAttributeValue.getContent().add("ACCESS");
246             accessMatch.setAttributeValue(accessAttributeValue);
247             AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
248             URI accessURI = null;
249             try {
250                 accessURI = new URI(ACTION_ID);
251             } catch (URISyntaxException e) {
252                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "OptimizationConfigPolicy",
253                     "Exception creating ACCESS URI");
254             }
255             accessAttributeDesignator.setCategory(CATEGORY_ACTION);
256             accessAttributeDesignator.setDataType(STRING_DATATYPE);
257             accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
258             accessMatch.setAttributeDesignator(accessAttributeDesignator);
259             accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
260
261             // Creating Config Match in rule Target
262             MatchType configMatch = new MatchType();
263             AttributeValueType configAttributeValue = new AttributeValueType();
264             configAttributeValue.setDataType(STRING_DATATYPE);
265             configAttributeValue.getContent().add("Config");
266             configMatch.setAttributeValue(configAttributeValue);
267             AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
268             URI configURI = null;
269             try {
270                 configURI = new URI(RESOURCE_ID);
271             } catch (URISyntaxException e) {
272                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "OptimizationConfigPolicy",
273                     "Exception creating Config URI");
274             }
275             configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
276             configAttributeDesignator.setDataType(STRING_DATATYPE);
277             configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
278             configMatch.setAttributeDesignator(configAttributeDesignator);
279             configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
280
281             allOfInRule.getMatch().add(accessMatch);
282             allOfInRule.getMatch().add(configMatch);
283
284             AnyOfType anyOfInRule = new AnyOfType();
285             anyOfInRule.getAllOf().add(allOfInRule);
286
287             TargetType targetInRule = new TargetType();
288             targetInRule.getAnyOf().add(anyOfInRule);
289
290             rule.setTarget(targetInRule);
291             rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
292
293             configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
294             policyAdapter.setPolicyData(configPolicy);
295
296         } else {
297             PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
298         }
299         setPreparedToSave(true);
300         return true;
301     }
302
303     private void pullMatchValue(JsonNode rootNode) {
304         Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
305         String newValue = null;
306         while (fieldsIterator.hasNext()) {
307             Map.Entry<String, JsonNode> field = fieldsIterator.next();
308             final String key = field.getKey();
309             final JsonNode value = field.getValue();
310             if (value.isContainerNode() && !value.isArray()) {
311                 pullMatchValue(value); // RECURSIVE CALL
312             } else {
313                 newValue =
314                     StringUtils.replaceEach(value.toString(), new String[] {"[", "]", "\""}, new String[] {"", "", ""});
315                 mapAttribute.put(key, newValue);
316             }
317         }
318
319     }
320
321     private String getValueFromDictionary(String service) {
322         String ruleTemplate = null;
323         String modelName = service.split("-v")[0];
324         String modelVersion = service.split("-v")[1];
325
326         CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
327         List<Object> result =
328             dbConnection.getDataById(OptimizationModels.class, "modelName:version", modelName + ":" + modelVersion);
329         if (result != null && !result.isEmpty()) {
330             OptimizationModels model = (OptimizationModels) result.get(0);
331             ruleTemplate = model.getAnnotation();
332         }
333         return ruleTemplate;
334     }
335
336     // Data required for Advice part is setting here.
337     protected AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
338         AdviceExpressionsType advices = new AdviceExpressionsType();
339         AdviceExpressionType advice = new AdviceExpressionType();
340         advice.setAdviceId("OptimizationID");
341         advice.setAppliesTo(EffectType.PERMIT);
342
343         // For Configuration
344         AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
345         assignment1.setAttributeId("type");
346         assignment1.setCategory(CATEGORY_RESOURCE);
347         assignment1.setIssuer("");
348
349         AttributeValueType configNameAttributeValue = new AttributeValueType();
350         configNameAttributeValue.setDataType(STRING_DATATYPE);
351         configNameAttributeValue.getContent().add("Configuration");
352         assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
353
354         advice.getAttributeAssignmentExpression().add(assignment1);
355
356         // For Config file Url if configurations are provided.
357         AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
358         assignment2.setAttributeId("URLID");
359         assignment2.setCategory(CATEGORY_RESOURCE);
360         assignment2.setIssuer("");
361
362         AttributeValueType attributeValue = new AttributeValueType();
363         attributeValue.setDataType(URI_DATATYPE);
364         String configName;
365         if (policyName.endsWith(".xml")) {
366             configName = policyName.replace(".xml", "");
367         } else {
368             configName = policyName;
369         }
370         String content = CONFIG_URL + "/Config/" + configName + ".json";
371         attributeValue.getContent().add(content);
372         assignment2.setExpression(new ObjectFactory().createAttributeValue(attributeValue));
373
374         advice.getAttributeAssignmentExpression().add(assignment2);
375
376         // PolicyName Attribute Assignment
377         AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
378         assignment3.setAttributeId("PolicyName");
379         assignment3.setCategory(CATEGORY_RESOURCE);
380         assignment3.setIssuer("");
381
382         AttributeValueType attributeValue3 = new AttributeValueType();
383         attributeValue3.setDataType(STRING_DATATYPE);
384         fileName = FilenameUtils.removeExtension(fileName);
385         fileName = fileName + ".xml";
386         String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length());
387         if ((name == null) || (name.equals(""))) {
388             name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length());
389         }
390         attributeValue3.getContent().add(name);
391         assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
392         advice.getAttributeAssignmentExpression().add(assignment3);
393
394         // VersionNumber Attribute Assignment
395         AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
396         assignment4.setAttributeId("VersionNumber");
397         assignment4.setCategory(CATEGORY_RESOURCE);
398         assignment4.setIssuer("");
399
400         AttributeValueType configNameAttributeValue4 = new AttributeValueType();
401         configNameAttributeValue4.setDataType(STRING_DATATYPE);
402         configNameAttributeValue4.getContent().add(Integer.toString(version));
403         assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
404
405         advice.getAttributeAssignmentExpression().add(assignment4);
406
407         // OnapName Attribute Assignment
408         AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
409         assignment5.setAttributeId("matching:" + ONAPID);
410         assignment5.setCategory(CATEGORY_RESOURCE);
411         assignment5.setIssuer("");
412
413         AttributeValueType configNameAttributeValue5 = new AttributeValueType();
414         configNameAttributeValue5.setDataType(STRING_DATATYPE);
415         configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
416         assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
417
418         advice.getAttributeAssignmentExpression().add(assignment5);
419
420         // ServiceType Attribute Assignment
421         AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
422         assignment7.setAttributeId("matching:service");
423         assignment7.setCategory(CATEGORY_RESOURCE);
424         assignment7.setIssuer("");
425
426         AttributeValueType configNameAttributeValue7 = new AttributeValueType();
427         configNameAttributeValue7.setDataType(STRING_DATATYPE);
428         configNameAttributeValue7.getContent().add(policyAdapter.getServiceType());
429         assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
430
431         advice.getAttributeAssignmentExpression().add(assignment7);
432
433         // Add matching attribute assignments if exist
434         Map<String, String> matchMap = getMatchMap();
435         if (matchMap != null && !matchMap.isEmpty()) {
436             for (Entry<String, String> matchValue : matchMap.entrySet()) {
437                 String value = matchValue.getValue();
438                 String key = matchValue.getKey().trim();
439                 if (value.contains("matching-true") && mapAttribute.containsKey(key)) {
440                     AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
441                     assignment9.setAttributeId("matching:" + key);
442                     assignment9.setCategory(CATEGORY_RESOURCE);
443                     assignment9.setIssuer("");
444
445                     AttributeValueType configNameAttributeValue9 = new AttributeValueType();
446                     configNameAttributeValue9.setDataType(STRING_DATATYPE);
447                     configNameAttributeValue9.getContent().add(mapAttribute.get(key));
448                     assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
449
450                     advice.getAttributeAssignmentExpression().add(assignment9);
451                 }
452             }
453         }
454
455         // Priority Attribute Assignment
456         AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
457         assignment10.setAttributeId("Priority");
458         assignment10.setCategory(CATEGORY_RESOURCE);
459         assignment10.setIssuer("");
460
461         AttributeValueType configNameAttributeValue10 = new AttributeValueType();
462         configNameAttributeValue10.setDataType(STRING_DATATYPE);
463         configNameAttributeValue10.getContent().add(policyAdapter.getPriority());
464         assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
465
466         advice.getAttributeAssignmentExpression().add(assignment10);
467
468         // RiskType Attribute Assignment
469         AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
470         assignment11.setAttributeId("RiskType");
471         assignment11.setCategory(CATEGORY_RESOURCE);
472         assignment11.setIssuer("");
473
474         AttributeValueType configNameAttributeValue11 = new AttributeValueType();
475         configNameAttributeValue11.setDataType(STRING_DATATYPE);
476         configNameAttributeValue11.getContent().add(policyAdapter.getRiskType());
477         assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11));
478
479         advice.getAttributeAssignmentExpression().add(assignment11);
480
481         // RiskLevel Attribute Assignment
482         AttributeAssignmentExpressionType assignment12 = new AttributeAssignmentExpressionType();
483         assignment12.setAttributeId("RiskLevel");
484         assignment12.setCategory(CATEGORY_RESOURCE);
485         assignment12.setIssuer("");
486
487         AttributeValueType configNameAttributeValue12 = new AttributeValueType();
488         configNameAttributeValue12.setDataType(STRING_DATATYPE);
489         configNameAttributeValue12.getContent().add(policyAdapter.getRiskLevel());
490         assignment12.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue12));
491
492         advice.getAttributeAssignmentExpression().add(assignment12);
493
494         // Guard Attribute Assignment
495         AttributeAssignmentExpressionType assignment13 = new AttributeAssignmentExpressionType();
496         assignment13.setAttributeId("guard");
497         assignment13.setCategory(CATEGORY_RESOURCE);
498         assignment13.setIssuer("");
499
500         AttributeValueType configNameAttributeValue13 = new AttributeValueType();
501         configNameAttributeValue13.setDataType(STRING_DATATYPE);
502         configNameAttributeValue13.getContent().add(policyAdapter.getGuard());
503         assignment13.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue13));
504
505         advice.getAttributeAssignmentExpression().add(assignment13);
506
507         // TTLDate Attribute Assignment
508         AttributeAssignmentExpressionType assignment14 = new AttributeAssignmentExpressionType();
509         assignment14.setAttributeId("TTLDate");
510         assignment14.setCategory(CATEGORY_RESOURCE);
511         assignment14.setIssuer("");
512
513         AttributeValueType configNameAttributeValue14 = new AttributeValueType();
514         configNameAttributeValue14.setDataType(STRING_DATATYPE);
515         configNameAttributeValue14.getContent().add(policyAdapter.getTtlDate());
516         assignment14.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue14));
517
518         advice.getAttributeAssignmentExpression().add(assignment14);
519
520         advices.getAdviceExpression().add(advice);
521         return advices;
522     }
523
524     @Override
525     public Object getCorrectPolicyDataObject() {
526         return policyAdapter.getPolicyData();
527     }
528 }