c6ed498471ebadd8b33c963153a299398b93b759
[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.annotations.Expose;
34
35 import java.io.Serializable;
36 import java.io.UnsupportedEncodingException;
37 import java.net.URLEncoder;
38 import java.nio.charset.StandardCharsets;
39 import java.util.HashMap;
40 import java.util.Map;
41
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.ManyToOne;
48 import javax.persistence.Table;
49 import javax.persistence.Transient;
50
51 import org.hibernate.annotations.Type;
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.policy.Policy;
57 import org.yaml.snakeyaml.DumperOptions;
58 import org.yaml.snakeyaml.Yaml;
59
60 @Entity
61 @Table(name = "operational_policies")
62 @TypeDefs({ @TypeDef(name = "json", typeClass = StringJsonUserType.class) })
63 public class OperationalPolicy implements Serializable, Policy {
64     /**
65      * The serial version ID.
66      */
67     private static final long serialVersionUID = 6117076450841538255L;
68
69     @Transient
70     private static final EELFLogger logger = EELFManager.getInstance().getLogger(OperationalPolicy.class);
71
72     @Id
73     @Expose
74     @Column(nullable = false, name = "name", unique = true)
75     private String name;
76
77     @Expose
78     @Type(type = "json")
79     @Column(columnDefinition = "json", name = "configurations_json")
80     private JsonObject configurationsJson;
81
82     @ManyToOne(fetch = FetchType.LAZY)
83     @JoinColumn(name = "loop_id", nullable = false)
84     private Loop loop;
85
86     public OperationalPolicy() {
87         // Serialization
88     }
89
90     /**
91      * The constructor.
92      *
93      * @param name               The name of the operational policy
94      * @param loop               The loop that uses this operational policy
95      * @param configurationsJson The operational policy property in the format of
96      *                           json
97      */
98     public OperationalPolicy(String name, Loop loop, JsonObject configurationsJson) {
99         this.name = name;
100         this.loop = loop;
101         this.configurationsJson = configurationsJson;
102         LegacyOperationalPolicy.preloadConfiguration(this.configurationsJson, loop);
103     }
104
105     @Override
106     public String getName() {
107         return name;
108     }
109
110     public void setLoop(Loop loopName) {
111         this.loop = loopName;
112     }
113
114     public Loop getLoop() {
115         return loop;
116     }
117
118     public JsonObject getConfigurationsJson() {
119         return configurationsJson;
120     }
121
122     public void setConfigurationsJson(JsonObject configurationsJson) {
123         this.configurationsJson = configurationsJson;
124     }
125
126     @Override
127     public JsonObject getJsonRepresentation() {
128         return null;
129     }
130
131     @Override
132     public int hashCode() {
133         final int prime = 31;
134         int result = 1;
135         result = prime * result + ((name == null) ? 0 : name.hashCode());
136         return result;
137     }
138
139     @Override
140     public boolean equals(Object obj) {
141         if (this == obj) {
142             return true;
143         }
144         if (obj == null) {
145             return false;
146         }
147         if (getClass() != obj.getClass()) {
148             return false;
149         }
150         OperationalPolicy other = (OperationalPolicy) obj;
151         if (name == null) {
152             if (other.name != null) {
153                 return false;
154             }
155         } else if (!name.equals(other.name)) {
156             return false;
157         }
158         return true;
159     }
160
161     /**
162      * Create policy Yaml from json defined here.
163      * 
164      * @return A string containing Yaml
165      */
166     public String createPolicyPayloadYaml() {
167         JsonObject policyPayloadResult = new JsonObject();
168
169         policyPayloadResult.addProperty("tosca_definitions_version", "tosca_simple_yaml_1_0_0");
170
171         JsonObject topologyTemplateNode = new JsonObject();
172         policyPayloadResult.add("topology_template", topologyTemplateNode);
173
174         JsonArray policiesArray = new JsonArray();
175         topologyTemplateNode.add("policies", policiesArray);
176
177         JsonObject operationalPolicy = new JsonObject();
178         policiesArray.add(operationalPolicy);
179
180         JsonObject operationalPolicyDetails = new JsonObject();
181         operationalPolicy.add(this.name, operationalPolicyDetails);
182         operationalPolicyDetails.addProperty("type", "onap.policies.controlloop.Operational");
183         operationalPolicyDetails.addProperty("version", "1.0.0");
184
185         JsonObject metadata = new JsonObject();
186         operationalPolicyDetails.add("metadata", metadata);
187         metadata.addProperty("policy-id", this.name);
188
189         operationalPolicyDetails.add("properties", LegacyOperationalPolicy
190                 .reworkPayloadAttributes(this.configurationsJson.get("operational_policy").deepCopy()));
191
192         DumperOptions options = new DumperOptions();
193         options.setIndent(2);
194         options.setPrettyFlow(true);
195         options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
196         Gson gson = new GsonBuilder().create();
197
198         return (new Yaml(options)).dump(gson.fromJson(gson.toJson(policyPayloadResult), Map.class));
199     }
200
201     @Override
202     public String createPolicyPayload() throws UnsupportedEncodingException {
203         // Now using the legacy payload fo Dublin
204         JsonObject payload = new JsonObject();
205         payload.addProperty("policy-id", this.getName());
206         payload.addProperty("content", URLEncoder.encode(LegacyOperationalPolicy.createPolicyPayloadYamlLegacy(
207                 this.configurationsJson.get("operational_policy")), StandardCharsets.UTF_8.toString()));
208         String opPayload = new GsonBuilder().setPrettyPrinting().create().toJson(payload);
209         logger.info("Operational policy payload: " + opPayload);
210         return opPayload;
211     }
212
213     /**
214      * Return a map containing all Guard policies indexed by Guard policy Name.
215      *
216      * @return The Guards map
217      */
218     public Map<String, String> createGuardPolicyPayloads() {
219         Map<String, String> result = new HashMap<>();
220
221         JsonElement guardsList = this.getConfigurationsJson().get("guard_policies");
222         if (guardsList != null) {
223             for (JsonElement guardElem : guardsList.getAsJsonArray()) {
224                 result.put(guardElem.getAsJsonObject().get("policy-id").getAsString(),
225                         new GsonBuilder().create().toJson(guardElem));
226             }
227         }
228         logger.info("Guard policy payload: " + result);
229         return result;
230     }
231
232 }