CLAMP-CDS integration to display all CDS actions for blueprint in CL
[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  * Modifications Copyright (C) 2020 Huawei Technologies Co., Ltd.
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  * http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END============================================
21  * ===================================================================
22  *
23  */
24
25 package org.onap.clamp.policy.operational;
26
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 import com.google.gson.Gson;
30 import com.google.gson.GsonBuilder;
31 import com.google.gson.JsonArray;
32 import com.google.gson.JsonElement;
33 import com.google.gson.JsonObject;
34 import com.google.gson.JsonSyntaxException;
35 import com.google.gson.annotations.Expose;
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 import javax.persistence.Column;
44 import javax.persistence.Entity;
45 import javax.persistence.FetchType;
46 import javax.persistence.Id;
47 import javax.persistence.JoinColumn;
48 import javax.persistence.JoinColumns;
49 import javax.persistence.ManyToOne;
50 import javax.persistence.Table;
51 import javax.persistence.Transient;
52 import org.hibernate.annotations.TypeDef;
53 import org.hibernate.annotations.TypeDefs;
54 import org.onap.clamp.dao.model.jsontype.StringJsonUserType;
55 import org.onap.clamp.loop.Loop;
56 import org.onap.clamp.loop.template.LoopElementModel;
57 import org.onap.clamp.loop.template.PolicyModel;
58 import org.onap.clamp.policy.Policy;
59 import org.yaml.snakeyaml.DumperOptions;
60 import org.yaml.snakeyaml.Yaml;
61
62 @Entity
63 @Table(name = "operational_policies")
64 @TypeDefs({@TypeDef(name = "json", typeClass = StringJsonUserType.class)})
65 public class OperationalPolicy extends Policy implements Serializable {
66     /**
67      * The serial version ID.
68      */
69     private static final long serialVersionUID = 6117076450841538255L;
70
71     @Transient
72     private static final EELFLogger logger = EELFManager.getInstance().getLogger(OperationalPolicy.class);
73
74     @Id
75     @Expose
76     @Column(nullable = false, name = "name", unique = true)
77     private String name;
78
79     @ManyToOne(fetch = FetchType.LAZY)
80     @JoinColumn(name = "loop_id", nullable = false)
81     private Loop loop;
82
83     @Expose
84     @ManyToOne(fetch = FetchType.EAGER)
85     @JoinColumns({@JoinColumn(name = "policy_model_type", referencedColumnName = "policy_model_type"),
86             @JoinColumn(name = "policy_model_version", referencedColumnName = "version")})
87     private PolicyModel policyModel;
88
89     public OperationalPolicy() {
90         // Serialization
91     }
92
93     /**
94      * The constructor.
95      *
96      * @param name               The name of the operational policy
97      * @param loop               The loop that uses this operational policy
98      * @param configurationsJson The operational policy property in the format of
99      *                           json
100      * @param policyModel        The policy model associated if any, can be null
101      * @param loopElementModel   The loop element from which this instance is supposed to be created
102      * @param pdpGroup           The Pdp Group info
103      * @param pdpSubgroup        The Pdp Subgroup info
104      */
105     public OperationalPolicy(String name, Loop loop, JsonObject configurationsJson, PolicyModel policyModel,
106                              LoopElementModel loopElementModel, String pdpGroup, String pdpSubgroup) {
107         this.name = name;
108         this.loop = loop;
109         this.setPolicyModel(policyModel);
110         this.setConfigurationsJson(configurationsJson);
111         this.setPdpGroup(pdpGroup);
112         this.setPdpSubgroup(pdpSubgroup);
113         this.setLoopElementModel(loopElementModel);
114         if (policyModel != null && policyModel.getPolicyModelType().contains("legacy")) {
115             LegacyOperationalPolicy.preloadConfiguration(configurationsJson, loop);
116         }
117         try {
118             this.setJsonRepresentation(
119                 OperationalPolicyRepresentationBuilder.generateOperationalPolicySchema(loop.getModelService()));
120         } catch (JsonSyntaxException | IOException | NullPointerException e) {
121             logger.error("Unable to generate the operational policy Schema ... ", e);
122             this.setJsonRepresentation(new JsonObject());
123         }
124     }
125
126     public void setLoop(Loop loopName) {
127         this.loop = loopName;
128     }
129
130     public Loop getLoop() {
131         return loop;
132     }
133
134     @Override
135     public String getName() {
136         return name;
137     }
138
139     /**
140      * name setter.
141      *
142      * @param name the name to set
143      */
144     @Override
145     public void setName(String name) {
146         this.name = name;
147     }
148
149     /**
150      * policyModel getter.
151      *
152      * @return the policyModel
153      */
154     public PolicyModel getPolicyModel() {
155         return policyModel;
156     }
157
158     /**
159      * policyModel setter.
160      *
161      * @param policyModel the policyModel to set
162      */
163     public void setPolicyModel(PolicyModel policyModel) {
164         this.policyModel = policyModel;
165     }
166
167     @Override
168     public int hashCode() {
169         final int prime = 31;
170         int result = 1;
171         result = prime * result + ((name == null) ? 0 : name.hashCode());
172         return result;
173     }
174
175     @Override
176     public boolean equals(Object obj) {
177         if (this == obj) {
178             return true;
179         }
180         if (obj == null) {
181             return false;
182         }
183         if (getClass() != obj.getClass()) {
184             return false;
185         }
186         OperationalPolicy other = (OperationalPolicy) obj;
187         if (name == null) {
188             if (other.name != null) {
189                 return false;
190             }
191         } else if (!name.equals(other.name)) {
192             return false;
193         }
194         return true;
195     }
196
197     /**
198      * Create policy Yaml from json defined here.
199      *
200      * @return A string containing Yaml
201      */
202     public String createPolicyPayloadYaml() {
203         JsonObject policyPayloadResult = new JsonObject();
204
205         policyPayloadResult.addProperty("tosca_definitions_version", "tosca_simple_yaml_1_0_0");
206
207         JsonObject topologyTemplateNode = new JsonObject();
208         policyPayloadResult.add("topology_template", topologyTemplateNode);
209
210         JsonArray policiesArray = new JsonArray();
211         topologyTemplateNode.add("policies", policiesArray);
212
213         JsonObject operationalPolicy = new JsonObject();
214         policiesArray.add(operationalPolicy);
215
216         JsonObject operationalPolicyDetails = new JsonObject();
217         operationalPolicy.add(this.name, operationalPolicyDetails);
218         operationalPolicyDetails.addProperty("type", "onap.policies.controlloop.Operational");
219         operationalPolicyDetails.addProperty("version", "1.0.0");
220
221         JsonObject metadata = new JsonObject();
222         operationalPolicyDetails.add("metadata", metadata);
223         metadata.addProperty("policy-id", this.name);
224
225         operationalPolicyDetails.add("properties", LegacyOperationalPolicy
226                 .reworkActorAttributes(this.getConfigurationsJson().get("operational_policy").deepCopy()));
227
228         DumperOptions options = new DumperOptions();
229         options.setIndent(2);
230         options.setPrettyFlow(true);
231         options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
232         Gson gson = new GsonBuilder().create();
233
234         return (new Yaml(options)).dump(gson.fromJson(gson.toJson(policyPayloadResult), Map.class));
235     }
236
237     @Override
238     public String createPolicyPayload() throws UnsupportedEncodingException {
239         // Now using the legacy payload fo Dublin
240         JsonObject payload = new JsonObject();
241         payload.addProperty("policy-id", this.getName());
242         payload.addProperty("content",
243                 URLEncoder.encode(
244                         LegacyOperationalPolicy
245                                 .createPolicyPayloadYamlLegacy(this.getConfigurationsJson().get("operational_policy")),
246                         StandardCharsets.UTF_8.toString()));
247         String opPayload = new GsonBuilder().setPrettyPrinting().create().toJson(payload);
248         logger.info("Operational policy payload: " + opPayload);
249         return opPayload;
250     }
251
252     /**
253      * Return a map containing all Guard policies indexed by Guard policy Name.
254      *
255      * @return The Guards map
256      */
257     public Map<String, String> createGuardPolicyPayloads() {
258         Map<String, String> result = new HashMap<>();
259
260         if (this.getConfigurationsJson() != null) {
261             JsonElement guardsList = this.getConfigurationsJson().get("guard_policies");
262             if (guardsList != null) {
263                 for (JsonElement guardElem : guardsList.getAsJsonArray()) {
264                     result.put(guardElem.getAsJsonObject().get("policy-id").getAsString(),
265                         new GsonBuilder().create().toJson(guardElem));
266                 }
267             }
268         }
269         logger.info("Guard policy payload: " + result);
270         return result;
271     }
272
273     /**
274      * Regenerate the Operational Policy Json Representation.
275      */
276     public void updateJsonRepresentation() {
277         try {
278             this.setJsonRepresentation(
279                     OperationalPolicyRepresentationBuilder.generateOperationalPolicySchema(loop.getModelService()));
280         } catch (JsonSyntaxException | IOException | NullPointerException e) {
281             logger.error("Unable to generate the operational policy Schema ... ", e);
282             this.setJsonRepresentation(new JsonObject());
283         }
284     }
285 }