Change json representation in op policy
[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
34 import java.io.UnsupportedEncodingException;
35 import java.util.Map;
36 import javax.persistence.Column;
37 import javax.persistence.FetchType;
38 import javax.persistence.JoinColumn;
39 import javax.persistence.JoinColumns;
40 import javax.persistence.ManyToOne;
41 import javax.persistence.MappedSuperclass;
42 import javax.persistence.Transient;
43 import org.hibernate.annotations.Type;
44 import org.hibernate.annotations.TypeDef;
45 import org.hibernate.annotations.TypeDefs;
46 import org.json.JSONObject;
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      * policyModel getter.
181      *
182      * @return the policyModel
183      */
184     public PolicyModel getPolicyModel() {
185         return policyModel;
186     }
187
188     /**
189      * policyModel setter.
190      *
191      * @param policyModel The new policyModel
192      */
193     public void setPolicyModel(PolicyModel policyModel) {
194         this.policyModel = policyModel;
195     }
196
197     /**
198      * configurationsJson getter.
199      *
200      * @return The configurationsJson
201      */
202     public JsonObject getConfigurationsJson() {
203         return configurationsJson;
204     }
205
206     /**
207      * configurationsJson setter.
208      *
209      * @param configurationsJson the configurationsJson to set
210      */
211     public void setConfigurationsJson(JsonObject configurationsJson) {
212         this.configurationsJson = configurationsJson;
213     }
214
215     /**
216      * loopElementModel getter.
217      *
218      * @return the loopElementModel
219      */
220     public LoopElementModel getLoopElementModel() {
221         return loopElementModel;
222     }
223
224     /**
225      * loopElementModel setter.
226      *
227      * @param loopElementModel the loopElementModel to set
228      */
229     public void setLoopElementModel(LoopElementModel loopElementModel) {
230         this.loopElementModel = loopElementModel;
231     }
232
233     /**
234      * pdpGroup getter.
235      *
236      * @return the pdpGroup
237      */
238     public String getPdpGroup() {
239         return pdpGroup;
240     }
241
242     /**
243      * pdpGroup setter.
244      *
245      * @param pdpGroup the pdpGroup to set
246      */
247     public void setPdpGroup(String pdpGroup) {
248         this.pdpGroup = pdpGroup;
249     }
250
251     /**
252      * pdpSubgroup getter.
253      *
254      * @return the pdpSubgroup
255      */
256     public String getPdpSubgroup() {
257         return pdpSubgroup;
258     }
259
260     /**
261      * pdpSubgroup setter.
262      *
263      * @param pdpSubgroup the pdpSubgroup to set
264      */
265     public void setPdpSubgroup(String pdpSubgroup) {
266         this.pdpSubgroup = pdpSubgroup;
267     }
268
269     /**
270      * Generate the policy name.
271      *
272      * @param policyType        The policy type
273      * @param serviceName       The service name
274      * @param serviceVersion    The service version
275      * @param resourceName      The resource name
276      * @param blueprintFilename The blueprint file name
277      * @return The generated policy name
278      */
279     public static String generatePolicyName(String policyType, String serviceName, String serviceVersion,
280                                             String resourceName, String blueprintFilename) {
281         StringBuilder buffer = new StringBuilder(policyType).append("_").append(serviceName).append("_v")
282                 .append(serviceVersion).append("_").append(resourceName).append("_")
283                 .append(blueprintFilename.replaceAll(".yaml", ""));
284         return buffer.toString().replace('.', '_').replaceAll(" ", "");
285     }
286
287 }