Change the model to fix TCA
[clamp.git] / src / main / java / org / onap / clamp / clds / client / req / TcaRequestFormatter.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2017 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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  */
23
24 package org.onap.clamp.clds.client.req;
25
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28 import com.fasterxml.jackson.databind.node.ArrayNode;
29 import com.fasterxml.jackson.databind.node.ObjectNode;
30 import com.fasterxml.jackson.dataformat.yaml.snakeyaml.Yaml;
31
32 import java.util.Map;
33
34 import org.onap.clamp.clds.exception.TcaRequestFormatterException;
35 import org.onap.clamp.clds.model.prop.ModelProperties;
36 import org.onap.clamp.clds.model.prop.Tca;
37 import org.onap.clamp.clds.model.prop.TcaItem;
38 import org.onap.clamp.clds.model.prop.TcaThreshold;
39 import org.onap.clamp.clds.model.refprop.RefProp;
40
41 /**
42  * Construct the requests for TCA policy and SDC.
43  *
44  */
45 public class TcaRequestFormatter {
46     protected static final EELFLogger logger        = EELFManager.getInstance().getLogger(TcaRequestFormatter.class);
47     protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
48
49     /**
50      * Hide the default constructor.
51      */
52     private TcaRequestFormatter() {
53
54     }
55
56     /**
57      * Format Tca Policy JSON request.
58      *
59      * @param refProp
60      *            The refProp generally created by Spring, it's an access on the
61      *            clds-references.properties file
62      * @param modelProperties
63      *            The Model Prop created from BPMN JSON and BPMN properties JSON
64      * @return The Json string containing that should be sent to policy
65      */
66     public static String createPolicyJson(RefProp refProp, ModelProperties modelProperties) {
67         try {
68             String service = modelProperties.getGlobal().getService();
69
70             Tca tca = modelProperties.getType(Tca.class);
71             modelProperties.setCurrentModelElementId(tca.getId());
72             ObjectNode rootNode = (ObjectNode) refProp.getJsonTemplate("tca.template", service);
73             ((ObjectNode) rootNode.get("cdap-tca-hi-lo_policy").get("metricsPerEventName").get(0)).put("policyName",
74                     modelProperties.getCurrentPolicyScopeAndPolicyName());
75             ((ObjectNode) rootNode.get("cdap-tca-hi-lo_policy").get("metricsPerEventName").get(0)).put("eventName",
76                     tca.getTcaItem().getEventName());
77
78             ObjectNode thresholdsParent = ((ObjectNode) rootNode.get("cdap-tca-hi-lo_policy").get("metricsPerEventName")
79                     .get(0));
80
81             addThresholds(refProp, service, thresholdsParent, tca.getTcaItem(), modelProperties);
82
83             String tcaPolicyReq = rootNode.toString();
84             logger.info("tcaPolicyReq=" + tcaPolicyReq);
85             return tcaPolicyReq;
86         } catch (Exception e) {
87             throw new TcaRequestFormatterException("Exception caught when attempting to create the policy JSON", e);
88         }
89     }
90
91     /**
92      * Add threshold values to the existing policy JSON.
93      *
94      * @param refProp
95      *            The refProp generally created by Spring, it's an access on the
96      *            clds-references.properties file
97      * @param service
98      *            The Service value extracted from Global section of the Bpmn
99      *            Properties JSON
100      * @param appendToNode
101      *            The JSON structure from where the thresholds section must be
102      *            added
103      * @param tcaItem
104      *            The TCA item contained in the Tca object
105      * @param modelProperties
106      *            The Model Properties created from BPMN JSON and BPMN
107      *            properties JSON
108      */
109     private static void addThresholds(RefProp refProp, String service, ObjectNode appendToNode, TcaItem tcaItem,
110             ModelProperties modelProperties) {
111         try {
112             ArrayNode tcaNodes = appendToNode.withArray("thresholds");
113             ObjectNode tcaNode = (ObjectNode) refProp.getJsonTemplate("tca.thresholds.template", service);
114
115             for (TcaThreshold tcaThreshold : tcaItem.getTcaThresholds()) {
116                 tcaNode.put("controlLoopSchema", tcaThreshold.getControlLoopSchema());
117                 tcaNode.put("closedLoopControlName", modelProperties.getControlNameAndPolicyUniqueId());
118                 tcaNode.put("fieldPath", tcaThreshold.getFieldPath());
119                 tcaNode.put("thresholdValue", tcaThreshold.getThreshold());
120                 tcaNode.put("direction", tcaThreshold.getOperator());
121                 tcaNode.put("closedLoopEventStatus", tcaThreshold.getClosedLoopEventStatus());
122                 tcaNodes.add(tcaNode);
123             }
124         } catch (Exception e) {
125             throw new TcaRequestFormatterException("Exception caught when attempting to create the thresholds JSON", e);
126         }
127     }
128
129     /**
130      * This method updates the blueprint that is received in the UI with the TCA
131      * Json.
132      * 
133      * @param refProp
134      *            * The refProp generally created by Spring, it's an access on
135      *            the clds-references.properties file
136      * @param modelProperties
137      *            The Model Prop created from BPMN JSON and BPMN properties JSON
138      * @param yamlValue
139      *            The yaml string received from the UI
140      * @return The updated YAML as a string
141      */
142     public static String updatedBlueprintWithConfiguration(RefProp refProp, ModelProperties modelProperties,
143             String yamlValue) {
144         try {
145             String jsonPolicy = createPolicyJson(refProp, modelProperties);
146
147             logger.info("Yaml that will be updated:" + yamlValue);
148             Yaml yaml = new Yaml();
149
150             Map<String, Object> loadedYaml = (Map<String, Object>) yaml.load(yamlValue);
151
152             Map<String, Object> nodeTemplates = (Map<String, Object>) loadedYaml.get("node_templates");
153             Map<String, Object> tcaObject = (Map<String, Object>) nodeTemplates.get("tca_tca");
154             Map<String, Object> propsObject = (Map<String, Object>) tcaObject.get("properties");
155             Map<String, Object> appPreferences = (Map<String, Object>) propsObject.get("app_preferences");
156             appPreferences.put("tca_policy", jsonPolicy);
157
158             String blueprint = yaml.dump(loadedYaml);
159             logger.info("Yaml updated:" + blueprint);
160
161             return blueprint;
162         } catch (Exception e) {
163             throw new TcaRequestFormatterException("Exception caught when attempting to update the blueprint", e);
164         }
165     }
166 }