2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2019 AT&T Intellectual Property. All rights
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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 * ===================================================================
24 package org.onap.clamp.policy.operational;
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 import java.io.IOException;
36 import java.io.Serializable;
37 import java.io.UnsupportedEncodingException;
38 import java.net.URLEncoder;
39 import java.nio.charset.StandardCharsets;
40 import java.util.HashMap;
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.JoinColumns;
48 import javax.persistence.ManyToOne;
49 import javax.persistence.Table;
50 import javax.persistence.Transient;
51 import org.hibernate.annotations.TypeDef;
52 import org.hibernate.annotations.TypeDefs;
53 import org.onap.clamp.clds.tosca.ToscaYamlToJsonConvertor;
54 import org.onap.clamp.clds.util.JsonUtils;
55 import org.onap.clamp.dao.model.jsontype.StringJsonUserType;
56 import org.onap.clamp.loop.Loop;
57 import org.onap.clamp.loop.template.LoopElementModel;
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;
64 @Table(name = "operational_policies")
65 @TypeDefs({@TypeDef(name = "json", typeClass = StringJsonUserType.class)})
66 public class OperationalPolicy extends Policy implements Serializable {
68 * The serial version ID.
70 private static final long serialVersionUID = 6117076450841538255L;
73 private static final EELFLogger logger = EELFManager.getInstance().getLogger(OperationalPolicy.class);
77 @Column(nullable = false, name = "name", unique = true)
80 @ManyToOne(fetch = FetchType.LAZY)
81 @JoinColumn(name = "loop_id", nullable = false)
84 public OperationalPolicy() {
91 * @param name The name of the operational policy
92 * @param loop The loop that uses this operational policy
93 * @param configurationsJson The operational policy property in the format of
95 * @param policyModel The policy model associated if any, can be null
96 * @param loopElementModel The loop element from which this instance is supposed to be created
97 * @param pdpGroup The Pdp Group info
98 * @param pdpSubgroup The Pdp Subgroup info
100 public OperationalPolicy(String name, Loop loop, JsonObject configurationsJson, PolicyModel policyModel,
101 LoopElementModel loopElementModel, String pdpGroup, String pdpSubgroup) {
104 this.setPolicyModel(policyModel);
105 this.setConfigurationsJson(configurationsJson);
106 this.setPdpGroup(pdpGroup);
107 this.setPdpSubgroup(pdpSubgroup);
108 this.setLoopElementModel(loopElementModel);
109 this.setJsonRepresentation(this.generateJsonRepresentation(policyModel));
113 private JsonObject generateJsonRepresentation(PolicyModel policyModel) {
114 JsonObject jsonReturned = new JsonObject();
115 if (policyModel == null) {
116 return new JsonObject();
120 // Op policy Legacy case
121 LegacyOperationalPolicy.preloadConfiguration(jsonReturned, loop);
122 this.setJsonRepresentation(
123 OperationalPolicyRepresentationBuilder.generateOperationalPolicySchema(loop.getModelService()));
126 this.setJsonRepresentation(JsonUtils.GSON
127 .fromJson(new ToscaYamlToJsonConvertor().parseToscaYaml(policyModel.getPolicyModelTosca(),
128 policyModel.getPolicyModelType()), JsonObject.class));
130 } catch (JsonSyntaxException | IOException | NullPointerException e) {
131 logger.error("Unable to generate the operational policy Schema ... ", e);
132 this.setJsonRepresentation(new JsonObject());
137 public void setLoop(Loop loopName) {
138 this.loop = loopName;
141 public Loop getLoop() {
146 public String getName() {
153 * @param name the name to set
156 public void setName(String name) {
161 public int hashCode() {
162 final int prime = 31;
164 result = prime * result + ((name == null) ? 0 : name.hashCode());
169 public boolean equals(Object obj) {
176 if (getClass() != obj.getClass()) {
179 OperationalPolicy other = (OperationalPolicy) obj;
181 if (other.name != null) {
184 } else if (!name.equals(other.name)) {
190 public Boolean isLegacy() {
191 return (this.getPolicyModel() != null) && this.getPolicyModel().getPolicyModelType().contains("legacy");
195 * Create policy Yaml from json defined here.
197 * @return A string containing Yaml
199 public String createPolicyPayloadYaml() {
200 JsonObject policyPayloadResult = new JsonObject();
202 policyPayloadResult.addProperty("tosca_definitions_version", "tosca_simple_yaml_1_0_0");
204 JsonObject topologyTemplateNode = new JsonObject();
205 policyPayloadResult.add("topology_template", topologyTemplateNode);
207 JsonArray policiesArray = new JsonArray();
208 topologyTemplateNode.add("policies", policiesArray);
210 JsonObject operationalPolicy = new JsonObject();
211 policiesArray.add(operationalPolicy);
213 JsonObject operationalPolicyDetails = new JsonObject();
214 operationalPolicy.add(this.name, operationalPolicyDetails);
215 operationalPolicyDetails.addProperty("type", "onap.policies.controlloop.Operational");
216 operationalPolicyDetails.addProperty("version", "1.0.0");
218 JsonObject metadata = new JsonObject();
219 operationalPolicyDetails.add("metadata", metadata);
220 metadata.addProperty("policy-id", this.name);
222 operationalPolicyDetails.add("properties", LegacyOperationalPolicy
223 .reworkPayloadAttributes(this.getConfigurationsJson().get("operational_policy").deepCopy()));
225 DumperOptions options = new DumperOptions();
226 options.setIndent(2);
227 options.setPrettyFlow(true);
228 options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
229 Gson gson = new GsonBuilder().create();
231 return (new Yaml(options)).dump(gson.fromJson(gson.toJson(policyPayloadResult), Map.class));
235 public String createPolicyPayload() throws UnsupportedEncodingException {
237 // Now using the legacy payload fo Dublin
238 JsonObject payload = new JsonObject();
239 payload.addProperty("policy-id", this.getName());
240 payload.addProperty("content",
242 LegacyOperationalPolicy
243 .createPolicyPayloadYamlLegacy(
244 this.getConfigurationsJson().get("operational_policy")),
245 StandardCharsets.UTF_8.toString()));
246 String opPayload = new GsonBuilder().setPrettyPrinting().create().toJson(payload);
247 logger.info("Operational policy payload: " + opPayload);
250 return super.createPolicyPayload();
255 * Return a map containing all Guard policies indexed by Guard policy Name.
257 * @return The Guards map
259 public Map<String, String> createGuardPolicyPayloads() {
260 Map<String, String> result = new HashMap<>();
262 if (this.getConfigurationsJson() != null) {
263 JsonElement guardsList = this.getConfigurationsJson().get("guard_policies");
264 if (guardsList != null) {
265 for (JsonElement guardElem : guardsList.getAsJsonArray()) {
266 result.put(guardElem.getAsJsonObject().get("policy-id").getAsString(),
267 new GsonBuilder().create().toJson(guardElem));
271 logger.info("Guard policy payload: " + result);
276 * Regenerate the Operational Policy Json Representation.
278 public void updateJsonRepresentation() {
280 this.setJsonRepresentation(
281 OperationalPolicyRepresentationBuilder.generateOperationalPolicySchema(loop.getModelService()));
282 } catch (JsonSyntaxException | IOException | NullPointerException e) {
283 logger.error("Unable to generate the operational policy Schema ... ", e);
284 this.setJsonRepresentation(new JsonObject());