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