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