aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/org/onap/clamp/clds/client/req/TcaRequestFormatter.java
blob: 8a6f7e8aa95451bc371da593db1d0d9541641137 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
/*-
 * ============LICENSE_START=======================================================
 * ONAP CLAMP
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights
 *                             reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END============================================
 * ===================================================================
 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
 */

package org.onap.clamp.clds.client.req;

import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.dataformat.yaml.snakeyaml.Yaml;

import java.util.HashMap;
import java.util.Map;

import org.onap.clamp.clds.exception.TcaRequestFormatterException;
import org.onap.clamp.clds.model.prop.ModelProperties;
import org.onap.clamp.clds.model.prop.Tca;
import org.onap.clamp.clds.model.prop.TcaItem;
import org.onap.clamp.clds.model.prop.TcaThreshold;
import org.onap.clamp.clds.model.refprop.RefProp;

/**
 * Construct the requests for TCA policy and SDC.
 *
 */
public class TcaRequestFormatter {
    protected static final EELFLogger logger        = EELFManager.getInstance().getLogger(TcaRequestFormatter.class);
    protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();

    /**
     * Hide the default constructor.
     */
    private TcaRequestFormatter() {

    }

    /**
     * Format Tca Policy JSON request.
     *
     * @param refProp
     *            The refProp generally created by Spring, it's an access on the
     *            clds-references.properties file
     * @param modelProperties
     *            The Model Prop created from BPMN JSON and BPMN properties JSON
     * @return The Json string containing that should be sent to policy
     */
    public static String createPolicyJson(RefProp refProp, ModelProperties modelProperties) {
        try {
            String service = modelProperties.getGlobal().getService();

            Tca tca = modelProperties.getType(Tca.class);
            modelProperties.setCurrentModelElementId(tca.getId());
            ObjectNode rootNode = (ObjectNode) refProp.getJsonTemplate("tca.policy.template", service);
            String policyName = modelProperties.getCurrentPolicyScopeAndPolicyName();
            ((ObjectNode) rootNode).put("policyName", policyName);
            ((ObjectNode) rootNode).put("description", "MicroService vCPE Policy");
            ((ObjectNode) rootNode.get("content")).replace("tca_policy", createPolicyContent(refProp, modelProperties, service, policyName, tca));

            String tcaPolicyReq = rootNode.toString();
            logger.info("tcaPolicyReq=" + tcaPolicyReq);
            return tcaPolicyReq;
        } catch (Exception e) {
            throw new TcaRequestFormatterException("Exception caught when attempting to create the policy JSON", e);
        }
    }

    /**
     * Format Tca Policy Content JSON
     *
     * @param refProp
     *            The refProp generally created by Spring, it's an access on the
     *            clds-references.properties file
     * @param modelProperties
     *            The Model Prop created from BPMN JSON and BPMN properties JSON
     * @return The Json string containing that should be sent to policy
     */
    public static JsonNode createPolicyContent(RefProp refProp, ModelProperties modelProperties, String service, String policyName, Tca tca) {
        try {
            if (null == service) {
                service = modelProperties.getGlobal().getService();
            }
            if (null == tca){
                tca = modelProperties.getType(Tca.class);
                modelProperties.setCurrentModelElementId(tca.getId());
            }
            if (null == policyName) {
                policyName = modelProperties.getCurrentPolicyScopeAndPolicyName();
            }
            ObjectNode rootNode = (ObjectNode) refProp.getJsonTemplate("tca.template", service);
            ((ObjectNode) rootNode.get("metricsPerEventName").get(0)).put("eventName", tca.getTcaItem().getEventName());
            ((ObjectNode) rootNode.get("metricsPerEventName").get(0)).put("policyName", policyName);
            ((ObjectNode) rootNode.get("metricsPerEventName").get(0)).put("controlLoopSchemaType", tca.getTcaItem().getControlLoopSchemaType());
            ObjectNode thresholdsParent = ((ObjectNode) rootNode.get("metricsPerEventName").get(0));

            addThresholds(refProp, service, thresholdsParent, tca.getTcaItem(), modelProperties);

            logger.info("tcaPolicyContent=" + rootNode.toString());
            return (JsonNode) rootNode;
        } catch (Exception e) {
            throw new TcaRequestFormatterException("Exception caught when attempting to create the policy content JSON", e);
        }
    }

    /**
     * Add threshold values to the existing policy JSON.
     *
     * @param refProp
     *            The refProp generally created by Spring, it's an access on the
     *            clds-references.properties file
     * @param service
     *            The Service value extracted from Global section of the Bpmn
     *            Properties JSON
     * @param appendToNode
     *            The JSON structure from where the thresholds section must be
     *            added
     * @param tcaItem
     *            The TCA item contained in the Tca object
     * @param modelProperties
     *            The Model Properties created from BPMN JSON and BPMN
     *            properties JSON
     */
    private static void addThresholds(RefProp refProp, String service, ObjectNode appendToNode, TcaItem tcaItem,
            ModelProperties modelProperties) {
        try {
            ArrayNode tcaNodes = appendToNode.withArray("thresholds");
            ObjectNode tcaNode = (ObjectNode) refProp.getJsonTemplate("tca.thresholds.template", service);

            for (TcaThreshold tcaThreshold : tcaItem.getTcaThresholds()) {
                tcaNode.put("closedLoopControlName", modelProperties.getControlNameAndPolicyUniqueId());
                tcaNode.put("fieldPath", tcaThreshold.getFieldPath());
                tcaNode.put("thresholdValue", tcaThreshold.getThreshold());
                tcaNode.put("direction", tcaThreshold.getOperator());
                tcaNode.put("closedLoopEventStatus", tcaThreshold.getClosedLoopEventStatus());
                tcaNodes.add(tcaNode);
            }
        } catch (Exception e) {
            throw new TcaRequestFormatterException("Exception caught when attempting to create the thresholds JSON", e);
        }
    }

    /**
     * This method updates the blueprint that is received in the UI with the TCA
     * Json.
     * 
     * @param refProp
     *            * The refProp generally created by Spring, it's an access on
     *            the clds-references.properties file
     * @param modelProperties
     *            The Model Prop created from BPMN JSON and BPMN properties JSON
     * @param yamlValue
     *            The yaml string received from the UI
     * @return The updated YAML as a string
     */
    public static String updatedBlueprintWithConfiguration(RefProp refProp, ModelProperties modelProperties,
            String yamlValue) {
        try {
            String jsonPolicy = ((ObjectNode) createPolicyContent(refProp, modelProperties, null, null, null)).toString();

            logger.info("Yaml that will be updated:" + yamlValue);
            Yaml yaml = new Yaml();

            Map<String, Object> loadedYaml = (Map<String, Object>) yaml.load(yamlValue);

            Map<String, Object> nodeTemplates = (Map<String, Object>) loadedYaml.get("node_templates");
            //add policy_0 section in blueprint
            Map<String, Object> policyObject = new HashMap<String, Object> ();
            Map<String, Object> policyIdObject = new HashMap<String, Object> ();
            String policyPrefix = refProp.getStringValue("tca.policyid.prefix");
            policyIdObject.put("policy_id", policyPrefix + modelProperties.getCurrentPolicyScopeAndPolicyName());
            policyObject.put("type", "dcae.nodes.policy");
            policyObject.put("properties", policyIdObject);
            nodeTemplates.put("policy_0", policyObject);

            Map<String, Object> tcaObject = (Map<String, Object>) nodeTemplates.get("tca_tca");
            Map<String, Object> propsObject = (Map<String, Object>) tcaObject.get("properties");
            Map<String, Object> appPreferences = (Map<String, Object>) propsObject.get("app_preferences");
            appPreferences.put("tca_policy", jsonPolicy);

            String blueprint = yaml.dump(loadedYaml);
            logger.info("Yaml updated:" + blueprint);

            return blueprint;
        } catch (Exception e) {
            throw new TcaRequestFormatterException("Exception caught when attempting to update the blueprint", e);
        }
    }
}