Sonar cleanup in controllers etc
[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     public void prePopulateClosedLoopPMPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
56         if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
57             return;
58         }
59         Object policyData = policyAdapter.getPolicyData();
60         PolicyType policy = (PolicyType) policyData;
61
62         // Set oldPolicyFileName to PolicyAdapter
63         policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
64
65         // Set policyNameValue and description to PolicyAdapter
66         setPolicyAdapterNameValueAndDescription(policyAdapter, policy);
67
68         // Set PolicyAdapter JsonBodyData
69         setClosedLoopJsonFile(policyAdapter, entity);
70
71         // Get the target data under policy.
72         TargetType target = policy.getTarget();
73         if (target == null) {
74             return;
75         }
76         // Set PolicyAdapter OnapNameField, riskType, riskLevel, guard, ttlDate, ServiceType from match attributes
77         setPolicyAdapterMatchAttributes(policyAdapter, target.getAnyOf());
78     }
79
80     private void setPolicyAdapterNameValueAndDescription(PolicyRestAdapter policyAdapter, PolicyType policy) {
81         String policyNameValue =
82                 policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("PM_") + 3);
83         policyAdapter.setPolicyName(policyNameValue);
84         String description;
85         try {
86             description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
87         } catch (Exception e) {
88             LOGGER.info("General error", e);
89             description = policy.getDescription();
90         }
91         policyAdapter.setPolicyDescription(description);
92     }
93
94     private void setClosedLoopJsonFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
95         try {
96             ClosedLoopPMBody closedLoopBody =
97                     new ObjectMapper().readValue(entity.getConfigurationData().getConfigBody(), ClosedLoopPMBody.class);
98             policyAdapter.setJsonBodyData(closedLoopBody);
99         } catch (IOException e) {
100             LOGGER.error("Exception Occured" + e);
101         }
102     }
103
104     private void setPolicyAdapterMatchAttributes(final PolicyRestAdapter policyAdapter,
105             final List<AnyOfType> anyOfList) {
106         anyOfList.stream()
107                 // Extract nonNull list of AllOfType objs from each AnyOfType obj
108                 .map(AnyOfType::getAllOf).filter(Objects::nonNull).forEach(allOfList ->
109                 // Extract nonNull list of MatchType objs from each AllOFType obj
110                 allOfList.stream().map(AllOfType::getMatch).filter(Objects::nonNull)
111                         .forEach(matchList -> matchList.forEach(match -> {
112                             // Under the match we have attribute value and
113                             // attributeDesignator. So,finally down to the actual attribute.
114                             AttributeValueType attributeValue = match.getAttributeValue();
115                             String value = (String) attributeValue.getContent().get(0);
116                             AttributeDesignatorType designator = match.getAttributeDesignator();
117                             String attributeId = designator.getAttributeId();
118                             // First match in the target is OnapName, so set that value.
119                             if ("ONAPName".equals(attributeId)) {
120                                 policyAdapter.setOnapName(value);
121                             } else if ("RiskType".equals(attributeId)) {
122                                 policyAdapter.setRiskType(value);
123                             } else if ("RiskLevel".equals(attributeId)) {
124                                 policyAdapter.setRiskLevel(value);
125                             } else if ("guard".equals(attributeId)) {
126                                 policyAdapter.setGuard(value);
127                             } else if ("TTLDate".equals(attributeId) && !value.contains("NA")) {
128                                 PolicyController controller = new PolicyController();
129                                 String newDate = controller.convertDate(value);
130                                 policyAdapter.setTtlDate(newDate);
131                             } else if ("ServiceType".equals(attributeId)) {
132                                 LinkedHashMap<String, String> serviceTypePolicyName1 = new LinkedHashMap<>();
133                                 serviceTypePolicyName1.put(KEY_SERVICE_TYPE_POLICY_NAME, value);
134                                 policyAdapter.setServiceTypePolicyName(serviceTypePolicyName1);
135                                 LinkedHashMap<String, String> vertica = new LinkedHashMap<>();
136                                 vertica.put("verticaMetrics", getVertica(value));
137                                 policyAdapter.setVerticaMetrics(vertica);
138                                 LinkedHashMap<String, String> desc = new LinkedHashMap<>();
139                                 desc.put("policyDescription", getDescription(value));
140                                 policyAdapter.setDescription(desc);
141                                 LinkedHashMap<String, Object> attributes = new LinkedHashMap<>();
142                                 attributes.put("attributes", getAttributes(value));
143                                 policyAdapter.setAttributeFields(attributes);
144                             }
145                         })));
146     }
147
148     // get vertica metrics data from the table
149     private String getVertica(String policyName) {
150         JsonArray data = PolicyManagerServlet.getPolicyNames();
151         for (int i = 0; i < data.size(); i++) {
152             if (policyName.equals(data.getJsonObject(i).getJsonString(KEY_SERVICE_TYPE_POLICY_NAME).getString())) {
153                 return data.getJsonObject(i).getJsonString("verticaMetrics").getString();
154             }
155         }
156         return null;
157     }
158
159     // get policy description from the table
160     private String getDescription(String policyName) {
161         JsonArray data = PolicyManagerServlet.getPolicyNames();
162         for (int i = 0; i < data.size(); i++) {
163             if (policyName.equals(data.getJsonObject(i).getJsonString(KEY_SERVICE_TYPE_POLICY_NAME).getString())) {
164                 return data.getJsonObject(i).getJsonString("policyDescription").getString();
165             }
166         }
167         return null;
168     }
169
170     // get Attributes
171     private JsonObject getAttributes(String policyName) {
172         JsonArray data = PolicyManagerServlet.getPolicyNames();
173         for (int i = 0; i < data.size(); i++) {
174             if (policyName.equals(data.getJsonObject(i).getJsonString(KEY_SERVICE_TYPE_POLICY_NAME).getString())) {
175                 return data.getJsonObject(i).getJsonObject("attributes");
176             }
177         }
178         return null;
179     }
180 }