Rework the policy refresh
[clamp.git] / src / main / java / org / onap / clamp / policy / Policy.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2019 Nokia 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;
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.JsonObject;
32 import com.google.gson.annotations.Expose;
33 import java.io.UnsupportedEncodingException;
34 import java.util.Map;
35 import javax.persistence.Column;
36 import javax.persistence.FetchType;
37 import javax.persistence.JoinColumn;
38 import javax.persistence.JoinColumns;
39 import javax.persistence.ManyToOne;
40 import javax.persistence.MappedSuperclass;
41 import javax.persistence.Transient;
42 import org.hibernate.annotations.Type;
43 import org.hibernate.annotations.TypeDef;
44 import org.hibernate.annotations.TypeDefs;
45 import org.json.JSONObject;
46 import org.onap.clamp.clds.tosca.update.ToscaConverterWithDictionarySupport;
47 import org.onap.clamp.dao.model.jsontype.StringJsonUserType;
48 import org.onap.clamp.loop.common.AuditEntity;
49 import org.onap.clamp.loop.template.LoopElementModel;
50 import org.onap.clamp.loop.template.PolicyModel;
51 import org.yaml.snakeyaml.Yaml;
52
53 @MappedSuperclass
54 @TypeDefs({@TypeDef(name = "json", typeClass = StringJsonUserType.class)})
55 public abstract class Policy extends AuditEntity {
56
57     @Transient
58     private static final EELFLogger logger = EELFManager.getInstance().getLogger(Policy.class);
59
60     @Expose
61     @Type(type = "json")
62     @Column(columnDefinition = "json", name = "json_representation", nullable = false)
63     private JsonObject jsonRepresentation;
64
65     @Expose
66     @Type(type = "json")
67     @Column(columnDefinition = "json", name = "configurations_json")
68     private JsonObject configurationsJson;
69
70     /**
71      * This attribute can be null when the user add a policy on the loop instance, not the template.
72      * When null, It therefore indicates that this policy is not by default in the loop template.
73      */
74     @Expose
75     @ManyToOne(fetch = FetchType.EAGER)
76     @JoinColumn(name = "loop_element_model_id")
77     private LoopElementModel loopElementModel;
78
79     @Expose
80     @Column(name = "pdp_group")
81     private String pdpGroup;
82
83     @Expose
84     @Column(name = "pdp_sub_group")
85     private String pdpSubgroup;
86
87     @Expose
88     @ManyToOne(fetch = FetchType.EAGER)
89     @JoinColumns({@JoinColumn(name = "policy_model_type", referencedColumnName = "policy_model_type"),
90             @JoinColumn(name = "policy_model_version", referencedColumnName = "version")})
91     private PolicyModel policyModel;
92
93     private JsonObject createJsonFromPolicyTosca() {
94         Map<String, Object> map =
95                 new Yaml().load(this.getPolicyModel() != null ? this.getPolicyModel().getPolicyModelTosca() : "");
96         JSONObject jsonObject = new JSONObject(map);
97         return new Gson().fromJson(jsonObject.toString(), JsonObject.class);
98     }
99
100     private String getModelPropertyNameFromTosca(JsonObject object, String policyModelType) {
101         return object.getAsJsonObject("policy_types").getAsJsonObject(policyModelType)
102                 .getAsJsonObject(
103                         "properties")
104                 .keySet().toArray(new String[1])[0];
105     }
106
107     /**
108      * This method create the policy payload that must be sent to PEF.
109      *
110      * @return A String containing the payload
111      * @throws UnsupportedEncodingException In case of failure
112      */
113     public String createPolicyPayload() throws UnsupportedEncodingException {
114         JsonObject toscaJson = createJsonFromPolicyTosca();
115
116         JsonObject policyPayloadResult = new JsonObject();
117
118         policyPayloadResult.add("tosca_definitions_version", toscaJson.get("tosca_definitions_version"));
119
120         JsonObject topologyTemplateNode = new JsonObject();
121         policyPayloadResult.add("topology_template", topologyTemplateNode);
122
123         JsonArray policiesArray = new JsonArray();
124         topologyTemplateNode.add("policies", policiesArray);
125
126         JsonObject thisPolicy = new JsonObject();
127         policiesArray.add(thisPolicy);
128
129         JsonObject policyDetails = new JsonObject();
130         thisPolicy.add(this.getName(), policyDetails);
131         policyDetails.addProperty("type", this.getPolicyModel().getPolicyModelType());
132         policyDetails.addProperty("version", this.getPolicyModel().getVersion());
133
134         JsonObject policyMetadata = new JsonObject();
135         policyDetails.add("metadata", policyMetadata);
136         policyMetadata.addProperty("policy-id", this.getName());
137
138         JsonObject policyProperties = new JsonObject();
139         policyDetails.add("properties", policyProperties);
140         policyProperties
141                 .add(this.getModelPropertyNameFromTosca(toscaJson, this.getPolicyModel().getPolicyModelType()),
142                         this.getConfigurationsJson());
143         String policyPayload = new GsonBuilder().setPrettyPrinting().create().toJson(policyPayloadResult);
144         logger.info("Policy payload: " + policyPayload);
145         return policyPayload;
146     }
147
148
149     /**
150      * Name getter.
151      *
152      * @return the name
153      */
154     public abstract String getName();
155
156     /**
157      * Name setter.
158      */
159     public abstract void setName(String name);
160
161     /**
162      * jsonRepresentation getter.
163      *
164      * @return the jsonRepresentation
165      */
166     public JsonObject getJsonRepresentation() {
167         return jsonRepresentation;
168     }
169
170     /**
171      * jsonRepresentation setter.
172      *
173      * @param jsonRepresentation The jsonRepresentation to set
174      */
175     public void setJsonRepresentation(JsonObject jsonRepresentation) {
176         this.jsonRepresentation = jsonRepresentation;
177     }
178
179     /**
180      * Regenerate the Policy Json Representation.
181      *
182      * @param toscaConverter The tosca converter required to regenerate the json schema
183      */
184     public abstract void updateJsonRepresentation(ToscaConverterWithDictionarySupport toscaConverter);
185
186     /**
187      * policyModel getter.
188      *
189      * @return the policyModel
190      */
191     public PolicyModel getPolicyModel() {
192         return policyModel;
193     }
194
195     /**
196      * policyModel setter.
197      *
198      * @param policyModel The new policyModel
199      */
200     public void setPolicyModel(PolicyModel policyModel) {
201         this.policyModel = policyModel;
202     }
203
204     /**
205      * configurationsJson getter.
206      *
207      * @return The configurationsJson
208      */
209     public JsonObject getConfigurationsJson() {
210         return configurationsJson;
211     }
212
213     /**
214      * configurationsJson setter.
215      *
216      * @param configurationsJson the configurationsJson to set
217      */
218     public void setConfigurationsJson(JsonObject configurationsJson) {
219         this.configurationsJson = configurationsJson;
220     }
221
222     /**
223      * loopElementModel getter.
224      *
225      * @return the loopElementModel
226      */
227     public LoopElementModel getLoopElementModel() {
228         return loopElementModel;
229     }
230
231     /**
232      * loopElementModel setter.
233      *
234      * @param loopElementModel the loopElementModel to set
235      */
236     public void setLoopElementModel(LoopElementModel loopElementModel) {
237         this.loopElementModel = loopElementModel;
238     }
239
240     /**
241      * pdpGroup getter.
242      *
243      * @return the pdpGroup
244      */
245     public String getPdpGroup() {
246         return pdpGroup;
247     }
248
249     /**
250      * pdpGroup setter.
251      *
252      * @param pdpGroup the pdpGroup to set
253      */
254     public void setPdpGroup(String pdpGroup) {
255         this.pdpGroup = pdpGroup;
256     }
257
258     /**
259      * pdpSubgroup getter.
260      *
261      * @return the pdpSubgroup
262      */
263     public String getPdpSubgroup() {
264         return pdpSubgroup;
265     }
266
267     /**
268      * pdpSubgroup setter.
269      *
270      * @param pdpSubgroup the pdpSubgroup to set
271      */
272     public void setPdpSubgroup(String pdpSubgroup) {
273         this.pdpSubgroup = pdpSubgroup;
274     }
275
276     /**
277      * Generate the policy name.
278      *
279      * @param policyType        The policy type
280      * @param serviceName       The service name
281      * @param serviceVersion    The service version
282      * @param resourceName      The resource name
283      * @param blueprintFilename The blueprint file name
284      * @return The generated policy name
285      */
286     public static String generatePolicyName(String policyType, String serviceName, String serviceVersion,
287                                             String resourceName, String blueprintFilename) {
288         StringBuilder buffer = new StringBuilder(policyType).append("_").append(serviceName).append("_v")
289                 .append(serviceVersion).append("_").append(resourceName).append("_")
290                 .append(blueprintFilename.replaceAll(".yaml", ""));
291         return buffer.toString().replace('.', '_').replaceAll(" ", "");
292     }
293 }