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