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