214cb32441783ca0394eab64a422b379e379133f
[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             return;
60         }
61         PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
62         policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
63
64         // Set PolicyAdapter name value
65         setPolicyAdapterNameValue(policyAdapter);
66
67         // Set PolicyAdapter description.
68         setPolicyAdapterDescription(policyAdapter, policy);
69
70         // Set PolicyAdapter attributes.
71         setPolicyAdapterAttributes(policyAdapter, policy);
72
73         // Set PolicyAdapter configBodyData
74         policyAdapter.setConfigBodyData(entity.getConfigurationData().getConfigBody());
75
76         // Get the target data under policy.
77         TargetType target = policy.getTarget();
78         if (target == null) {
79             return;
80         }
81         // Under target we have AnyOFType
82         List<AnyOfType> anyOfList = target.getAnyOf();
83         if (anyOfList == null) {
84             return;
85         }
86
87         // Set PolicyAdapter riskType, riskLevel, guard, ttlDate from match attributes
88         setPolicyAdapterMatchAttributes(policyAdapter, policy.getTarget().getAnyOf());
89     }
90
91     private void setPolicyAdapterMatchAttributes(PolicyRestAdapter policyAdapter, List<AnyOfType> anyOfList) {
92         anyOfList.stream()
93                 // Extract nonNull list of AllOfType objs from each AnyOfType obj
94                 .map(AnyOfType::getAllOf).filter(Objects::nonNull).forEach(allOfList ->
95                 // Extract nonNull list of MatchType objs from each AllOFType obj
96                 allOfList.stream().map(AllOfType::getMatch).filter(Objects::nonNull).flatMap(Collection::stream)
97                         .forEach(match -> {
98                             // Under the match we have attribute value and
99                             // attributeDesignator. So,finally down to the actual attribute.
100                             AttributeValueType attributeValue = match.getAttributeValue();
101                             String value = (String) attributeValue.getContent().get(0);
102                             AttributeDesignatorType designator = match.getAttributeDesignator();
103                             String attributeId = designator.getAttributeId();
104                             if ("RiskType".equals(attributeId)) {
105                                 policyAdapter.setRiskType(value);
106                             } else if ("RiskLevel".equals(attributeId)) {
107                                 policyAdapter.setRiskLevel(value);
108                             } else if ("guard".equals(attributeId)) {
109                                 policyAdapter.setGuard(value);
110                             } else if ("TTLDate".equals(attributeId) && !value.contains("NA")) {
111                                 PolicyController controller = new PolicyController();
112                                 String newDate = controller.convertDate(value);
113                                 policyAdapter.setTtlDate(newDate);
114                             }
115                         }));
116     }
117
118     private void setPolicyAdapterNameValue(final PolicyRestAdapter policyAdapter) {
119         // policy name value is the policy name without any prefix and extensions.
120         String policyNameValue =
121                 policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Raw_") + 9);
122         if (logger.isDebugEnabled()) {
123             logger.debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName());
124         }
125         policyAdapter.setPolicyName(policyNameValue);
126     }
127
128     private void setPolicyAdapterDescription(final PolicyRestAdapter policyAdapter, final PolicyType policy) {
129         String description;
130         try {
131             description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
132         } catch (Exception e) {
133             logger.info("Not able to see the createdby in description. So, add generic description", e);
134             description = policy.getDescription();
135         }
136         policyAdapter.setPolicyDescription(description);
137     }
138
139     @SuppressWarnings("unchecked")
140     private void setPolicyAdapterAttributes(final PolicyRestAdapter policyAdapter, final PolicyType policy) {
141         ArrayList<Object> attributeList = new ArrayList<>();
142         AdviceExpressionsType expressionTypes =
143                 ((RuleType) policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0))
144                         .getAdviceExpressions();
145         for (AdviceExpressionType adviceExpression : expressionTypes.getAdviceExpression()) {
146             for (AttributeAssignmentExpressionType attributeAssignment : adviceExpression
147                     .getAttributeAssignmentExpression()) {
148                 if (attributeAssignment.getAttributeId().startsWith("key:")) {
149                     Map<String, String> attribute = new HashMap<>();
150                     String key = attributeAssignment.getAttributeId().replace("key:", "");
151                     attribute.put("key", key);
152                     JAXBElement<AttributeValueType> attributeValue =
153                             (JAXBElement<AttributeValueType>) attributeAssignment.getExpression();
154                     String value = (String) attributeValue.getValue().getContent().get(0);
155                     attribute.put("value", value);
156                     attributeList.add(attribute);
157                 } else if (attributeAssignment.getAttributeId().startsWith("dependencies:")) {
158                     ArrayList<String> dependencies = new ArrayList<>(Arrays
159                             .asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(",")));
160                     dependencies.remove("");
161                     policyAdapter.setBrmsDependency(dependencies);
162                 } else if (attributeAssignment.getAttributeId().startsWith("controller:")) {
163                     policyAdapter.setBrmsController(attributeAssignment.getAttributeId().replace("controller:", ""));
164                 }
165             }
166             policyAdapter.setAttributes(attributeList);
167         }
168     }
169 }