Consolidate PolicyRestAdapter setup
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / controller / CreateClosedLoopPMController.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 com.fasterxml.jackson.databind.ObjectMapper;
25
26 import java.io.IOException;
27 import java.util.LinkedHashMap;
28 import java.util.List;
29 import java.util.Objects;
30
31 import javax.json.JsonArray;
32 import javax.json.JsonObject;
33
34 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
35 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
36 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
37 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
38 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
39 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
40
41 import org.onap.policy.admin.PolicyManagerServlet;
42 import org.onap.policy.common.logging.flexlogger.FlexLogger;
43 import org.onap.policy.common.logging.flexlogger.Logger;
44 import org.onap.policy.rest.adapter.ClosedLoopPMBody;
45 import org.onap.policy.rest.adapter.PolicyRestAdapter;
46 import org.onap.policy.rest.jpa.PolicyEntity;
47
48 public class CreateClosedLoopPMController {
49
50     private static final Logger LOGGER = FlexLogger.getLogger(CreateClosedLoopPMController.class);
51     private static final String KEY_SERVICE_TYPE_POLICY_NAME = "serviceTypePolicyName";
52
53     protected PolicyRestAdapter policyAdapter = null;
54
55     /**
56      * prePopulateClosedLoopPMPolicyData.
57      *
58      * @param policyAdapter PolicyRestAdapter
59      * @param entity PolicyEntity
60      */
61     public void prePopulateClosedLoopPMPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
62         if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
63             return;
64         }
65         Object policyData = policyAdapter.getPolicyData();
66         PolicyType policy = (PolicyType) policyData;
67
68         // Set oldPolicyFileName to PolicyAdapter
69         policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
70
71         // Set policyNameValue and description to PolicyAdapter
72         setPolicyAdapterNameValueAndDescription(policyAdapter, policy);
73
74         // Set PolicyAdapter JsonBodyData
75         setClosedLoopJsonFile(policyAdapter, entity);
76
77         // Get the target data under policy.
78         TargetType target = policy.getTarget();
79         if (target == null) {
80             return;
81         }
82         // Set PolicyAdapter OnapNameField, riskType, riskLevel, guard, ttlDate, ServiceType from match attributes
83         setPolicyAdapterMatchAttributes(policyAdapter, target.getAnyOf());
84     }
85
86     private void setPolicyAdapterNameValueAndDescription(PolicyRestAdapter policyAdapter, PolicyType policy) {
87         String policyNameValue =
88                 policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("PM_") + 3);
89         policyAdapter.setPolicyName(policyNameValue);
90         String description;
91         try {
92             description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
93         } catch (Exception e) {
94             LOGGER.info("General error", e);
95             description = policy.getDescription();
96         }
97         policyAdapter.setPolicyDescription(description);
98     }
99
100     private void setClosedLoopJsonFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
101         try {
102             ClosedLoopPMBody closedLoopBody =
103                     new ObjectMapper().readValue(entity.getConfigurationData().getConfigBody(), ClosedLoopPMBody.class);
104             policyAdapter.setJsonBodyData(closedLoopBody);
105         } catch (IOException e) {
106             LOGGER.error("Exception Occured" + e);
107         }
108     }
109
110     private void setPolicyAdapterMatchAttributes(final PolicyRestAdapter policyAdapter,
111             final List<AnyOfType> anyOfList) {
112         anyOfList.stream()
113                 // Extract nonNull list of AllOfType objs from each AnyOfType obj
114                 .map(AnyOfType::getAllOf).filter(Objects::nonNull).forEach(allOfList ->
115                 // Extract nonNull list of MatchType objs from each AllOFType obj
116                 allOfList.stream().map(AllOfType::getMatch).filter(Objects::nonNull)
117                         .forEach(matchList -> matchList.forEach(match -> {
118                             // Under the match we have attribute value and
119                             // attributeDesignator. So,finally down to the actual attribute.
120                             AttributeValueType attributeValue = match.getAttributeValue();
121                             String value = (String) attributeValue.getContent().get(0);
122                             AttributeDesignatorType designator = match.getAttributeDesignator();
123                             String attributeId = designator.getAttributeId();
124                             // First match in the target is OnapName, so set that value.
125                             policyAdapter.setupUsingAttribute(attributeId, value);
126                             if ("ServiceType".equals(attributeId)) {
127                                 LinkedHashMap<String, String> serviceTypePolicyName1 = new LinkedHashMap<>();
128                                 serviceTypePolicyName1.put(KEY_SERVICE_TYPE_POLICY_NAME, value);
129                                 policyAdapter.setServiceTypePolicyName(serviceTypePolicyName1);
130                                 LinkedHashMap<String, String> vertica = new LinkedHashMap<>();
131                                 vertica.put("verticaMetrics", getVertica(value));
132                                 policyAdapter.setVerticaMetrics(vertica);
133                                 LinkedHashMap<String, String> desc = new LinkedHashMap<>();
134                                 desc.put("policyDescription", getDescription(value));
135                                 policyAdapter.setDescription(desc);
136                                 LinkedHashMap<String, Object> attributes = new LinkedHashMap<>();
137                                 attributes.put("attributes", getAttributes(value));
138                                 policyAdapter.setAttributeFields(attributes);
139                             }
140                         })));
141     }
142
143     // get vertica metrics data from the table
144     private String getVertica(String policyName) {
145         JsonArray data = PolicyManagerServlet.getPolicyNames();
146         for (int i = 0; i < data.size(); i++) {
147             if (policyName.equals(data.getJsonObject(i).getJsonString(KEY_SERVICE_TYPE_POLICY_NAME).getString())) {
148                 return data.getJsonObject(i).getJsonString("verticaMetrics").getString();
149             }
150         }
151         return null;
152     }
153
154     // get policy description from the table
155     private String getDescription(String policyName) {
156         JsonArray data = PolicyManagerServlet.getPolicyNames();
157         for (int i = 0; i < data.size(); i++) {
158             if (policyName.equals(data.getJsonObject(i).getJsonString(KEY_SERVICE_TYPE_POLICY_NAME).getString())) {
159                 return data.getJsonObject(i).getJsonString("policyDescription").getString();
160             }
161         }
162         return null;
163     }
164
165     // get Attributes
166     private JsonObject getAttributes(String policyName) {
167         JsonArray data = PolicyManagerServlet.getPolicyNames();
168         for (int i = 0; i < data.size(); i++) {
169             if (policyName.equals(data.getJsonObject(i).getJsonString(KEY_SERVICE_TYPE_POLICY_NAME).getString())) {
170                 return data.getJsonObject(i).getJsonObject("attributes");
171             }
172         }
173         return null;
174     }
175 }