Update the TCA blueprint format
[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.HashMap;
33 import java.util.Map;
34
35 import org.onap.clamp.clds.exception.TcaRequestFormatterException;
36 import org.onap.clamp.clds.model.prop.ModelProperties;
37 import org.onap.clamp.clds.model.prop.Tca;
38 import org.onap.clamp.clds.model.prop.TcaItem;
39 import org.onap.clamp.clds.model.prop.TcaThreshold;
40 import org.onap.clamp.clds.model.refprop.RefProp;
41
42 /**
43  * Construct the requests for TCA policy and SDC.
44  *
45  */
46 public class TcaRequestFormatter {
47     protected static final EELFLogger logger        = EELFManager.getInstance().getLogger(TcaRequestFormatter.class);
48     protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
49
50     /**
51      * Hide the default constructor.
52      */
53     private TcaRequestFormatter() {
54
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(RefProp refProp, ModelProperties modelProperties) {
68         try {
69             String service = modelProperties.getGlobal().getService();
70
71             Tca tca = modelProperties.getType(Tca.class);
72             modelProperties.setCurrentModelElementId(tca.getId());
73             ObjectNode rootNode = (ObjectNode) refProp.getJsonTemplate("tca.template", service);
74             ((ObjectNode) rootNode.get("cdap-tca-hi-lo_policy").get("metricsPerEventName").get(0)).put("policyName",
75                     modelProperties.getCurrentPolicyScopeAndPolicyName());
76             ((ObjectNode) rootNode.get("cdap-tca-hi-lo_policy").get("metricsPerEventName").get(0)).put("eventName",
77                     tca.getTcaItem().getEventName());
78
79             ObjectNode thresholdsParent = ((ObjectNode) rootNode.get("cdap-tca-hi-lo_policy").get("metricsPerEventName")
80                     .get(0));
81
82             addThresholds(refProp, service, thresholdsParent, tca.getTcaItem(), modelProperties);
83
84             String tcaPolicyReq = rootNode.toString();
85             logger.info("tcaPolicyReq=" + tcaPolicyReq);
86             return tcaPolicyReq;
87         } catch (Exception e) {
88             throw new TcaRequestFormatterException("Exception caught when attempting to create the policy JSON", e);
89         }
90     }
91
92     /**
93      * Add threshold values to the existing policy JSON.
94      *
95      * @param refProp
96      *            The refProp generally created by Spring, it's an access on the
97      *            clds-references.properties file
98      * @param service
99      *            The Service value extracted from Global section of the Bpmn
100      *            Properties JSON
101      * @param appendToNode
102      *            The JSON structure from where the thresholds section must be
103      *            added
104      * @param tcaItem
105      *            The TCA item contained in the Tca object
106      * @param modelProperties
107      *            The Model Properties created from BPMN JSON and BPMN
108      *            properties JSON
109      */
110     private static void addThresholds(RefProp refProp, String service, ObjectNode appendToNode, TcaItem tcaItem,
111             ModelProperties modelProperties) {
112         try {
113             ArrayNode tcaNodes = appendToNode.withArray("thresholds");
114             ObjectNode tcaNode = (ObjectNode) refProp.getJsonTemplate("tca.thresholds.template", service);
115
116             for (TcaThreshold tcaThreshold : tcaItem.getTcaThresholds()) {
117                 tcaNode.put("controlLoopSchema", tcaThreshold.getControlLoopSchema());
118                 tcaNode.put("closedLoopControlName", modelProperties.getControlNameAndPolicyUniqueId());
119                 tcaNode.put("fieldPath", tcaThreshold.getFieldPath());
120                 tcaNode.put("thresholdValue", tcaThreshold.getThreshold());
121                 tcaNode.put("direction", tcaThreshold.getOperator());
122                 tcaNode.put("closedLoopEventStatus", tcaThreshold.getClosedLoopEventStatus());
123                 tcaNodes.add(tcaNode);
124             }
125         } catch (Exception e) {
126             throw new TcaRequestFormatterException("Exception caught when attempting to create the thresholds JSON", e);
127         }
128     }
129
130     /**
131      * This method updates the blueprint that is received in the UI with the TCA
132      * Json.
133      * 
134      * @param refProp
135      *            * The refProp generally created by Spring, it's an access on
136      *            the clds-references.properties file
137      * @param modelProperties
138      *            The Model Prop created from BPMN JSON and BPMN properties JSON
139      * @param yamlValue
140      *            The yaml string received from the UI
141      * @return The updated YAML as a string
142      */
143     public static String updatedBlueprintWithConfiguration(RefProp refProp, ModelProperties modelProperties,
144             String yamlValue) {
145         try {
146             String jsonPolicy = createPolicyJson(refProp, modelProperties);
147
148             logger.info("Yaml that will be updated:" + yamlValue);
149             Yaml yaml = new Yaml();
150
151             Map<String, Object> loadedYaml = (Map<String, Object>) yaml.load(yamlValue);
152
153             Map<String, Object> nodeTemplates = (Map<String, Object>) loadedYaml.get("node_templates");
154             //add policy_0 section in blueprint
155             Map<String, Object> policyObject = new HashMap<String, Object> ();
156             Map<String, Object> policyIdObject = new HashMap<String, Object> ();
157             String policyPrefix = refProp.getStringValue("tca.policyid.prefix");
158             policyIdObject.put("policy_id", policyPrefix + modelProperties.getCurrentPolicyScopeAndPolicyName());
159             policyObject.put("type", "dcae.nodes.policy");
160             policyObject.put("properties", policyIdObject);
161             nodeTemplates.put("policy_0", policyObject);
162
163             Map<String, Object> tcaObject = (Map<String, Object>) nodeTemplates.get("tca_tca");
164             Map<String, Object> propsObject = (Map<String, Object>) tcaObject.get("properties");
165             Map<String, Object> appPreferences = (Map<String, Object>) propsObject.get("app_preferences");
166             appPreferences.put("tca_policy", jsonPolicy);
167
168             String blueprint = yaml.dump(loadedYaml);
169             logger.info("Yaml updated:" + blueprint);
170
171             return blueprint;
172         } catch (Exception e) {
173             throw new TcaRequestFormatterException("Exception caught when attempting to update the blueprint", e);
174         }
175     }
176 }