Add template and tosca model entities and repositories
[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     public MicroServicePolicy() {
117         // serialization
118     }
119
120     /**
121      * The constructor that create the json representation from the policyTosca
122      * using the ToscaYamlToJsonConvertor.
123      *
124      * @param name        The name of the MicroService
125      * @param modelType   The model type of the MicroService
126      * @param policyTosca The policy Tosca of the MicroService
127      * @param shared      The flag indicate whether the MicroService is shared
128      * @param usedByLoops The list of loops that uses this MicroService
129      */
130     public MicroServicePolicy(String name, String modelType, String policyTosca, Boolean shared,
131             Set<Loop> usedByLoops) {
132         this.name = name;
133         this.modelType = modelType;
134         this.policyTosca = policyTosca;
135         this.shared = shared;
136         this.jsonRepresentation = JsonUtils.GSON_JPA_MODEL
137                 .fromJson(new ToscaYamlToJsonConvertor().parseToscaYaml(policyTosca, modelType), JsonObject.class);
138         this.usedByLoops = usedByLoops;
139     }
140
141     private JsonObject createJsonFromPolicyTosca() {
142         Map<String, Object> map = new Yaml().load(this.getPolicyTosca());
143         JSONObject jsonObject = new JSONObject(map);
144         return new Gson().fromJson(jsonObject.toString(), JsonObject.class);
145     }
146
147     /**
148      * The constructor that does not make use of ToscaYamlToJsonConvertor but take
149      * the jsonRepresentation instead.
150      *
151      * @param name               The name of the MicroService
152      * @param modelType          The model type of the MicroService
153      * @param policyTosca        The policy Tosca of the MicroService
154      * @param shared             The flag indicate whether the MicroService is
155      *                           shared
156      * @param jsonRepresentation The UI representation in json format
157      * @param usedByLoops        The list of loops that uses this MicroService
158      */
159     public MicroServicePolicy(String name, String modelType, String policyTosca, Boolean shared,
160             JsonObject jsonRepresentation, Set<Loop> usedByLoops) {
161         this.name = name;
162         this.modelType = modelType;
163         this.policyTosca = policyTosca;
164         this.shared = shared;
165         this.usedByLoops = usedByLoops;
166         this.jsonRepresentation = jsonRepresentation;
167     }
168
169     @Override
170     public String getName() {
171         return name;
172     }
173
174     public String getModelType() {
175         return modelType;
176     }
177
178     void setModelType(String modelType) {
179         this.modelType = modelType;
180     }
181
182     public JsonObject getProperties() {
183         return properties;
184     }
185
186     public void setProperties(JsonObject properties) {
187         this.properties = properties;
188     }
189
190     public Boolean getShared() {
191         return shared;
192     }
193
194     void setShared(Boolean shared) {
195         this.shared = shared;
196     }
197
198     public String getPolicyTosca() {
199         return policyTosca;
200     }
201
202     void setPolicyTosca(String policyTosca) {
203         this.policyTosca = policyTosca;
204     }
205
206     @Override
207     public JsonObject getJsonRepresentation() {
208         return jsonRepresentation;
209     }
210
211     void setJsonRepresentation(JsonObject jsonRepresentation) {
212         this.jsonRepresentation = jsonRepresentation;
213     }
214
215     public Set<Loop> getUsedByLoops() {
216         return usedByLoops;
217     }
218
219     void setUsedByLoops(Set<Loop> usedBy) {
220         this.usedByLoops = usedBy;
221     }
222
223     public String getContext() {
224         return context;
225     }
226
227     public void setContext(String context) {
228         this.context = context;
229     }
230
231     public String getDeviceTypeScope() {
232         return deviceTypeScope;
233     }
234
235     public void setDeviceTypeScope(String deviceTypeScope) {
236         this.deviceTypeScope = deviceTypeScope;
237     }
238
239     /**
240      * microServiceModel getter.
241      * 
242      * @return the microServiceModel
243      */
244     public MicroServiceModel getMicroServiceModel() {
245         return microServiceModel;
246     }
247
248     /**
249      * microServiceModel setter.
250      * 
251      * @param microServiceModel the microServiceModel to set
252      */
253     public void setMicroServiceModel(MicroServiceModel microServiceModel) {
254         this.microServiceModel = microServiceModel;
255     }
256
257     /**
258      * name setter.
259      * 
260      * @param name the name to set
261      */
262     public void setName(String name) {
263         this.name = name;
264     }
265
266     @Override
267     public int hashCode() {
268         final int prime = 31;
269         int result = 1;
270         result = prime * result + ((name == null) ? 0 : name.hashCode());
271         return result;
272     }
273
274     @Override
275     public boolean equals(Object obj) {
276         if (this == obj) {
277             return true;
278         }
279         if (obj == null) {
280             return false;
281         }
282         if (getClass() != obj.getClass()) {
283             return false;
284         }
285         MicroServicePolicy other = (MicroServicePolicy) obj;
286         if (name == null) {
287             if (other.name != null) {
288                 return false;
289             }
290         } else if (!name.equals(other.name)) {
291             return false;
292         }
293         return true;
294     }
295
296     private String getMicroServicePropertyNameFromTosca(JsonObject object) {
297         return object.getAsJsonObject("policy_types").getAsJsonObject(this.modelType).getAsJsonObject("properties")
298                 .keySet().toArray(new String[1])[0];
299     }
300
301     @Override
302     public String createPolicyPayload() {
303         JsonObject toscaJson = createJsonFromPolicyTosca();
304
305         JsonObject policyPayloadResult = new JsonObject();
306
307         policyPayloadResult.add("tosca_definitions_version", toscaJson.get("tosca_definitions_version"));
308
309         JsonObject topologyTemplateNode = new JsonObject();
310         policyPayloadResult.add("topology_template", topologyTemplateNode);
311
312         JsonArray policiesArray = new JsonArray();
313         topologyTemplateNode.add("policies", policiesArray);
314
315         JsonObject thisPolicy = new JsonObject();
316         policiesArray.add(thisPolicy);
317
318         JsonObject policyDetails = new JsonObject();
319         thisPolicy.add(this.getName(), policyDetails);
320         policyDetails.addProperty("type", this.getModelType());
321         policyDetails.addProperty("version", "1.0.0");
322
323         JsonObject policyMetadata = new JsonObject();
324         policyDetails.add("metadata", policyMetadata);
325         policyMetadata.addProperty("policy-id", this.getName());
326
327         JsonObject policyProperties = new JsonObject();
328         policyDetails.add("properties", policyProperties);
329         policyProperties.add(this.getMicroServicePropertyNameFromTosca(toscaJson), this.getProperties());
330         String policyPayload = new GsonBuilder().setPrettyPrinting().create().toJson(policyPayloadResult);
331         logger.info("Micro service policy payload: " + policyPayload);
332         return policyPayload;
333     }
334
335 }