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