6b8f04397fbc65633a4769611848a1f7c3b25394
[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  * 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  */
23
24 package org.onap.clamp.clds.client.req.tca;
25
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28
29 import com.google.gson.JsonArray;
30 import com.google.gson.JsonObject;
31 import java.io.IOException;
32 import java.util.Map;
33
34 import org.onap.clamp.clds.config.ClampProperties;
35 import org.onap.clamp.clds.exception.TcaRequestFormatterException;
36 import org.onap.clamp.clds.model.properties.ModelProperties;
37 import org.onap.clamp.clds.model.properties.Tca;
38 import org.onap.clamp.clds.model.properties.TcaItem;
39 import org.onap.clamp.clds.model.properties.TcaThreshold;
40 import org.onap.clamp.clds.util.JsonUtils;
41 import org.yaml.snakeyaml.Yaml;
42
43 /**
44  * Construct the requests for TCA policy and SDC.
45  */
46 public class TcaRequestFormatter {
47
48     protected static final EELFLogger logger = EELFManager.getInstance().getLogger(TcaRequestFormatter.class);
49     protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
50
51     /**
52      * Hide the default constructor.
53      */
54     private TcaRequestFormatter() {
55     }
56
57     /**
58      * Format Tca Policy JSON request.
59      *
60      * @param refProp
61      *            The refProp generally created by Spring, it's an access on the
62      *            clds-references.properties file
63      * @param modelProperties
64      *            The Model Prop created from BPMN JSON and BPMN properties JSON
65      * @return The Json string containing that should be sent to policy
66      */
67     public static String createPolicyJson(ClampProperties refProp, ModelProperties modelProperties) {
68         try {
69             String service = modelProperties.getGlobal().getService();
70             Tca tca = modelProperties.getType(Tca.class);
71             modelProperties.setCurrentModelElementId(tca.getId());
72             // Always one tcaItem so must be set to id 0
73             modelProperties.setPolicyUniqueId("0");
74             JsonObject rootNode = refProp.getJsonTemplate("tca.policy.template", service ).getAsJsonObject();
75             String policyName = modelProperties.getCurrentPolicyScopeAndPolicyName();
76             rootNode.addProperty("policyName", policyName);
77             rootNode.get("content").getAsJsonObject().add("tca_policy",
78                     createPolicyContent(refProp, modelProperties, service, policyName, tca));
79             String tcaPolicyReq = rootNode.toString();
80             logger.info("tcaPolicyReq=" + tcaPolicyReq);
81             return tcaPolicyReq;
82         } catch (IOException e) {
83             throw new TcaRequestFormatterException("Exception caught when attempting to create the policy JSON", e);
84         }
85     }
86
87     /**
88      * Format Tca Policy Content JSON
89      *
90      * @param refProp
91      *            The refProp generally created by Spring, it's an access on the
92      *            clds-references.properties file
93      * @param modelProperties
94      *            The Model Prop created from BPMN JSON and BPMN properties JSON
95      * @param service
96      *            The service ID, if not specified getGlobal.getService will be
97      *            used
98      * @param policyName
99      *            The policyName, if not specified the
100      *            modelProperties.getCurrentPolicyScopeAndPolicyName will be
101      *            used
102      * @param tca
103      *            The Tca object, if not specified the
104      *            modelProperties.setCurrentModelElementId will be used
105      * @return The Json node containing what should be sent to policy
106      */
107     public static JsonObject createPolicyContent(ClampProperties refProp, ModelProperties modelProperties, String service,
108             String policyName, Tca tca) {
109         try {
110             String serviceToUse = service;
111             String policyNameToUse = policyName;
112             Tca tcaToUse = tca;
113             if (serviceToUse == null) {
114                 serviceToUse = modelProperties.getGlobal().getService();
115             }
116             if (tcaToUse == null) {
117                 tcaToUse = modelProperties.getType(Tca.class);
118                 modelProperties.setCurrentModelElementId(tcaToUse.getId());
119             }
120             if (policyNameToUse == null) {
121                 policyNameToUse = modelProperties.getCurrentPolicyScopeAndPolicyName();
122             }
123             JsonObject rootNode = refProp.getJsonTemplate("tca.template", serviceToUse).getAsJsonObject();
124             JsonObject metricsPerEventName = rootNode.get("metricsPerEventName").getAsJsonArray().get(0).getAsJsonObject();
125             metricsPerEventName.addProperty("eventName", tcaToUse.getTcaItem().getEventName());
126             metricsPerEventName.addProperty("policyName", policyNameToUse);
127             metricsPerEventName.addProperty("controlLoopSchemaType",tcaToUse.getTcaItem().getControlLoopSchemaType());
128             addThresholds(refProp, serviceToUse, metricsPerEventName, tcaToUse.getTcaItem(), modelProperties);
129             logger.info("tcaPolicyContent=" + rootNode.toString());
130             return rootNode;
131         } catch (IOException e) {
132             throw new TcaRequestFormatterException("Exception caught when attempting to create the policy content JSON",
133                     e);
134         }
135     }
136
137     /**
138      * Add threshold values to the existing policy JSON.
139      *
140      * @param refProp
141      *            The refProp generally created by Spring, it's an access on the
142      *            clds-references.properties file
143      * @param service
144      *            The Service value extracted from Global section of the Bpmn
145      *            Properties JSON
146      * @param appendToNode
147      *            The JSON structure from where the thresholds section must be
148      *            added
149      * @param tcaItem
150      *            The TCA item contained in the Tca object
151      * @param modelProperties
152      *            The Model Properties created from BPMN JSON and BPMN
153      *            properties JSON
154      */
155     private static void addThresholds(ClampProperties refProp, String service, JsonObject appendToNode, TcaItem tcaItem,
156             ModelProperties modelProperties) {
157         JsonArray tcaNodes = appendToNode.get("thresholds").getAsJsonArray();
158         try {
159             for (TcaThreshold tcaThreshold : tcaItem.getTcaThresholds()) {
160                 JsonObject tcaNode = refProp.getJsonTemplate("tca.thresholds.template", service).getAsJsonObject();
161                 tcaNode.addProperty("closedLoopControlName", modelProperties.getControlNameAndPolicyUniqueId());
162                 tcaNode.addProperty("fieldPath", tcaThreshold.getFieldPath());
163                 tcaNode.addProperty("thresholdValue", tcaThreshold.getThreshold());
164                 tcaNode.addProperty("direction", tcaThreshold.getOperator());
165                 tcaNode.addProperty("closedLoopEventStatus", tcaThreshold.getClosedLoopEventStatus());
166                 tcaNodes.add(tcaNode);
167             }
168         } catch (IOException e) {
169             throw new TcaRequestFormatterException("Exception caught when attempting to create the thresholds JSON", e);
170         }
171     }
172
173     /**
174      * This method updates the blueprint that is received in the UI with the TCA
175      * Json.
176      * 
177      * @param refProp
178      *            * The refProp generally created by Spring, it's an access on
179      *            the clds-references.properties file
180      * @param modelProperties
181      *            The Model Prop created from BPMN JSON and BPMN properties JSON
182      * @param yamlValue
183      *            The yaml string received from the UI
184      * @return The updated YAML as a string
185      */
186     public static String updatedBlueprintWithConfiguration(ClampProperties refProp, ModelProperties modelProperties,
187             String yamlValue) {
188         String jsonPolicy = JsonUtils.GSON.toJson(createPolicyContent(refProp, modelProperties, null, null, null));
189         logger.info("Yaml that will be updated:" + yamlValue);
190         Yaml yaml = new Yaml();
191         Map<String, Object> loadedYaml = (Map<String, Object>) yaml.load(yamlValue);
192         Map<String, Object> nodeTemplates = (Map<String, Object>) loadedYaml.get("node_templates");
193         Map<String, Object> tcaObject = (Map<String, Object>) nodeTemplates.get("tca_tca");
194         Map<String, Object> propsObject = (Map<String, Object>) tcaObject.get("properties");
195         Map<String, Object> appPreferences = (Map<String, Object>) propsObject.get("app_preferences");
196         appPreferences.put("tca_policy", jsonPolicy);
197         String blueprint = yaml.dump(loadedYaml);
198         logger.info("Yaml updated:" + blueprint);
199         return blueprint;
200     }
201 }