Consolidate PolicyRestAdapter setup
[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.AttributeValueType;
40 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
41 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
42 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
43
44 import org.onap.policy.common.logging.flexlogger.FlexLogger;
45 import org.onap.policy.common.logging.flexlogger.Logger;
46 import org.onap.policy.rest.adapter.PolicyRestAdapter;
47 import org.onap.policy.rest.jpa.PolicyEntity;
48
49 public class CreateBRMSRawController {
50
51     private static final Logger logger = FlexLogger.getLogger(CreateBRMSRawController.class);
52
53     protected PolicyRestAdapter policyAdapter = null;
54
55     /**
56      * prePopulateBRMSRawPolicyData.
57      *
58      * @param policyAdapter PolicyRestAdapter
59      * @param entity PolicyEntity
60      */
61     public void prePopulateBRMSRawPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
62
63         if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
64             return;
65         }
66         PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
67         policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
68
69         // Set PolicyAdapter name value
70         setPolicyAdapterNameValue(policyAdapter);
71
72         // Set PolicyAdapter description.
73         setPolicyAdapterDescription(policyAdapter, policy);
74
75         // Set PolicyAdapter attributes.
76         setPolicyAdapterAttributes(policyAdapter, policy);
77
78         // Set PolicyAdapter configBodyData
79         policyAdapter.setConfigBodyData(entity.getConfigurationData().getConfigBody());
80
81         // Get the target data under policy.
82         TargetType target = policy.getTarget();
83         if (target == null) {
84             return;
85         }
86         // Under target we have AnyOFType
87         List<AnyOfType> anyOfList = target.getAnyOf();
88         if (anyOfList == null) {
89             return;
90         }
91
92         // Set PolicyAdapter riskType, riskLevel, guard, ttlDate from match attributes
93         setPolicyAdapterMatchAttributes(policyAdapter, policy.getTarget().getAnyOf());
94     }
95
96     private void setPolicyAdapterMatchAttributes(PolicyRestAdapter policyAdapter, List<AnyOfType> anyOfList) {
97         anyOfList.stream()
98                 // Extract nonNull list of AllOfType objs from each AnyOfType obj
99                 .map(AnyOfType::getAllOf).filter(Objects::nonNull).forEach(allOfList ->
100                 // Extract nonNull list of MatchType objs from each AllOFType obj
101                 allOfList.stream().map(AllOfType::getMatch).filter(Objects::nonNull).flatMap(Collection::stream)
102                         .forEach(match -> {
103                             // Under the match we have attribute value and
104                             // attributeDesignator. So,finally down to the actual attribute.
105                             policyAdapter.setupUsingAttribute(match.getAttributeDesignator().getAttributeId(),
106                                     (String) match.getAttributeValue().getContent().get(0));
107                         }));
108     }
109
110     private void setPolicyAdapterNameValue(final PolicyRestAdapter policyAdapter) {
111         // policy name value is the policy name without any prefix and extensions.
112         String policyNameValue =
113                 policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Raw_") + 9);
114         if (logger.isDebugEnabled()) {
115             logger.debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName());
116         }
117         policyAdapter.setPolicyName(policyNameValue);
118     }
119
120     private void setPolicyAdapterDescription(final PolicyRestAdapter policyAdapter, final PolicyType policy) {
121         String description;
122         try {
123             description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
124         } catch (Exception e) {
125             logger.info("Not able to see the createdby in description. So, add generic description", e);
126             description = policy.getDescription();
127         }
128         policyAdapter.setPolicyDescription(description);
129     }
130
131     @SuppressWarnings("unchecked")
132     private void setPolicyAdapterAttributes(final PolicyRestAdapter policyAdapter, final PolicyType policy) {
133         ArrayList<Object> attributeList = new ArrayList<>();
134         AdviceExpressionsType expressionTypes =
135                 ((RuleType) policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0))
136                         .getAdviceExpressions();
137         for (AdviceExpressionType adviceExpression : expressionTypes.getAdviceExpression()) {
138             for (AttributeAssignmentExpressionType attributeAssignment : adviceExpression
139                     .getAttributeAssignmentExpression()) {
140                 if (attributeAssignment.getAttributeId().startsWith("key:")) {
141                     Map<String, String> attribute = new HashMap<>();
142                     String key = attributeAssignment.getAttributeId().replace("key:", "");
143                     attribute.put("key", key);
144                     JAXBElement<AttributeValueType> attributeValue =
145                             (JAXBElement<AttributeValueType>) attributeAssignment.getExpression();
146                     String value = (String) attributeValue.getValue().getContent().get(0);
147                     attribute.put("value", value);
148                     attributeList.add(attribute);
149                 } else if (attributeAssignment.getAttributeId().startsWith("dependencies:")) {
150                     ArrayList<String> dependencies = new ArrayList<>(Arrays
151                             .asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(",")));
152                     dependencies.remove("");
153                     policyAdapter.setBrmsDependency(dependencies);
154                 } else if (attributeAssignment.getAttributeId().startsWith("controller:")) {
155                     policyAdapter.setBrmsController(attributeAssignment.getAttributeId().replace("controller:", ""));
156                 }
157             }
158             policyAdapter.setAttributes(attributeList);
159         }
160     }
161 }