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