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