aboutsummaryrefslogtreecommitdiffstats
path: root/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java
blob: d6a4e8285fbc780bdd0431dcee587159f8e21137 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
/*-
 * ============LICENSE_START=======================================================
 * ONAP Policy Engine
 * ================================================================================
 * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.xml.bind.JAXBElement;

import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.rest.adapter.PolicyRestAdapter;
import org.onap.policy.rest.adapter.RainyDayParams;
import org.onap.policy.rest.adapter.YAMLParams;
import org.onap.policy.rest.jpa.PolicyEntity;
import org.onap.policy.xacml.util.XACMLPolicyWriter;
import org.onap.portalsdk.core.controller.RestrictedBaseController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/")
public class DecisionPolicyController extends RestrictedBaseController {
    private static final Logger policyLogger = FlexLogger.getLogger(DecisionPolicyController.class);

    public static final String FUNCTION_NOT = "urn:oasis:names:tc:xacml:1.0:function:not";
    private static final String BLENTRY = "@blEntry@";
    private static final String DECISIONRAWTYPE = "@#RuleProvider@#Decision_Raw@#RuleProvider@#";
    private static final String GUARD_YAML = "GUARD_YAML";
    private static final String GUARD_BL_YAML = "GUARD_BL_YAML";
    private static final String GUARD_MIN_MAX = "GUARD_MIN_MAX";

    protected PolicyRestAdapter policyAdapter = null;
    private ArrayList<Object> ruleAlgorithmList;
    private ArrayList<Object> treatmentList = null;
    protected LinkedList<Integer> ruleAlgoirthmTracker;

    public DecisionPolicyController() {
        // This constructor is empty
    }

    public void rawXACMLPolicy(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
        try (InputStream policyXmlStream = XACMLPolicyWriter.getXmlAsInputStream(policyAdapter.getPolicyData())) {
            String name = StringUtils.substringAfter(entity.getPolicyName(), "Decision_");
            policyAdapter.setPolicyName(name.substring(0, name.indexOf('.')));
            policyAdapter.setRuleProvider("Raw");
            policyAdapter.setRawXacmlPolicy(IOUtils.toString(policyXmlStream).replaceAll(DECISIONRAWTYPE, ""));
        } catch (IOException e) {
            policyLogger.error("Exception Occured while setting XACML Raw Object" + e);
        }
    }

    @SuppressWarnings("unchecked")
    public void prePopulateDecisionPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
        List<Object> attributeList = new ArrayList<>();
        List<Object> decisionList = new ArrayList<>();
        ruleAlgorithmList = new ArrayList<>();
        treatmentList = new ArrayList<>();

        boolean rawPolicyCheck = false;
        if (policyAdapter.getPolicyData() instanceof PolicySetType) {
            rawPolicyCheck = ((PolicySetType) policyAdapter.getPolicyData()).getDescription().contains(DECISIONRAWTYPE);
        } else {
            rawPolicyCheck = ((PolicyType) policyAdapter.getPolicyData()).getDescription().contains(DECISIONRAWTYPE);
        }

        if (rawPolicyCheck) {
            rawXACMLPolicy(policyAdapter, entity);
        } else {
            RainyDayParams rainydayParams = new RainyDayParams();
            Object policyData = policyAdapter.getPolicyData();
            PolicyType policy = (PolicyType) policyData;
            policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());

            policyAdapter.setPolicyName(StringUtils.substringAfter(policyAdapter.getPolicyName(), "Decision_"));
            String description = "";
            String blackListEntryType = "Use Manual Entry";
            try {
                if (policy.getDescription().contains(BLENTRY)) {
                    blackListEntryType = policy.getDescription().substring(policy.getDescription().indexOf(BLENTRY) + 9,
                            policy.getDescription().lastIndexOf(BLENTRY));
                }
                policyAdapter.setBlackListEntryType(blackListEntryType);
                description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));

            } catch (Exception e) {
                policyLogger.info("General error", e);
                description = policy.getDescription();
            }
            policyAdapter.setPolicyDescription(description);
            // Get the target data under policy for Action.
            TargetType target = policy.getTarget();
            if (target != null) {
                // under target we have AnyOFType
                List<AnyOfType> anyOfList = target.getAnyOf();
                if (anyOfList != null) {
                    Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
                    while (iterAnyOf.hasNext()) {
                        AnyOfType anyOf = iterAnyOf.next();
                        // Under AntOfType we have AllOfType
                        List<AllOfType> allOfList = anyOf.getAllOf();
                        if (allOfList != null) {
                            Iterator<AllOfType> iterAllOf = allOfList.iterator();
                            while (iterAllOf.hasNext()) {
                                AllOfType allOf = iterAllOf.next();
                                // Under AllOfType we have Mathch.
                                List<MatchType> matchList = allOf.getMatch();
                                int index = 0;
                                if (matchList != null) {
                                    Iterator<MatchType> iterMatch = matchList.iterator();
                                    while (iterMatch.hasNext()) {
                                        MatchType match = iterMatch.next();
                                        //
                                        // Under the match we have attributevalue and
                                        // attributeDesignator. So,finally down to the actual attribute.
                                        //
                                        AttributeValueType attributeValue = match.getAttributeValue();
                                        String value = (String) attributeValue.getContent().get(0);
                                        if (value != null) {
                                            value = value.replaceAll("\\(\\?i\\)", "");
                                        }
                                        AttributeDesignatorType designator = match.getAttributeDesignator();
                                        String attributeId = designator.getAttributeId();
                                        // First match in the target is OnapName, so set that value.
                                        if ("ONAPName".equals(attributeId)) {
                                            policyAdapter.setOnapName(value);
                                        }
                                        // Component attributes are saved under Target here we are fetching them back.
                                        // One row is default so we are not adding dynamic component at index 0.
                                        if (index >= 1) {
                                            Map<String, String> attribute = new HashMap<>();
                                            attribute.put("key", attributeId);
                                            attribute.put("value", value);
                                            attributeList.add(attribute);
                                        }
                                        index++;
                                    }
                                }
                                policyAdapter.setAttributes(attributeList);
                            }
                        }
                    }
                    // Setting rainy day attributes to the parameters object if they exist
                    boolean rainy = false;
                    if (!attributeList.isEmpty()) {
                        for (int i = 0; i < attributeList.size(); i++) {
                            Map<String, String> map = (Map<String, String>) attributeList.get(i);
                            if ("WorkStep".equals(map.get("key"))) {
                                rainydayParams.setWorkstep(map.get("value"));
                                rainy = true;
                            } else if ("BB_ID".equals(map.get("key"))) {
                                rainydayParams.setBbid(map.get("value"));
                                rainy = true;
                            } else if ("ServiceType".equals(map.get("key"))) {
                                rainydayParams.setServiceType(map.get("value"));
                                rainy = true;
                            } else if ("VNFType".equals(map.get("key"))) {
                                rainydayParams.setVnfType(map.get("value"));
                                rainy = true;
                            }
                        }
                    }
                    if (rainy) {
                        policyAdapter.setRuleProvider("Rainy_Day");
                    }
                }

                List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
                int index = 0;
                for (Object object : ruleList) {
                    if (object instanceof VariableDefinitionType) {
                        VariableDefinitionType variableDefinitionType = (VariableDefinitionType) object;
                        Map<String, String> settings = new HashMap<>();
                        settings.put("key", variableDefinitionType.getVariableId());
                        JAXBElement<AttributeValueType> attributeValueTypeElement =
                                (JAXBElement<AttributeValueType>) variableDefinitionType.getExpression();
                        if (attributeValueTypeElement != null) {
                            AttributeValueType attributeValueType = attributeValueTypeElement.getValue();
                            settings.put("value", attributeValueType.getContent().get(0).toString());
                        }
                        decisionList.add(settings);
                    } else if (object instanceof RuleType) {
                        // get the condition data under the rule for rule Algorithms.
                        if (((RuleType) object).getEffect().equals(EffectType.DENY)) {
                            if (((RuleType) object).getAdviceExpressions() != null) {
                                if ("AAF".equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
                                        .getAdviceExpression().get(0).getAdviceId())) {
                                    policyAdapter.setRuleProvider("AAF");
                                    break;
                                } else if (GUARD_YAML.equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
                                        .getAdviceExpression().get(0).getAdviceId())) {
                                    policyAdapter.setRuleProvider(GUARD_YAML);
                                } else if (GUARD_BL_YAML.equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
                                        .getAdviceExpression().get(0).getAdviceId())) {
                                    policyAdapter.setRuleProvider(GUARD_BL_YAML);
                                } else if (GUARD_MIN_MAX.equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
                                        .getAdviceExpression().get(0).getAdviceId())) {
                                    policyAdapter.setRuleProvider(GUARD_MIN_MAX);
                                }
                            } else {
                                policyAdapter.setRuleProvider("Custom");
                            }
                            ConditionType condition = ((RuleType) object).getCondition();
                            if (condition != null) {
                                ApplyType decisionApply = (ApplyType) condition.getExpression().getValue();
                                decisionApply = (ApplyType) decisionApply.getExpression().get(0).getValue();
                                ruleAlgoirthmTracker = new LinkedList<>();
                                if (policyAdapter.getRuleProvider() != null
                                        && (GUARD_YAML.equals(policyAdapter.getRuleProvider())
                                                || (GUARD_BL_YAML.equals(policyAdapter.getRuleProvider()))
                                                || (GUARD_MIN_MAX.equals(policyAdapter.getRuleProvider())))) {
                                    YAMLParams yamlParams = new YAMLParams();
                                    for (int i = 0; i < attributeList.size(); i++) {
                                        Map<String, String> map = (Map<String, String>) attributeList.get(i);
                                        if ("actor".equals(map.get("key"))) {
                                            yamlParams.setActor(map.get("value"));
                                        } else if ("recipe".equals(map.get("key"))) {
                                            yamlParams.setRecipe(map.get("value"));
                                        } else if ("target".equals(map.get("key"))) {
                                            yamlParams.setTargets(Arrays.asList(map.get("value").split("\\|")));
                                        } else if ("clname".equals(map.get("key"))) {
                                            yamlParams.setClname(map.get("value"));
                                        } else if ("min".equals(map.get("key"))) {
                                            yamlParams.setMin(map.get("value"));
                                        } else if ("max".equals(map.get("key"))) {
                                            yamlParams.setMax(map.get("value"));
                                        }
                                    }
                                    ApplyType apply =
                                            (ApplyType) ((ApplyType) decisionApply.getExpression().get(0).getValue())
                                                    .getExpression().get(0).getValue();
                                    yamlParams.setGuardActiveStart(
                                            ((AttributeValueType) apply.getExpression().get(1).getValue()).getContent()
                                                    .get(0).toString());
                                    yamlParams.setGuardActiveEnd(
                                            ((AttributeValueType) apply.getExpression().get(2).getValue()).getContent()
                                                    .get(0).toString());
                                    if (GUARD_BL_YAML.equals(policyAdapter.getRuleProvider())) {
                                        apply = (ApplyType) ((ApplyType) ((ApplyType) decisionApply.getExpression()
                                                .get(0).getValue()).getExpression().get(1).getValue()).getExpression()
                                                        .get(2).getValue();
                                        Iterator<JAXBElement<?>> attributes = apply.getExpression().iterator();
                                        List<String> blackList = new ArrayList<>();
                                        while (attributes.hasNext()) {
                                            blackList.add(((AttributeValueType) attributes.next().getValue())
                                                    .getContent().get(0).toString());
                                        }
                                        yamlParams.setBlackList(blackList);
                                        if ("Use File Upload".equals(policyAdapter.getBlackListEntryType())) {
                                            policyAdapter.setBlackListEntries(blackList);
                                        }
                                    } else {
                                        ApplyType timeWindowSection = (ApplyType) ((ApplyType) decisionApply
                                                .getExpression().get(0).getValue()).getExpression().get(1).getValue();
                                        yamlParams.setLimit(((AttributeValueType) timeWindowSection.getExpression()
                                                .get(1).getValue()).getContent().get(0).toString());
                                        String timeWindow = ((AttributeDesignatorType) ((ApplyType) timeWindowSection
                                                .getExpression().get(0).getValue()).getExpression().get(0).getValue())
                                                        .getIssuer();
                                        yamlParams.setTimeUnits(timeWindow.substring(timeWindow.lastIndexOf(':') + 1));
                                        yamlParams.setTimeWindow(timeWindow.substring(timeWindow.indexOf(":tw:") + 4,
                                                timeWindow.lastIndexOf(':')));
                                    }
                                    policyAdapter.setYamlparams(yamlParams);
                                    policyAdapter.setAttributes(new ArrayList<Object>());
                                    policyAdapter.setRuleAlgorithmschoices(new ArrayList<Object>());
                                    break;
                                }
                                // Populating Rule Algorithms starting from compound.
                                prePopulateDecisionCompoundRuleAlgorithm(index, decisionApply);
                                policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList);
                            }
                        } else if (policyAdapter.getRuleProvider() != null
                                && "Rainy_Day".equals(policyAdapter.getRuleProvider())
                                && ((RuleType) object).getEffect().equals(EffectType.PERMIT)) {

                            TargetType ruleTarget = ((RuleType) object).getTarget();
                            AdviceExpressionsType adviceExpression = ((RuleType) object).getAdviceExpressions();

                            String errorcode = ruleTarget.getAnyOf().get(0).getAllOf().get(0).getMatch().get(1)
                                    .getAttributeValue().getContent().get(0).toString();
                            JAXBElement<AttributeValueType> tempTreatmentObj =
                                    (JAXBElement<AttributeValueType>) adviceExpression.getAdviceExpression().get(0)
                                            .getAttributeAssignmentExpression().get(0).getExpression();
                            String treatment = tempTreatmentObj.getValue().getContent().get(0).toString();

                            prePopulateRainyDayTreatments(errorcode, treatment);

                        }
                    }
                }
            }

            rainydayParams.setTreatmentTableChoices(treatmentList);
            policyAdapter.setRainyday(rainydayParams);
            policyAdapter.setSettings(decisionList);
        }

    }

    private void prePopulateRainyDayTreatments(String errorcode, String treatment) {
        Map<String, String> ruleMap = new HashMap<>();

        ruleMap.put("errorcode", errorcode);
        ruleMap.put("treatment", treatment);
        treatmentList.add(ruleMap);

    }

    private void prePopulateDecisionRuleAlgorithms(int index, ApplyType decisionApply,
            List<JAXBElement<?>> jaxbDecisionTypes) {
        Map<String, String> ruleMap = new HashMap<>();
        ruleMap.put("id", "A" + (index + 1));
        Map<String, String> dropDownMap = PolicyController.getDropDownMap();
        for (Entry<String, String> entry : dropDownMap.entrySet()) {
            if (entry.getValue().equals(decisionApply.getFunctionId())) {
                ruleMap.put("dynamicRuleAlgorithmCombo", entry.getKey());
            }
        }
        // Populate the key and value fields
        if ((jaxbDecisionTypes.get(0).getValue() instanceof AttributeValueType)) {
            ApplyType innerDecisionApply = (ApplyType) jaxbDecisionTypes.get(1).getValue();
            List<JAXBElement<?>> jaxbInnerDecisionTypes = innerDecisionApply.getExpression();
            if (jaxbInnerDecisionTypes.get(0).getValue() instanceof AttributeDesignatorType) {
                AttributeDesignatorType attributeDesignator =
                        (AttributeDesignatorType) jaxbInnerDecisionTypes.get(0).getValue();
                ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId());

                // Get from Attribute Value
                AttributeValueType actionConditionAttributeValue =
                        (AttributeValueType) jaxbDecisionTypes.get(0).getValue();
                String attributeValue = (String) actionConditionAttributeValue.getContent().get(0);
                ruleMap.put("dynamicRuleAlgorithmField2", attributeValue);
            }
        } else if ((jaxbDecisionTypes.get(0).getValue()) instanceof VariableReferenceType) {
            VariableReferenceType variableReference = (VariableReferenceType) jaxbDecisionTypes.get(0).getValue();
            ruleMap.put("dynamicRuleAlgorithmField1", "S_" + variableReference.getVariableId());

            // Get from Attribute Value
            AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbDecisionTypes.get(1).getValue();
            String attributeValue = (String) actionConditionAttributeValue.getContent().get(0);
            ruleMap.put("dynamicRuleAlgorithmField2", attributeValue);
        }
        ruleAlgorithmList.add(ruleMap);
    }

    private int prePopulateDecisionCompoundRuleAlgorithm(int index, ApplyType decisionApply) {
        boolean isCompoundRule = true;
        List<JAXBElement<?>> jaxbDecisionTypes = decisionApply.getExpression();
        for (JAXBElement<?> jaxbElement : jaxbDecisionTypes) {
            // If There is Attribute Value under Decision Type that means we came to the final child
            if (policyLogger.isDebugEnabled()) {
                policyLogger.debug("Prepopulating rule algoirthm: " + index);
            }
            // Check to see if Attribute Value exists, if yes then it is not a compound rule
            if (jaxbElement.getValue() instanceof AttributeValueType) {
                prePopulateDecisionRuleAlgorithms(index, decisionApply, jaxbDecisionTypes);
                ruleAlgoirthmTracker.addLast(index);
                isCompoundRule = false;
                index++;
            }
        }
        if (isCompoundRule) {
            // As it's compound rule, Get the Apply types
            for (JAXBElement<?> jaxbElement : jaxbDecisionTypes) {
                ApplyType innerDecisionApply = (ApplyType) jaxbElement.getValue();
                index = prePopulateDecisionCompoundRuleAlgorithm(index, innerDecisionApply);
            }
            // Populate combo box
            if (policyLogger.isDebugEnabled()) {
                policyLogger.debug("Prepopulating Compound rule algorithm: " + index);
            }
            Map<String, String> rule = new HashMap<>();
            for (String key : PolicyController.getDropDownMap().keySet()) {
                String keyValue = PolicyController.getDropDownMap().get(key);
                if (keyValue.equals(decisionApply.getFunctionId())) {
                    rule.put("dynamicRuleAlgorithmCombo", key);
                    break;
                }
            }

            rule.put("id", "A" + (index + 1));
            // Populate Key and values for Compound Rule
            rule.put("dynamicRuleAlgorithmField1", "A" + (ruleAlgoirthmTracker.getLast() + 1));
            ruleAlgoirthmTracker.removeLast();
            rule.put("dynamicRuleAlgorithmField2", "A" + (ruleAlgoirthmTracker.getLast() + 1));
            ruleAlgoirthmTracker.removeLast();
            ruleAlgoirthmTracker.addLast(index);
            ruleAlgorithmList.add(rule);
            index++;
        }

        return index;
    }
}