aab30bfb6cfde83294e3f82a227c0610c77c7b1f
[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.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     @Expose
83     @ManyToOne(fetch = FetchType.EAGER)
84     @JoinColumns({@JoinColumn(name = "policy_model_type", referencedColumnName = "policy_model_type"),
85             @JoinColumn(name = "policy_model_version", referencedColumnName = "version")})
86     private PolicyModel policyModel;
87
88     public OperationalPolicy() {
89         // Serialization
90     }
91
92     /**
93      * The constructor.
94      *
95      * @param name               The name of the operational policy
96      * @param loop               The loop that uses this operational policy
97      * @param configurationsJson The operational policy property in the format of
98      *                           json
99      * @param policyModel        The policy model associated if any, can be null
100      * @param loopElementModel   The loop element from which this instance is supposed to be created
101      * @param pdpGroup           The Pdp Group info
102      * @param pdpSubgroup        The Pdp Subgroup info
103      */
104     public OperationalPolicy(String name, Loop loop, JsonObject configurationsJson, PolicyModel policyModel,
105                              LoopElementModel loopElementModel, String pdpGroup, String pdpSubgroup) {
106         this.name = name;
107         this.loop = loop;
108         this.setPolicyModel(policyModel);
109         this.setConfigurationsJson(configurationsJson);
110         this.setPdpGroup(pdpGroup);
111         this.setPdpSubgroup(pdpSubgroup);
112         this.setLoopElementModel(loopElementModel);
113         if (policyModel != null && policyModel.getPolicyModelType().contains("legacy")) {
114             LegacyOperationalPolicy.preloadConfiguration(configurationsJson, loop);
115         }
116         try {
117             this.setJsonRepresentation(
118                 OperationalPolicyRepresentationBuilder.generateOperationalPolicySchema(loop.getModelService()));
119         } catch (JsonSyntaxException | IOException | NullPointerException e) {
120             logger.error("Unable to generate the operational policy Schema ... ", e);
121             this.setJsonRepresentation(new JsonObject());
122         }
123     }
124
125     public void setLoop(Loop loopName) {
126         this.loop = loopName;
127     }
128
129     public Loop getLoop() {
130         return loop;
131     }
132
133     @Override
134     public String getName() {
135         return name;
136     }
137
138     /**
139      * name setter.
140      *
141      * @param name the name to set
142      */
143     @Override
144     public void setName(String name) {
145         this.name = name;
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     @Override
167     public int hashCode() {
168         final int prime = 31;
169         int result = 1;
170         result = prime * result + ((name == null) ? 0 : name.hashCode());
171         return result;
172     }
173
174     @Override
175     public boolean equals(Object obj) {
176         if (this == obj) {
177             return true;
178         }
179         if (obj == null) {
180             return false;
181         }
182         if (getClass() != obj.getClass()) {
183             return false;
184         }
185         OperationalPolicy other = (OperationalPolicy) obj;
186         if (name == null) {
187             if (other.name != null) {
188                 return false;
189             }
190         } else if (!name.equals(other.name)) {
191             return false;
192         }
193         return true;
194     }
195
196     /**
197      * Create policy Yaml from json defined here.
198      *
199      * @return A string containing Yaml
200      */
201     public String createPolicyPayloadYaml() {
202         JsonObject policyPayloadResult = new JsonObject();
203
204         policyPayloadResult.addProperty("tosca_definitions_version", "tosca_simple_yaml_1_0_0");
205
206         JsonObject topologyTemplateNode = new JsonObject();
207         policyPayloadResult.add("topology_template", topologyTemplateNode);
208
209         JsonArray policiesArray = new JsonArray();
210         topologyTemplateNode.add("policies", policiesArray);
211
212         JsonObject operationalPolicy = new JsonObject();
213         policiesArray.add(operationalPolicy);
214
215         JsonObject operationalPolicyDetails = new JsonObject();
216         operationalPolicy.add(this.name, operationalPolicyDetails);
217         operationalPolicyDetails.addProperty("type", "onap.policies.controlloop.Operational");
218         operationalPolicyDetails.addProperty("version", "1.0.0");
219
220         JsonObject metadata = new JsonObject();
221         operationalPolicyDetails.add("metadata", metadata);
222         metadata.addProperty("policy-id", this.name);
223
224         operationalPolicyDetails.add("properties", LegacyOperationalPolicy
225                 .reworkPayloadAttributes(this.getConfigurationsJson().get("operational_policy").deepCopy()));
226
227         DumperOptions options = new DumperOptions();
228         options.setIndent(2);
229         options.setPrettyFlow(true);
230         options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
231         Gson gson = new GsonBuilder().create();
232
233         return (new Yaml(options)).dump(gson.fromJson(gson.toJson(policyPayloadResult), Map.class));
234     }
235
236     @Override
237     public String createPolicyPayload() throws UnsupportedEncodingException {
238         // Now using the legacy payload fo Dublin
239         JsonObject payload = new JsonObject();
240         payload.addProperty("policy-id", this.getName());
241         payload.addProperty("content",
242                 URLEncoder.encode(
243                         LegacyOperationalPolicy
244                                 .createPolicyPayloadYamlLegacy(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     }
250
251     /**
252      * Return a map containing all Guard policies indexed by Guard policy Name.
253      *
254      * @return The Guards map
255      */
256     public Map<String, String> createGuardPolicyPayloads() {
257         Map<String, String> result = new HashMap<>();
258
259         if (this.getConfigurationsJson() != null) {
260             JsonElement guardsList = this.getConfigurationsJson().get("guard_policies");
261             if (guardsList != null) {
262                 for (JsonElement guardElem : guardsList.getAsJsonArray()) {
263                     result.put(guardElem.getAsJsonObject().get("policy-id").getAsString(),
264                         new GsonBuilder().create().toJson(guardElem));
265                 }
266             }
267         }
268         logger.info("Guard policy payload: " + result);
269         return result;
270     }
271
272     /**
273      * Regenerate the Operational Policy Json Representation.
274      */
275     public void updateJsonRepresentation() {
276         try {
277             this.setJsonRepresentation(
278                     OperationalPolicyRepresentationBuilder.generateOperationalPolicySchema(loop.getModelService()));
279         } catch (JsonSyntaxException | IOException | NullPointerException e) {
280             logger.error("Unable to generate the operational policy Schema ... ", e);
281             this.setJsonRepresentation(new JsonObject());
282         }
283     }
284 }