Change Yaml to Json payload
[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.google.gson.Gson;
27 import com.google.gson.GsonBuilder;
28 import com.google.gson.JsonArray;
29 import com.google.gson.JsonElement;
30 import com.google.gson.JsonObject;
31 import com.google.gson.annotations.Expose;
32
33 import java.io.Serializable;
34 import java.io.UnsupportedEncodingException;
35 import java.net.URLEncoder;
36 import java.nio.charset.StandardCharsets;
37 import java.util.HashMap;
38 import java.util.Map;
39 import java.util.Map.Entry;
40
41 import javax.persistence.Column;
42 import javax.persistence.Entity;
43 import javax.persistence.FetchType;
44 import javax.persistence.Id;
45 import javax.persistence.JoinColumn;
46 import javax.persistence.ManyToOne;
47 import javax.persistence.Table;
48
49 import org.hibernate.annotations.Type;
50 import org.hibernate.annotations.TypeDef;
51 import org.hibernate.annotations.TypeDefs;
52 import org.onap.clamp.dao.model.jsontype.StringJsonUserType;
53 import org.onap.clamp.loop.Loop;
54 import org.onap.clamp.policy.Policy;
55 import org.yaml.snakeyaml.Yaml;
56
57 @Entity
58 @Table(name = "operational_policies")
59 @TypeDefs({ @TypeDef(name = "json", typeClass = StringJsonUserType.class) })
60 public class OperationalPolicy implements Serializable, Policy {
61     /**
62      * The serial version ID.
63      */
64     private static final long serialVersionUID = 6117076450841538255L;
65
66     @Id
67     @Expose
68     @Column(nullable = false, name = "name", unique = true)
69     private String name;
70
71     @Expose
72     @Type(type = "json")
73     @Column(columnDefinition = "json", name = "configurations_json")
74     private JsonObject configurationsJson;
75
76     @ManyToOne(fetch = FetchType.LAZY)
77     @JoinColumn(name = "loop_id", nullable = false)
78     private Loop loop;
79
80     public OperationalPolicy() {
81         // Serialization
82     }
83
84     /**
85      * The constructor.
86      *
87      * @param name
88      *        The name of the operational policy
89      * @param loop
90      *        The loop that uses this operational policy
91      * @param configurationsJson
92      *        The operational policy property in the format of json
93      */
94     public OperationalPolicy(String name, Loop loop, JsonObject configurationsJson) {
95         this.name = name;
96         this.loop = loop;
97         this.configurationsJson = configurationsJson;
98     }
99
100     @Override
101     public String getName() {
102         return name;
103     }
104
105     public void setLoop(Loop loopName) {
106         this.loop = loopName;
107     }
108
109     public Loop getLoop() {
110         return loop;
111     }
112
113     @Override
114     public JsonObject getJsonRepresentation() {
115         return configurationsJson;
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 int hashCode() {
128         final int prime = 31;
129         int result = 1;
130         result = prime * result + ((name == null) ? 0 : name.hashCode());
131         return result;
132     }
133
134     @Override
135     public boolean equals(Object obj) {
136         if (this == obj) {
137             return true;
138         }
139         if (obj == null) {
140             return false;
141         }
142         if (getClass() != obj.getClass()) {
143             return false;
144         }
145         OperationalPolicy other = (OperationalPolicy) obj;
146         if (name == null) {
147             if (other.name != null) {
148                 return false;
149             }
150         } else if (!name.equals(other.name)) {
151             return false;
152         }
153         return true;
154     }
155
156     public String createPolicyPayloadYaml() {
157         JsonObject policyPayloadResult = new JsonObject();
158
159         policyPayloadResult.addProperty("tosca_definitions_version", "tosca_simple_yaml_1_0_0");
160
161         JsonObject topologyTemplateNode = new JsonObject();
162         policyPayloadResult.add("topology_template", topologyTemplateNode);
163
164         JsonArray policiesArray = new JsonArray();
165         topologyTemplateNode.add("policies", policiesArray);
166
167         JsonObject operationalPolicy = new JsonObject();
168         policiesArray.add(operationalPolicy);
169
170         JsonObject operationalPolicyDetails = new JsonObject();
171         operationalPolicy.add(this.name, operationalPolicyDetails);
172         operationalPolicyDetails.addProperty("type", "onap.policies.controlloop.Operational");
173         operationalPolicyDetails.addProperty("version", "1.0.0");
174
175         JsonObject metadata = new JsonObject();
176         operationalPolicyDetails.add("metadata", metadata);
177         metadata.addProperty("policy-id", this.name);
178
179         operationalPolicyDetails.add("properties", this.configurationsJson.get("operational_policy"));
180
181         Gson gson = new GsonBuilder().create();
182         Map<?, ?> jsonMap = gson.fromJson(gson.toJson(policyPayloadResult), Map.class);
183         return (new Yaml()).dump(jsonMap);
184     }
185
186     @Override
187     public String createPolicyPayload() throws UnsupportedEncodingException {
188
189         // Now the Yaml payload must be injected in a json ...
190         JsonObject payload = new JsonObject();
191         payload.addProperty("policy-id", this.getName());
192         payload.addProperty("content", URLEncoder.encode(createPolicyPayloadYaml(), StandardCharsets.UTF_8.toString()));
193         return new GsonBuilder().setPrettyPrinting().create().toJson(payload);
194     }
195
196     /**
197      * Return a map containing all Guard policies indexed by Guard policy Name.
198      *
199      * @return The Guards map
200      */
201     public Map<String, String> createGuardPolicyPayloads() {
202         Map<String, String> result = new HashMap<>();
203
204         JsonElement guardsList = this.getConfigurationsJson().get("guard_policies");
205         if (guardsList != null) {
206             for (Entry<String, JsonElement> guardElem : guardsList.getAsJsonObject().entrySet()) {
207                 JsonObject guard = new JsonObject();
208                 guard.addProperty("policy-id", guardElem.getKey());
209                 guard.add("contents", guardElem.getValue());
210                 result.put(guardElem.getKey(), new GsonBuilder().create().toJson(guard));
211             }
212         }
213         return result;
214     }
215
216 }