081b33cc0c271646a5c1293db319382c1309d0c5
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / controller / CreateBRMSRawController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2019 Bell Canada
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.controller;
23
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.Collection;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Objects;
31
32 import javax.xml.bind.JAXBElement;
33
34 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
35 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
36 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
37 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
38 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
39 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
40 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
41 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
42 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
43 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
44
45 import org.onap.policy.common.logging.flexlogger.FlexLogger;
46 import org.onap.policy.common.logging.flexlogger.Logger;
47 import org.onap.policy.rest.adapter.PolicyRestAdapter;
48 import org.onap.policy.rest.jpa.PolicyEntity;
49
50 public class CreateBRMSRawController {
51
52     private static final Logger logger = FlexLogger.getLogger(CreateBRMSRawController.class);
53
54     protected PolicyRestAdapter policyAdapter = null;
55
56     public void prePopulateBRMSRawPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
57
58         if (policyAdapter.getPolicyData() instanceof PolicyType) {
59             PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
60             policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
61
62             // Set PolicyAdapter name value
63             setPolicyAdapterNameValue(policyAdapter);
64
65             // Set PolicyAdapter description.
66             setPolicyAdapterDescription(policyAdapter, policy);
67
68             // Set PolicyAdapter attributes.
69             setPolicyAdapterAttributes(policyAdapter, policy);
70
71             // Set PolicyAdapter configBodyData
72             policyAdapter.setConfigBodyData(entity.getConfigurationData().getConfigBody());
73
74             // Get the target data under policy.
75             TargetType target = policy.getTarget();
76             if (target == null) {
77                 return;
78             }
79             // Under target we have AnyOFType
80             List<AnyOfType> anyOfList = target.getAnyOf();
81             if (anyOfList == null) {
82                 return;
83             }
84
85             // Set PolicyAdapter riskType, riskLevel, guard, ttlDate from match attributes
86             setPolicyAdapterMatchAttributes(policyAdapter, policy.getTarget().getAnyOf());
87         }
88     }
89
90     private void setPolicyAdapterMatchAttributes(PolicyRestAdapter policyAdapter, List<AnyOfType> anyOfList) {
91         anyOfList.stream()
92                 // Extract nonNull list of AllOfType objs from each AnyOfType obj
93                 .map(AnyOfType::getAllOf).filter(Objects::nonNull).forEach(allOfList ->
94                 // Extract nonNull list of MatchType objs from each AllOFType obj
95                 allOfList.stream().map(AllOfType::getMatch).filter(Objects::nonNull).flatMap(Collection::stream)
96                         .forEach(match -> {
97                             // Under the match we have attribute value and
98                             // attributeDesignator. So,finally down to the actual attribute.
99                             AttributeValueType attributeValue = match.getAttributeValue();
100                             String value = (String) attributeValue.getContent().get(0);
101                             AttributeDesignatorType designator = match.getAttributeDesignator();
102                             String attributeId = designator.getAttributeId();
103                             if ("RiskType".equals(attributeId)) {
104                                 policyAdapter.setRiskType(value);
105                             } else if ("RiskLevel".equals(attributeId)) {
106                                 policyAdapter.setRiskLevel(value);
107                             } else if ("guard".equals(attributeId)) {
108                                 policyAdapter.setGuard(value);
109                             } else if ("TTLDate".equals(attributeId) && !value.contains("NA")) {
110                                 PolicyController controller = new PolicyController();
111                                 String newDate = controller.convertDate(value);
112                                 policyAdapter.setTtlDate(newDate);
113                             }
114                         }));
115     }
116
117     private void setPolicyAdapterNameValue(final PolicyRestAdapter policyAdapter) {
118         // policy name value is the policy name without any prefix and extensions.
119         String policyNameValue =
120                 policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Raw_") + 9);
121         if (logger.isDebugEnabled()) {
122             logger.debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName());
123         }
124         policyAdapter.setPolicyName(policyNameValue);
125     }
126
127     private void setPolicyAdapterDescription(final PolicyRestAdapter policyAdapter, final PolicyType policy) {
128         String description;
129         try {
130             description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
131         } catch (Exception e) {
132             logger.info("Not able to see the createdby in description. So, add generic description", e);
133             description = policy.getDescription();
134         }
135         policyAdapter.setPolicyDescription(description);
136     }
137
138     @SuppressWarnings("unchecked")
139     private void setPolicyAdapterAttributes(final PolicyRestAdapter policyAdapter, final PolicyType policy) {
140         ArrayList<Object> attributeList = new ArrayList<>();
141         AdviceExpressionsType expressionTypes =
142                 ((RuleType) policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0))
143                         .getAdviceExpressions();
144         for (AdviceExpressionType adviceExpression : expressionTypes.getAdviceExpression()) {
145             for (AttributeAssignmentExpressionType attributeAssignment : adviceExpression
146                     .getAttributeAssignmentExpression()) {
147                 if (attributeAssignment.getAttributeId().startsWith("key:")) {
148                     Map<String, String> attribute = new HashMap<>();
149                     String key = attributeAssignment.getAttributeId().replace("key:", "");
150                     attribute.put("key", key);
151                     JAXBElement<AttributeValueType> attributeValue =
152                             (JAXBElement<AttributeValueType>) attributeAssignment.getExpression();
153                     String value = (String) attributeValue.getValue().getContent().get(0);
154                     attribute.put("value", value);
155                     attributeList.add(attribute);
156                 } else if (attributeAssignment.getAttributeId().startsWith("dependencies:")) {
157                     ArrayList<String> dependencies = new ArrayList<>(Arrays
158                             .asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(",")));
159                     dependencies.remove("");
160                     policyAdapter.setBrmsDependency(dependencies);
161                 } else if (attributeAssignment.getAttributeId().startsWith("controller:")) {
162                     policyAdapter.setBrmsController(attributeAssignment.getAttributeId().replace("controller:", ""));
163                 }
164             }
165             policyAdapter.setAttributes(attributeList);
166         }
167     }
168 }