abb16d73f26df26a2e543251f6a6abeeeb1dc420
[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     /**
101      * This method create the policy payload that must be sent to PEF.
102      *
103      * @return A String containing the payload
104      * @throws UnsupportedEncodingException In case of failure
105      */
106     public String createPolicyPayload() throws UnsupportedEncodingException {
107         JsonObject toscaJson = createJsonFromPolicyTosca();
108
109         JsonObject policyPayloadResult = new JsonObject();
110
111         policyPayloadResult.add("tosca_definitions_version", toscaJson.get("tosca_definitions_version"));
112
113         JsonObject topologyTemplateNode = new JsonObject();
114         policyPayloadResult.add("topology_template", topologyTemplateNode);
115
116         JsonArray policiesArray = new JsonArray();
117         topologyTemplateNode.add("policies", policiesArray);
118
119         JsonObject thisPolicy = new JsonObject();
120         policiesArray.add(thisPolicy);
121
122         JsonObject policyDetails = new JsonObject();
123         thisPolicy.add(this.getName(), policyDetails);
124         policyDetails.addProperty("type", this.getPolicyModel().getPolicyModelType());
125         policyDetails.addProperty("type_version", this.getPolicyModel().getVersion());
126         policyDetails.addProperty("version", this.getPolicyModel().getVersion());
127
128         JsonObject policyMetadata = new JsonObject();
129         policyDetails.add("metadata", policyMetadata);
130         policyMetadata.addProperty("policy-id", this.getName());
131
132         policyDetails.add("properties", this.getConfigurationsJson());
133
134         String policyPayload = new GsonBuilder().setPrettyPrinting().create().toJson(policyPayloadResult);
135         logger.info("Policy payload: " + policyPayload);
136         return policyPayload;
137     }
138
139
140     /**
141      * Name getter.
142      *
143      * @return the name
144      */
145     public abstract String getName();
146
147     /**
148      * Name setter.
149      */
150     public abstract void setName(String name);
151
152     /**
153      * jsonRepresentation getter.
154      *
155      * @return the jsonRepresentation
156      */
157     public JsonObject getJsonRepresentation() {
158         return jsonRepresentation;
159     }
160
161     /**
162      * jsonRepresentation setter.
163      *
164      * @param jsonRepresentation The jsonRepresentation to set
165      */
166     public void setJsonRepresentation(JsonObject jsonRepresentation) {
167         this.jsonRepresentation = jsonRepresentation;
168     }
169
170     /**
171      * Regenerate the Policy Json Representation.
172      *
173      * @param toscaConverter The tosca converter required to regenerate the json schema
174      */
175     public abstract void updateJsonRepresentation(ToscaConverterWithDictionarySupport toscaConverter);
176
177     /**
178      * policyModel getter.
179      *
180      * @return the policyModel
181      */
182     public PolicyModel getPolicyModel() {
183         return policyModel;
184     }
185
186     /**
187      * policyModel setter.
188      *
189      * @param policyModel The new policyModel
190      */
191     public void setPolicyModel(PolicyModel policyModel) {
192         this.policyModel = policyModel;
193     }
194
195     /**
196      * configurationsJson getter.
197      *
198      * @return The configurationsJson
199      */
200     public JsonObject getConfigurationsJson() {
201         return configurationsJson;
202     }
203
204     /**
205      * configurationsJson setter.
206      *
207      * @param configurationsJson the configurationsJson to set
208      */
209     public void setConfigurationsJson(JsonObject configurationsJson) {
210         this.configurationsJson = configurationsJson;
211     }
212
213     /**
214      * loopElementModel getter.
215      *
216      * @return the loopElementModel
217      */
218     public LoopElementModel getLoopElementModel() {
219         return loopElementModel;
220     }
221
222     /**
223      * loopElementModel setter.
224      *
225      * @param loopElementModel the loopElementModel to set
226      */
227     public void setLoopElementModel(LoopElementModel loopElementModel) {
228         this.loopElementModel = loopElementModel;
229     }
230
231     /**
232      * pdpGroup getter.
233      *
234      * @return the pdpGroup
235      */
236     public String getPdpGroup() {
237         return pdpGroup;
238     }
239
240     /**
241      * pdpGroup setter.
242      *
243      * @param pdpGroup the pdpGroup to set
244      */
245     public void setPdpGroup(String pdpGroup) {
246         this.pdpGroup = pdpGroup;
247     }
248
249     /**
250      * pdpSubgroup getter.
251      *
252      * @return the pdpSubgroup
253      */
254     public String getPdpSubgroup() {
255         return pdpSubgroup;
256     }
257
258     /**
259      * pdpSubgroup setter.
260      *
261      * @param pdpSubgroup the pdpSubgroup to set
262      */
263     public void setPdpSubgroup(String pdpSubgroup) {
264         this.pdpSubgroup = pdpSubgroup;
265     }
266
267     /**
268      * Generate the policy name.
269      *
270      * @param policyType        The policy type
271      * @param serviceName       The service name
272      * @param serviceVersion    The service version
273      * @param resourceName      The resource name
274      * @param blueprintFilename The blueprint file name
275      * @return The generated policy name
276      */
277     public static String generatePolicyName(String policyType, String serviceName, String serviceVersion,
278                                             String resourceName, String blueprintFilename) {
279         StringBuilder buffer = new StringBuilder(policyType).append("_").append(serviceName).append("_v")
280                 .append(serviceVersion).append("_").append(resourceName).append("_")
281                 .append(blueprintFilename.replaceAll(".yaml", ""));
282         return buffer.toString().replace('.', '_').replaceAll(" ", "");
283     }
284 }