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