Merge "Fixed Sonar issues in the onap.clamp.clds.client packages"
[clamp.git] / src / main / java / org / onap / clamp / clds / client / req / tca / TcaRequestFormatter.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights
6  *                             reserved.
7  * ================================================================================
8  * Modifications Copyright (c) 2019 Samsung
9  * ================================================================================
10  * Licensed under the Apache License, Version 2.0 (the "License");
11  * you may not use this file except in compliance with the License.
12  * You may obtain a copy of the License at
13  *
14  * http://www.apache.org/licenses/LICENSE-2.0
15  *
16  * Unless required by applicable law or agreed to in writing, software
17  * distributed under the License is distributed on an "AS IS" BASIS,
18  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  * See the License for the specific language governing permissions and
20  * limitations under the License.
21  * ============LICENSE_END============================================
22  * ===================================================================
23  * 
24  */
25
26 package org.onap.clamp.clds.client.req.tca;
27
28 import com.att.eelf.configuration.EELFLogger;
29 import com.att.eelf.configuration.EELFManager;
30
31 import com.google.gson.JsonArray;
32 import com.google.gson.JsonObject;
33 import java.io.IOException;
34 import java.util.Map;
35
36 import org.onap.clamp.clds.config.ClampProperties;
37 import org.onap.clamp.clds.exception.TcaRequestFormatterException;
38 import org.onap.clamp.clds.model.properties.ModelProperties;
39 import org.onap.clamp.clds.model.properties.Tca;
40 import org.onap.clamp.clds.model.properties.TcaItem;
41 import org.onap.clamp.clds.model.properties.TcaThreshold;
42 import org.onap.clamp.clds.util.JsonUtils;
43 import org.yaml.snakeyaml.Yaml;
44
45 /**
46  * Construct the requests for TCA policy and SDC.
47  */
48 public class TcaRequestFormatter {
49
50     protected static final EELFLogger logger = EELFManager.getInstance().getLogger(TcaRequestFormatter.class);
51     protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
52
53     /**
54      * Hide the default constructor.
55      */
56     private TcaRequestFormatter() {
57     }
58
59     /**
60      * Format Tca Policy JSON request.
61      *
62      * @param refProp
63      *            The refProp generally created by Spring, it's an access on the
64      *            clds-references.properties file
65      * @param modelProperties
66      *            The Model Prop created from BPMN JSON and BPMN properties JSON
67      * @return The Json string containing that should be sent to policy
68      */
69     public static String createPolicyJson(ClampProperties refProp, ModelProperties modelProperties) {
70         try {
71             String service = modelProperties.getGlobal().getService();
72             Tca tca = modelProperties.getType(Tca.class);
73             modelProperties.setCurrentModelElementId(tca.getId());
74             // Always one tcaItem so must be set to id 0
75             modelProperties.setPolicyUniqueId("0");
76             JsonObject rootNode = refProp.getJsonTemplate("tca.policy.template", service ).getAsJsonObject();
77             String policyName = modelProperties.getCurrentPolicyScopeAndPolicyName();
78             rootNode.addProperty("policyName", policyName);
79             rootNode.get("content").getAsJsonObject().add("tca_policy",
80                     createPolicyContent(refProp, modelProperties, service, policyName, tca));
81             String tcaPolicyReq = rootNode.toString();
82             logger.info("tcaPolicyReq=" + tcaPolicyReq);
83             return tcaPolicyReq;
84         } catch (IOException e) {
85             throw new TcaRequestFormatterException("Exception caught when attempting to create the policy JSON", e);
86         }
87     }
88
89     /**
90      * Format Tca Policy Content JSON
91      *
92      * @param refProp
93      *            The refProp generally created by Spring, it's an access on the
94      *            clds-references.properties file
95      * @param modelProperties
96      *            The Model Prop created from BPMN JSON and BPMN properties JSON
97      * @param service
98      *            The service ID, if not specified getGlobal.getService will be
99      *            used
100      * @param policyName
101      *            The policyName, if not specified the
102      *            modelProperties.getCurrentPolicyScopeAndPolicyName will be
103      *            used
104      * @param tca
105      *            The Tca object, if not specified the
106      *            modelProperties.setCurrentModelElementId will be used
107      * @return The Json node containing what should be sent to policy
108      */
109     public static JsonObject createPolicyContent(ClampProperties refProp, ModelProperties modelProperties, String service,
110             String policyName, Tca tca) {
111         try {
112             String serviceToUse = service;
113             String policyNameToUse = policyName;
114             Tca tcaToUse = tca;
115             if (serviceToUse == null) {
116                 serviceToUse = modelProperties.getGlobal().getService();
117             }
118             if (tcaToUse == null) {
119                 tcaToUse = modelProperties.getType(Tca.class);
120                 modelProperties.setCurrentModelElementId(tcaToUse.getId());
121             }
122             if (policyNameToUse == null) {
123                 policyNameToUse = modelProperties.getCurrentPolicyScopeAndPolicyName();
124             }
125             JsonObject rootNode = refProp.getJsonTemplate("tca.template", serviceToUse).getAsJsonObject();
126             JsonObject metricsPerEventName = rootNode.get("metricsPerEventName").getAsJsonArray().get(0).getAsJsonObject();
127             metricsPerEventName.addProperty("eventName", tcaToUse.getTcaItem().getEventName());
128             metricsPerEventName.addProperty("policyName", policyNameToUse);
129             metricsPerEventName.addProperty("controlLoopSchemaType",tcaToUse.getTcaItem().getControlLoopSchemaType());
130             addThresholds(refProp, serviceToUse, metricsPerEventName, tcaToUse.getTcaItem(), modelProperties);
131             logger.info("tcaPolicyContent=" + rootNode.toString());
132             return rootNode;
133         } catch (IOException e) {
134             throw new TcaRequestFormatterException("Exception caught when attempting to create the policy content JSON",
135                     e);
136         }
137     }
138
139     /**
140      * Add threshold values to the existing policy JSON.
141      *
142      * @param refProp
143      *            The refProp generally created by Spring, it's an access on the
144      *            clds-references.properties file
145      * @param service
146      *            The Service value extracted from Global section of the Bpmn
147      *            Properties JSON
148      * @param appendToNode
149      *            The JSON structure from where the thresholds section must be
150      *            added
151      * @param tcaItem
152      *            The TCA item contained in the Tca object
153      * @param modelProperties
154      *            The Model Properties created from BPMN JSON and BPMN
155      *            properties JSON
156      */
157     private static void addThresholds(ClampProperties refProp, String service, JsonObject appendToNode, TcaItem tcaItem,
158             ModelProperties modelProperties) {
159         JsonArray tcaNodes = appendToNode.get("thresholds").getAsJsonArray();
160         try {
161             for (TcaThreshold tcaThreshold : tcaItem.getTcaThresholds()) {
162                 JsonObject tcaNode = refProp.getJsonTemplate("tca.thresholds.template", service).getAsJsonObject();
163                 tcaNode.addProperty("closedLoopControlName", modelProperties.getControlNameAndPolicyUniqueId());
164                 tcaNode.addProperty("fieldPath", tcaThreshold.getFieldPath());
165                 tcaNode.addProperty("thresholdValue", tcaThreshold.getThreshold());
166                 tcaNode.addProperty("direction", tcaThreshold.getOperator());
167                 tcaNode.addProperty("closedLoopEventStatus", tcaThreshold.getClosedLoopEventStatus());
168                 tcaNodes.add(tcaNode);
169             }
170         } catch (IOException e) {
171             throw new TcaRequestFormatterException("Exception caught when attempting to create the thresholds JSON", e);
172         }
173     }
174
175     /**
176      * This method updates the blueprint that is received in the UI with the TCA
177      * Json.
178      *
179      * @param refProp
180      *            * The refProp generally created by Spring, it's an access on
181      *            the clds-references.properties file
182      * @param modelProperties
183      *            The Model Prop created from BPMN JSON and BPMN properties JSON
184      * @param yamlValue
185      *            The yaml string received from the UI
186      * @return The updated YAML as a string
187      */
188     public static String updatedBlueprintWithConfiguration(ClampProperties refProp, ModelProperties modelProperties,
189             String yamlValue) {
190         String jsonPolicy = JsonUtils.GSON.toJson(createPolicyContent(refProp, modelProperties, null, null, null));
191         logger.info("Yaml that will be updated:" + yamlValue);
192         Yaml yaml = new Yaml();
193         Map<String, Map> loadedYaml = yaml.load(yamlValue);
194         Map<String, Map> nodeTemplates = loadedYaml.get("node_templates");
195         Map<String, Map> tcaObject = nodeTemplates.get("tca_tca");
196         Map<String, Map> propsObject = tcaObject.get("properties");
197         Map<String, String> appPreferences = propsObject.get("app_preferences");
198         appPreferences.put("tca_policy", jsonPolicy);
199         String blueprint = yaml.dump(loadedYaml);
200         logger.info("Yaml updated:" + blueprint);
201         return blueprint;
202     }
203 }