Modify the template model
[clamp.git] / src / main / java / org / onap / clamp / policy / microservice / MicroServicePolicy.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2019 AT&T 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.microservice;
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.Serializable;
35 import java.util.HashSet;
36 import java.util.Map;
37 import java.util.Set;
38
39 import javax.persistence.Column;
40 import javax.persistence.Entity;
41 import javax.persistence.FetchType;
42 import javax.persistence.Id;
43 import javax.persistence.ManyToMany;
44 import javax.persistence.Table;
45 import javax.persistence.Transient;
46
47 import org.hibernate.annotations.TypeDef;
48 import org.hibernate.annotations.TypeDefs;
49 import org.json.JSONObject;
50 import org.onap.clamp.clds.tosca.ToscaYamlToJsonConvertor;
51 import org.onap.clamp.clds.util.JsonUtils;
52 import org.onap.clamp.dao.model.jsontype.StringJsonUserType;
53 import org.onap.clamp.loop.Loop;
54 import org.onap.clamp.policy.Policy;
55 import org.yaml.snakeyaml.Yaml;
56
57 @Entity
58 @Table(name = "micro_service_policies")
59 @TypeDefs({ @TypeDef(name = "json", typeClass = StringJsonUserType.class) })
60 public class MicroServicePolicy extends Policy implements Serializable {
61     /**
62      * The serial version ID.
63      */
64     private static final long serialVersionUID = 6271238288583332616L;
65
66     @Transient
67     private static final EELFLogger logger = EELFManager.getInstance().getLogger(MicroServicePolicy.class);
68
69     @Expose
70     @Id
71     @Column(nullable = false, name = "name", unique = true)
72     private String name;
73
74     @Expose
75     @Column(nullable = false, name = "policy_model_type")
76     private String modelType;
77
78     @Expose
79     @Column(name = "context")
80     private String context;
81
82     @Expose
83     @Column(name = "device_type_scope")
84     private String deviceTypeScope;
85
86     @Expose
87     @Column(name = "shared", nullable = false)
88     private Boolean shared;
89
90     @Column(columnDefinition = "MEDIUMTEXT", name = "policy_tosca", nullable = false)
91     private String policyTosca;
92
93     @ManyToMany(mappedBy = "microServicePolicies", fetch = FetchType.EAGER)
94     private Set<Loop> usedByLoops = new HashSet<>();
95
96     @Expose
97     @Column(name = "dcae_deployment_id")
98     private String dcaeDeploymentId;
99
100     @Expose
101     @Column(name = "dcae_deployment_status_url")
102     private String dcaeDeploymentStatusUrl;
103
104     public MicroServicePolicy() {
105         // serialization
106     }
107
108     /**
109      * The constructor that create the json representation from the policyTosca
110      * using the ToscaYamlToJsonConvertor.
111      *
112      * @param name        The name of the MicroService
113      * @param modelType   The model type of the MicroService
114      * @param policyTosca The policy Tosca of the MicroService
115      * @param shared      The flag indicate whether the MicroService is shared
116      * @param usedByLoops The list of loops that uses this MicroService
117      */
118     public MicroServicePolicy(String name, String modelType, String policyTosca, Boolean shared,
119             Set<Loop> usedByLoops) {
120         this.name = name;
121         this.modelType = modelType;
122         this.policyTosca = policyTosca;
123         this.shared = shared;
124         this.setJsonRepresentation(JsonUtils.GSON_JPA_MODEL
125                 .fromJson(new ToscaYamlToJsonConvertor().parseToscaYaml(policyTosca, modelType), JsonObject.class));
126         this.usedByLoops = usedByLoops;
127     }
128
129     private JsonObject createJsonFromPolicyTosca() {
130         Map<String, Object> map = new Yaml().load(this.getPolicyTosca());
131         JSONObject jsonObject = new JSONObject(map);
132         return new Gson().fromJson(jsonObject.toString(), JsonObject.class);
133     }
134
135     /**
136      * The constructor that does not make use of ToscaYamlToJsonConvertor but take
137      * the jsonRepresentation instead.
138      *
139      * @param name               The name of the MicroService
140      * @param modelType          The model type of the MicroService
141      * @param policyTosca        The policy Tosca of the MicroService
142      * @param shared             The flag indicate whether the MicroService is
143      *                           shared
144      * @param jsonRepresentation The UI representation in json format
145      * @param usedByLoops        The list of loops that uses this MicroService
146      */
147     public MicroServicePolicy(String name, String modelType, String policyTosca, Boolean shared,
148             JsonObject jsonRepresentation, Set<Loop> usedByLoops) {
149         this.name = name;
150         this.modelType = modelType;
151         this.policyTosca = policyTosca;
152         this.shared = shared;
153         this.usedByLoops = usedByLoops;
154         this.setJsonRepresentation(jsonRepresentation);
155     }
156
157     @Override
158     public String getName() {
159         return name;
160     }
161
162     /**
163      * name setter.
164      * 
165      * @param name the name to set
166      */
167     @Override
168     public void setName(String name) {
169         this.name = name;
170     }
171
172     public String getModelType() {
173         return modelType;
174     }
175
176     void setModelType(String modelType) {
177         this.modelType = modelType;
178     }
179
180     public Boolean getShared() {
181         return shared;
182     }
183
184     void setShared(Boolean shared) {
185         this.shared = shared;
186     }
187
188     public String getPolicyTosca() {
189         return policyTosca;
190     }
191
192     void setPolicyTosca(String policyTosca) {
193         this.policyTosca = policyTosca;
194     }
195
196     public Set<Loop> getUsedByLoops() {
197         return usedByLoops;
198     }
199
200     void setUsedByLoops(Set<Loop> usedBy) {
201         this.usedByLoops = usedBy;
202     }
203
204     public String getContext() {
205         return context;
206     }
207
208     public void setContext(String context) {
209         this.context = context;
210     }
211
212     public String getDeviceTypeScope() {
213         return deviceTypeScope;
214     }
215
216     public void setDeviceTypeScope(String deviceTypeScope) {
217         this.deviceTypeScope = deviceTypeScope;
218     }
219
220     /**
221      * dcaeDeploymentId getter.
222      * 
223      * @return the dcaeDeploymentId
224      */
225     public String getDcaeDeploymentId() {
226         return dcaeDeploymentId;
227     }
228
229     /**
230      * dcaeDeploymentId setter.
231      * 
232      * @param dcaeDeploymentId the dcaeDeploymentId to set
233      */
234     public void setDcaeDeploymentId(String dcaeDeploymentId) {
235         this.dcaeDeploymentId = dcaeDeploymentId;
236     }
237
238     /**
239      * dcaeDeploymentStatusUrl getter.
240      * 
241      * @return the dcaeDeploymentStatusUrl
242      */
243     public String getDcaeDeploymentStatusUrl() {
244         return dcaeDeploymentStatusUrl;
245     }
246
247     /**
248      * dcaeDeploymentStatusUrl setter.
249      * 
250      * @param dcaeDeploymentStatusUrl the dcaeDeploymentStatusUrl to set
251      */
252     public void setDcaeDeploymentStatusUrl(String dcaeDeploymentStatusUrl) {
253         this.dcaeDeploymentStatusUrl = dcaeDeploymentStatusUrl;
254     }
255
256     @Override
257     public int hashCode() {
258         final int prime = 31;
259         int result = 1;
260         result = prime * result + ((name == null) ? 0 : name.hashCode());
261         return result;
262     }
263
264     @Override
265     public boolean equals(Object obj) {
266         if (this == obj) {
267             return true;
268         }
269         if (obj == null) {
270             return false;
271         }
272         if (getClass() != obj.getClass()) {
273             return false;
274         }
275         MicroServicePolicy other = (MicroServicePolicy) obj;
276         if (name == null) {
277             if (other.name != null) {
278                 return false;
279             }
280         } else if (!name.equals(other.name)) {
281             return false;
282         }
283         return true;
284     }
285
286     private String getMicroServicePropertyNameFromTosca(JsonObject object) {
287         return object.getAsJsonObject("policy_types").getAsJsonObject(this.modelType).getAsJsonObject("properties")
288                 .keySet().toArray(new String[1])[0];
289     }
290
291     @Override
292     public String createPolicyPayload() {
293         JsonObject toscaJson = createJsonFromPolicyTosca();
294
295         JsonObject policyPayloadResult = new JsonObject();
296
297         policyPayloadResult.add("tosca_definitions_version", toscaJson.get("tosca_definitions_version"));
298
299         JsonObject topologyTemplateNode = new JsonObject();
300         policyPayloadResult.add("topology_template", topologyTemplateNode);
301
302         JsonArray policiesArray = new JsonArray();
303         topologyTemplateNode.add("policies", policiesArray);
304
305         JsonObject thisPolicy = new JsonObject();
306         policiesArray.add(thisPolicy);
307
308         JsonObject policyDetails = new JsonObject();
309         thisPolicy.add(this.getName(), policyDetails);
310         policyDetails.addProperty("type", this.getModelType());
311         policyDetails.addProperty("version", "1.0.0");
312
313         JsonObject policyMetadata = new JsonObject();
314         policyDetails.add("metadata", policyMetadata);
315         policyMetadata.addProperty("policy-id", this.getName());
316
317         JsonObject policyProperties = new JsonObject();
318         policyDetails.add("properties", policyProperties);
319         policyProperties.add(this.getMicroServicePropertyNameFromTosca(toscaJson), this.getConfigurationsJson());
320         String policyPayload = new GsonBuilder().setPrettyPrinting().create().toJson(policyPayloadResult);
321         logger.info("Micro service policy payload: " + policyPayload);
322         return policyPayload;
323     }
324
325 }