Change json representation in op policy
[clamp.git] / src / main / java / org / onap / clamp / policy / operational / OperationalPolicy.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2019 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  *
22  */
23
24 package org.onap.clamp.policy.operational;
25
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28 import com.google.gson.Gson;
29 import com.google.gson.GsonBuilder;
30 import com.google.gson.JsonArray;
31 import com.google.gson.JsonElement;
32 import com.google.gson.JsonObject;
33 import com.google.gson.JsonSyntaxException;
34 import com.google.gson.annotations.Expose;
35 import java.io.IOException;
36 import java.io.Serializable;
37 import java.io.UnsupportedEncodingException;
38 import java.net.URLEncoder;
39 import java.nio.charset.StandardCharsets;
40 import java.util.HashMap;
41 import java.util.Map;
42 import javax.persistence.Column;
43 import javax.persistence.Entity;
44 import javax.persistence.FetchType;
45 import javax.persistence.Id;
46 import javax.persistence.JoinColumn;
47 import javax.persistence.JoinColumns;
48 import javax.persistence.ManyToOne;
49 import javax.persistence.Table;
50 import javax.persistence.Transient;
51 import org.hibernate.annotations.TypeDef;
52 import org.hibernate.annotations.TypeDefs;
53 import org.onap.clamp.clds.tosca.ToscaYamlToJsonConvertor;
54 import org.onap.clamp.clds.util.JsonUtils;
55 import org.onap.clamp.dao.model.jsontype.StringJsonUserType;
56 import org.onap.clamp.loop.Loop;
57 import org.onap.clamp.loop.template.LoopElementModel;
58 import org.onap.clamp.loop.template.PolicyModel;
59 import org.onap.clamp.policy.Policy;
60 import org.yaml.snakeyaml.DumperOptions;
61 import org.yaml.snakeyaml.Yaml;
62
63 @Entity
64 @Table(name = "operational_policies")
65 @TypeDefs({@TypeDef(name = "json", typeClass = StringJsonUserType.class)})
66 public class OperationalPolicy extends Policy implements Serializable {
67     /**
68      * The serial version ID.
69      */
70     private static final long serialVersionUID = 6117076450841538255L;
71
72     @Transient
73     private static final EELFLogger logger = EELFManager.getInstance().getLogger(OperationalPolicy.class);
74
75     @Id
76     @Expose
77     @Column(nullable = false, name = "name", unique = true)
78     private String name;
79
80     @ManyToOne(fetch = FetchType.LAZY)
81     @JoinColumn(name = "loop_id", nullable = false)
82     private Loop loop;
83
84     public OperationalPolicy() {
85         // Serialization
86     }
87
88     /**
89      * The constructor.
90      *
91      * @param name               The name of the operational policy
92      * @param loop               The loop that uses this operational policy
93      * @param configurationsJson The operational policy property in the format of
94      *                           json
95      * @param policyModel        The policy model associated if any, can be null
96      * @param loopElementModel   The loop element from which this instance is supposed to be created
97      * @param pdpGroup           The Pdp Group info
98      * @param pdpSubgroup        The Pdp Subgroup info
99      */
100     public OperationalPolicy(String name, Loop loop, JsonObject configurationsJson, PolicyModel policyModel,
101                              LoopElementModel loopElementModel, String pdpGroup, String pdpSubgroup) {
102         this.name = name;
103         this.loop = loop;
104         this.setPolicyModel(policyModel);
105         this.setConfigurationsJson(configurationsJson);
106         this.setPdpGroup(pdpGroup);
107         this.setPdpSubgroup(pdpSubgroup);
108         this.setLoopElementModel(loopElementModel);
109         this.setJsonRepresentation(this.generateJsonRepresentation(policyModel));
110
111     }
112
113     private JsonObject generateJsonRepresentation(PolicyModel policyModel) {
114         JsonObject jsonReturned = new JsonObject();
115         if (policyModel == null) {
116             return new JsonObject();
117         }
118         try {
119             if (isLegacy()) {
120                 // Op policy Legacy case
121                 LegacyOperationalPolicy.preloadConfiguration(jsonReturned, loop);
122                 this.setJsonRepresentation(
123                         OperationalPolicyRepresentationBuilder.generateOperationalPolicySchema(loop.getModelService()));
124             } else {
125                 // Generic Case
126                 this.setJsonRepresentation(JsonUtils.GSON
127                         .fromJson(new ToscaYamlToJsonConvertor().parseToscaYaml(policyModel.getPolicyModelTosca(),
128                                 policyModel.getPolicyModelType()), JsonObject.class));
129             }
130         } catch (JsonSyntaxException | IOException | NullPointerException e) {
131             logger.error("Unable to generate the operational policy Schema ... ", e);
132             this.setJsonRepresentation(new JsonObject());
133         }
134         return jsonReturned;
135     }
136
137     public void setLoop(Loop loopName) {
138         this.loop = loopName;
139     }
140
141     public Loop getLoop() {
142         return loop;
143     }
144
145     @Override
146     public String getName() {
147         return name;
148     }
149
150     /**
151      * name setter.
152      *
153      * @param name the name to set
154      */
155     @Override
156     public void setName(String name) {
157         this.name = name;
158     }
159
160     @Override
161     public int hashCode() {
162         final int prime = 31;
163         int result = 1;
164         result = prime * result + ((name == null) ? 0 : name.hashCode());
165         return result;
166     }
167
168     @Override
169     public boolean equals(Object obj) {
170         if (this == obj) {
171             return true;
172         }
173         if (obj == null) {
174             return false;
175         }
176         if (getClass() != obj.getClass()) {
177             return false;
178         }
179         OperationalPolicy other = (OperationalPolicy) obj;
180         if (name == null) {
181             if (other.name != null) {
182                 return false;
183             }
184         } else if (!name.equals(other.name)) {
185             return false;
186         }
187         return true;
188     }
189
190     public Boolean isLegacy() {
191         return (this.getPolicyModel() != null) && this.getPolicyModel().getPolicyModelType().contains("legacy");
192     }
193
194     /**
195      * Create policy Yaml from json defined here.
196      *
197      * @return A string containing Yaml
198      */
199     public String createPolicyPayloadYaml() {
200         JsonObject policyPayloadResult = new JsonObject();
201
202         policyPayloadResult.addProperty("tosca_definitions_version", "tosca_simple_yaml_1_0_0");
203
204         JsonObject topologyTemplateNode = new JsonObject();
205         policyPayloadResult.add("topology_template", topologyTemplateNode);
206
207         JsonArray policiesArray = new JsonArray();
208         topologyTemplateNode.add("policies", policiesArray);
209
210         JsonObject operationalPolicy = new JsonObject();
211         policiesArray.add(operationalPolicy);
212
213         JsonObject operationalPolicyDetails = new JsonObject();
214         operationalPolicy.add(this.name, operationalPolicyDetails);
215         operationalPolicyDetails.addProperty("type", "onap.policies.controlloop.Operational");
216         operationalPolicyDetails.addProperty("version", "1.0.0");
217
218         JsonObject metadata = new JsonObject();
219         operationalPolicyDetails.add("metadata", metadata);
220         metadata.addProperty("policy-id", this.name);
221
222         operationalPolicyDetails.add("properties", LegacyOperationalPolicy
223                 .reworkPayloadAttributes(this.getConfigurationsJson().get("operational_policy").deepCopy()));
224
225         DumperOptions options = new DumperOptions();
226         options.setIndent(2);
227         options.setPrettyFlow(true);
228         options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
229         Gson gson = new GsonBuilder().create();
230
231         return (new Yaml(options)).dump(gson.fromJson(gson.toJson(policyPayloadResult), Map.class));
232     }
233
234     @Override
235     public String createPolicyPayload() throws UnsupportedEncodingException {
236         if (isLegacy()) {
237             // Now using the legacy payload fo Dublin
238             JsonObject payload = new JsonObject();
239             payload.addProperty("policy-id", this.getName());
240             payload.addProperty("content",
241                     URLEncoder.encode(
242                             LegacyOperationalPolicy
243                                     .createPolicyPayloadYamlLegacy(
244                                             this.getConfigurationsJson().get("operational_policy")),
245                             StandardCharsets.UTF_8.toString()));
246             String opPayload = new GsonBuilder().setPrettyPrinting().create().toJson(payload);
247             logger.info("Operational policy payload: " + opPayload);
248             return opPayload;
249         } else {
250             return super.createPolicyPayload();
251         }
252     }
253
254     /**
255      * Return a map containing all Guard policies indexed by Guard policy Name.
256      *
257      * @return The Guards map
258      */
259     public Map<String, String> createGuardPolicyPayloads() {
260         Map<String, String> result = new HashMap<>();
261
262         if (this.getConfigurationsJson() != null) {
263             JsonElement guardsList = this.getConfigurationsJson().get("guard_policies");
264             if (guardsList != null) {
265                 for (JsonElement guardElem : guardsList.getAsJsonArray()) {
266                     result.put(guardElem.getAsJsonObject().get("policy-id").getAsString(),
267                         new GsonBuilder().create().toJson(guardElem));
268                 }
269             }
270         }
271         logger.info("Guard policy payload: " + result);
272         return result;
273     }
274
275     /**
276      * Regenerate the Operational Policy Json Representation.
277      */
278     public void updateJsonRepresentation() {
279         try {
280             this.setJsonRepresentation(
281                     OperationalPolicyRepresentationBuilder.generateOperationalPolicySchema(loop.getModelService()));
282         } catch (JsonSyntaxException | IOException | NullPointerException e) {
283             logger.error("Unable to generate the operational policy Schema ... ", e);
284             this.setJsonRepresentation(new JsonObject());
285         }
286     }
287 }