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