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