Update UI to define Pdp Group
[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, null, null);
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      * @param pdpGroup           The Pdp Group info
143      * @param pdpSubgroup        The Pdp Subgrouop info
144      */
145     public MicroServicePolicy(String name, PolicyModel policyModel, Boolean shared,
146                               JsonObject jsonRepresentation, LoopElementModel loopElementModel, String pdpGroup, String pdpSubgroup) {
147         this.name = name;
148         this.policyModel = policyModel;
149         this.shared = shared;
150         this.setJsonRepresentation(jsonRepresentation);
151         this.setLoopElementModel(loopElementModel);
152         this.setPdpGroup(pdpGroup);
153         this.setPdpSubgroup(pdpSubgroup);
154     }
155
156     @Override
157     public String getName() {
158         return name;
159     }
160
161     /**
162      * name setter.
163      *
164      * @param name the name to set
165      */
166     @Override
167     public void setName(String name) {
168         this.name = name;
169     }
170
171     public Boolean getShared() {
172         return shared;
173     }
174
175     void setShared(Boolean shared) {
176         this.shared = shared;
177     }
178
179     public Set<Loop> getUsedByLoops() {
180         return usedByLoops;
181     }
182
183     void setUsedByLoops(Set<Loop> usedBy) {
184         this.usedByLoops = usedBy;
185     }
186
187     public String getContext() {
188         return context;
189     }
190
191     public void setContext(String context) {
192         this.context = context;
193     }
194
195     public String getDeviceTypeScope() {
196         return deviceTypeScope;
197     }
198
199     public void setDeviceTypeScope(String deviceTypeScope) {
200         this.deviceTypeScope = deviceTypeScope;
201     }
202
203     public PolicyModel getPolicyModel() {
204         return policyModel;
205     }
206
207     public void setPolicyModel(PolicyModel policyModel) {
208         this.policyModel = policyModel;
209     }
210
211     /**
212      * dcaeDeploymentId getter.
213      *
214      * @return the dcaeDeploymentId
215      */
216     public String getDcaeDeploymentId() {
217         return dcaeDeploymentId;
218     }
219
220     /**
221      * dcaeDeploymentId setter.
222      *
223      * @param dcaeDeploymentId the dcaeDeploymentId to set
224      */
225     public void setDcaeDeploymentId(String dcaeDeploymentId) {
226         this.dcaeDeploymentId = dcaeDeploymentId;
227     }
228
229     /**
230      * dcaeDeploymentStatusUrl getter.
231      *
232      * @return the dcaeDeploymentStatusUrl
233      */
234     public String getDcaeDeploymentStatusUrl() {
235         return dcaeDeploymentStatusUrl;
236     }
237
238     /**
239      * dcaeDeploymentStatusUrl setter.
240      *
241      * @param dcaeDeploymentStatusUrl the dcaeDeploymentStatusUrl to set
242      */
243     public void setDcaeDeploymentStatusUrl(String dcaeDeploymentStatusUrl) {
244         this.dcaeDeploymentStatusUrl = dcaeDeploymentStatusUrl;
245     }
246
247     /**
248      * dcaeBlueprintId getter.
249      *
250      * @return the dcaeBlueprintId
251      */
252     public String getDcaeBlueprintId() {
253         return dcaeBlueprintId;
254     }
255
256     /**
257      * dcaeBlueprintId setter.
258      *
259      * @param dcaeBlueprintId the dcaeBlueprintId to set
260      */
261     void setDcaeBlueprintId(String dcaeBlueprintId) {
262         this.dcaeBlueprintId = dcaeBlueprintId;
263     }
264
265     @Override
266     public int hashCode() {
267         final int prime = 31;
268         int result = 1;
269         result = prime * result + ((name == null) ? 0 : name.hashCode());
270         return result;
271     }
272
273     @Override
274     public boolean equals(Object obj) {
275         if (this == obj) {
276             return true;
277         }
278         if (obj == null) {
279             return false;
280         }
281         if (getClass() != obj.getClass()) {
282             return false;
283         }
284         MicroServicePolicy other = (MicroServicePolicy) obj;
285         if (name == null) {
286             if (other.name != null) {
287                 return false;
288             }
289         } else if (!name.equals(other.name)) {
290             return false;
291         }        return true;
292     }
293
294     private String getMicroServicePropertyNameFromTosca(JsonObject object) {
295         return object.getAsJsonObject("policy_types").getAsJsonObject(this.getPolicyModel().getPolicyModelType())
296                 .getAsJsonObject(
297                         "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.getPolicyModel().getPolicyModelType());
321         policyDetails.addProperty("version", this.getPolicyModel().getVersion());
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.getConfigurationsJson());
330         String policyPayload = new GsonBuilder().setPrettyPrinting().create().toJson(policyPayloadResult);
331         logger.info("Micro service policy payload: " + policyPayload);
332         return policyPayload;
333     }
334
335 }