Fix the blueprint for 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.JsonNode;
29 import com.fasterxml.jackson.databind.node.ArrayNode;
30 import com.fasterxml.jackson.databind.node.ObjectNode;
31 import com.fasterxml.jackson.dataformat.yaml.snakeyaml.Yaml;
32
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      * 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             Tca tca = modelProperties.getType(Tca.class);
70             modelProperties.setCurrentModelElementId(tca.getId());
71             ObjectNode rootNode = (ObjectNode) refProp.getJsonTemplate("tca.policy.template", service);
72             String policyName = modelProperties.getCurrentPolicyScopeAndPolicyName();
73             rootNode.put("policyName", policyName);
74             rootNode.put("description", "MicroService vCPE Policy");
75             ((ObjectNode) rootNode.get("content")).replace("tca_policy",
76                     createPolicyContent(refProp, modelProperties, service, policyName, tca));
77             String tcaPolicyReq = rootNode.toString();
78             logger.info("tcaPolicyReq=" + tcaPolicyReq);
79             return tcaPolicyReq;
80         } catch (Exception e) {
81             throw new TcaRequestFormatterException("Exception caught when attempting to create the policy JSON", e);
82         }
83     }
84
85     /**
86      * Format Tca Policy Content JSON
87      *
88      * @param refProp
89      *            The refProp generally created by Spring, it's an access on the
90      *            clds-references.properties file
91      * @param modelProperties
92      *            The Model Prop created from BPMN JSON and BPMN properties JSON
93      * @return The Json string containing that should be sent to policy
94      */
95     public static JsonNode createPolicyContent(RefProp refProp, ModelProperties modelProperties, String service,
96             String policyName, Tca tca) {
97         try {
98             if (null == service) {
99                 service = modelProperties.getGlobal().getService();
100             }
101             if (null == tca) {
102                 tca = modelProperties.getType(Tca.class);
103                 modelProperties.setCurrentModelElementId(tca.getId());
104             }
105             if (null == policyName) {
106                 policyName = modelProperties.getCurrentPolicyScopeAndPolicyName();
107             }
108             ObjectNode rootNode = (ObjectNode) refProp.getJsonTemplate("tca.template", service);
109             ((ObjectNode) rootNode.get("metricsPerEventName").get(0)).put("eventName", tca.getTcaItem().getEventName());
110             ((ObjectNode) rootNode.get("metricsPerEventName").get(0)).put("policyName", policyName);
111             ((ObjectNode) rootNode.get("metricsPerEventName").get(0)).put("controlLoopSchemaType",
112                     tca.getTcaItem().getControlLoopSchemaType());
113             ObjectNode thresholdsParent = ((ObjectNode) rootNode.get("metricsPerEventName").get(0));
114             addThresholds(refProp, service, thresholdsParent, tca.getTcaItem(), modelProperties);
115             logger.info("tcaPolicyContent=" + rootNode.toString());
116             return rootNode;
117         } catch (Exception e) {
118             throw new TcaRequestFormatterException("Exception caught when attempting to create the policy content JSON",
119                     e);
120         }
121     }
122
123     /**
124      * Add threshold values to the existing policy JSON.
125      *
126      * @param refProp
127      *            The refProp generally created by Spring, it's an access on the
128      *            clds-references.properties file
129      * @param service
130      *            The Service value extracted from Global section of the Bpmn
131      *            Properties JSON
132      * @param appendToNode
133      *            The JSON structure from where the thresholds section must be
134      *            added
135      * @param tcaItem
136      *            The TCA item contained in the Tca object
137      * @param modelProperties
138      *            The Model Properties created from BPMN JSON and BPMN
139      *            properties JSON
140      */
141     private static void addThresholds(RefProp refProp, String service, ObjectNode appendToNode, TcaItem tcaItem,
142             ModelProperties modelProperties) {
143         try {
144             ArrayNode tcaNodes = appendToNode.withArray("thresholds");
145             ObjectNode tcaNode = (ObjectNode) refProp.getJsonTemplate("tca.thresholds.template", service);
146             for (TcaThreshold tcaThreshold : tcaItem.getTcaThresholds()) {
147                 tcaNode.put("closedLoopControlName", modelProperties.getControlNameAndPolicyUniqueId());
148                 tcaNode.put("fieldPath", tcaThreshold.getFieldPath());
149                 tcaNode.put("thresholdValue", tcaThreshold.getThreshold());
150                 tcaNode.put("direction", tcaThreshold.getOperator());
151                 tcaNode.put("closedLoopEventStatus", tcaThreshold.getClosedLoopEventStatus());
152                 tcaNodes.add(tcaNode);
153             }
154         } catch (Exception e) {
155             throw new TcaRequestFormatterException("Exception caught when attempting to create the thresholds JSON", e);
156         }
157     }
158
159     /**
160      * This method updates the blueprint that is received in the UI with the TCA
161      * Json.
162      * 
163      * @param refProp
164      *            * The refProp generally created by Spring, it's an access on
165      *            the clds-references.properties file
166      * @param modelProperties
167      *            The Model Prop created from BPMN JSON and BPMN properties JSON
168      * @param yamlValue
169      *            The yaml string received from the UI
170      * @return The updated YAML as a string
171      */
172     public static String updatedBlueprintWithConfiguration(RefProp refProp, ModelProperties modelProperties,
173             String yamlValue) {
174         try {
175             String jsonPolicy = ((ObjectNode) createPolicyContent(refProp, modelProperties, null, null, null))
176                     .toString();
177             logger.info("Yaml that will be updated:" + yamlValue);
178             Yaml yaml = new Yaml();
179             Map<String, Object> loadedYaml = (Map<String, Object>) yaml.load(yamlValue);
180             Map<String, Object> nodeTemplates = (Map<String, Object>) loadedYaml.get("node_templates");
181             // add policy_0 section in blueprint
182             /*
183              * Map<String, Object> policyObject = new HashMap<String, Object>
184              * (); Map<String, Object> policyIdObject = new HashMap<String,
185              * Object> (); String policyPrefix =
186              * refProp.getStringValue("tca.policyid.prefix");
187              * policyIdObject.put("policy_id", policyPrefix +
188              * modelProperties.getCurrentPolicyScopeAndPolicyName());
189              * policyObject.put("type", "dcae.nodes.policy");
190              * policyObject.put("properties", policyIdObject);
191              * nodeTemplates.put("policy_0", policyObject);
192              */
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         } catch (Exception e) {
201             throw new TcaRequestFormatterException("Exception caught when attempting to update the blueprint", e);
202         }
203     }
204 }