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