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