Merge "Add template and tosca model entities and repositories"
[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.Type;
55 import org.hibernate.annotations.TypeDef;
56 import org.hibernate.annotations.TypeDefs;
57 import org.onap.clamp.dao.model.jsontype.StringJsonUserType;
58 import org.onap.clamp.loop.Loop;
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 implements Serializable, Policy {
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     @Expose
82     @Type(type = "json")
83     @Column(columnDefinition = "json", name = "configurations_json")
84     private JsonObject configurationsJson;
85
86     @Expose
87     @Type(type = "json")
88     @Column(columnDefinition = "json", name = "json_representation", nullable = false)
89     private JsonObject jsonRepresentation;
90
91     @ManyToOne(fetch = FetchType.LAZY)
92     @JoinColumn(name = "loop_id", nullable = false)
93     private Loop loop;
94
95     @Expose
96     @ManyToOne(fetch = FetchType.EAGER)
97     @JoinColumns({ @JoinColumn(name = "policy_model_type", referencedColumnName = "policy_model_type"),
98         @JoinColumn(name = "policy_model_version", referencedColumnName = "version") })
99     private PolicyModel policyModel;
100
101     public OperationalPolicy() {
102         // Serialization
103     }
104
105     /**
106      * The constructor.
107      *
108      * @param name               The name of the operational policy
109      * @param loop               The loop that uses this operational policy
110      * @param configurationsJson The operational policy property in the format of
111      *                           json
112      */
113     public OperationalPolicy(String name, Loop loop, JsonObject configurationsJson) {
114         this.name = name;
115         this.loop = loop;
116         this.configurationsJson = configurationsJson;
117         LegacyOperationalPolicy.preloadConfiguration(this.configurationsJson, loop);
118         try {
119             this.jsonRepresentation = OperationalPolicyRepresentationBuilder
120                     .generateOperationalPolicySchema(loop.getModelService());
121         } catch (JsonSyntaxException | IOException | NullPointerException e) {
122             logger.error("Unable to generate the operational policy Schema ... ", e);
123             this.jsonRepresentation = new JsonObject();
124         }
125     }
126
127     @Override
128     public String getName() {
129         return name;
130     }
131
132     public void setLoop(Loop loopName) {
133         this.loop = loopName;
134     }
135
136     public Loop getLoop() {
137         return loop;
138     }
139
140     public JsonObject getConfigurationsJson() {
141         return configurationsJson;
142     }
143
144     public void setConfigurationsJson(JsonObject configurationsJson) {
145         this.configurationsJson = configurationsJson;
146     }
147
148     /**
149      * policyModel getter.
150      * 
151      * @return the policyModel
152      */
153     public PolicyModel getPolicyModel() {
154         return policyModel;
155     }
156
157     /**
158      * policyModel setter.
159      * 
160      * @param policyModel the policyModel to set
161      */
162     public void setPolicyModel(PolicyModel policyModel) {
163         this.policyModel = policyModel;
164     }
165
166     /**
167      * name setter.
168      * 
169      * @param name the name to set
170      */
171     public void setName(String name) {
172         this.name = name;
173     }
174
175     @Override
176     public JsonObject getJsonRepresentation() {
177         return jsonRepresentation;
178     }
179
180     void setJsonRepresentation(JsonObject jsonRepresentation) {
181         this.jsonRepresentation = jsonRepresentation;
182     }
183
184     @Override
185     public int hashCode() {
186         final int prime = 31;
187         int result = 1;
188         result = prime * result + ((name == null) ? 0 : name.hashCode());
189         return result;
190     }
191
192     @Override
193     public boolean equals(Object obj) {
194         if (this == obj) {
195             return true;
196         }
197         if (obj == null) {
198             return false;
199         }
200         if (getClass() != obj.getClass()) {
201             return false;
202         }
203         OperationalPolicy other = (OperationalPolicy) obj;
204         if (name == null) {
205             if (other.name != null) {
206                 return false;
207             }
208         } else if (!name.equals(other.name)) {
209             return false;
210         }
211         return true;
212     }
213
214     /**
215      * Create policy Yaml from json defined here.
216      * 
217      * @return A string containing Yaml
218      */
219     public String createPolicyPayloadYaml() {
220         JsonObject policyPayloadResult = new JsonObject();
221
222         policyPayloadResult.addProperty("tosca_definitions_version", "tosca_simple_yaml_1_0_0");
223
224         JsonObject topologyTemplateNode = new JsonObject();
225         policyPayloadResult.add("topology_template", topologyTemplateNode);
226
227         JsonArray policiesArray = new JsonArray();
228         topologyTemplateNode.add("policies", policiesArray);
229
230         JsonObject operationalPolicy = new JsonObject();
231         policiesArray.add(operationalPolicy);
232
233         JsonObject operationalPolicyDetails = new JsonObject();
234         operationalPolicy.add(this.name, operationalPolicyDetails);
235         operationalPolicyDetails.addProperty("type", "onap.policies.controlloop.Operational");
236         operationalPolicyDetails.addProperty("version", "1.0.0");
237
238         JsonObject metadata = new JsonObject();
239         operationalPolicyDetails.add("metadata", metadata);
240         metadata.addProperty("policy-id", this.name);
241
242         operationalPolicyDetails.add("properties", LegacyOperationalPolicy
243                 .reworkPayloadAttributes(this.configurationsJson.get("operational_policy").deepCopy()));
244
245         DumperOptions options = new DumperOptions();
246         options.setIndent(2);
247         options.setPrettyFlow(true);
248         options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
249         Gson gson = new GsonBuilder().create();
250
251         return (new Yaml(options)).dump(gson.fromJson(gson.toJson(policyPayloadResult), Map.class));
252     }
253
254     @Override
255     public String createPolicyPayload() throws UnsupportedEncodingException {
256         // Now using the legacy payload fo Dublin
257         JsonObject payload = new JsonObject();
258         payload.addProperty("policy-id", this.getName());
259         payload.addProperty("content", URLEncoder.encode(LegacyOperationalPolicy.createPolicyPayloadYamlLegacy(
260                 this.configurationsJson.get("operational_policy")), StandardCharsets.UTF_8.toString()));
261         String opPayload = new GsonBuilder().setPrettyPrinting().create().toJson(payload);
262         logger.info("Operational policy payload: " + opPayload);
263         return opPayload;
264     }
265
266     /**
267      * Return a map containing all Guard policies indexed by Guard policy Name.
268      *
269      * @return The Guards map
270      */
271     public Map<String, String> createGuardPolicyPayloads() {
272         Map<String, String> result = new HashMap<>();
273
274         JsonElement guardsList = this.getConfigurationsJson().get("guard_policies");
275         if (guardsList != null) {
276             for (JsonElement guardElem : guardsList.getAsJsonArray()) {
277                 result.put(guardElem.getAsJsonObject().get("policy-id").getAsString(),
278                         new GsonBuilder().create().toJson(guardElem));
279             }
280         }
281         logger.info("Guard policy payload: " + result);
282         return result;
283     }
284
285     /**
286     * Regenerate the Operational Policy Json Representation.
287     *
288     */
289     public void updateJsonRepresentation() {
290         try {
291             this.jsonRepresentation = OperationalPolicyRepresentationBuilder
292                     .generateOperationalPolicySchema(loop.getModelService());
293         } catch (JsonSyntaxException | IOException | NullPointerException e) {
294             logger.error("Unable to generate the operational policy Schema ... ", e);
295             this.jsonRepresentation = new JsonObject();
296         }
297     }
298 }