d8d15a5b29e6234351802c45dfc3454bae79dc99
[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.ManyToMany;
44 import javax.persistence.Table;
45 import javax.persistence.Transient;
46
47 import org.hibernate.annotations.Type;
48 import org.hibernate.annotations.TypeDef;
49 import org.hibernate.annotations.TypeDefs;
50 import org.json.JSONObject;
51 import org.onap.clamp.clds.tosca.ToscaYamlToJsonConvertor;
52 import org.onap.clamp.clds.util.JsonUtils;
53 import org.onap.clamp.dao.model.jsontype.StringJsonUserType;
54 import org.onap.clamp.loop.Loop;
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 implements Serializable, Policy {
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(nullable = false, name = "model_type")
77     private String modelType;
78
79     @Expose
80     @Type(type = "json")
81     @Column(columnDefinition = "json", name = "properties")
82     private JsonObject properties;
83
84     @Expose
85     @Column(name = "shared", nullable = false)
86     private Boolean shared;
87
88     @Column(columnDefinition = "MEDIUMTEXT", name = "policy_tosca", nullable = false)
89     private String policyTosca;
90
91     @Expose
92     @Type(type = "json")
93     @Column(columnDefinition = "json", name = "json_representation", nullable = false)
94     private JsonObject jsonRepresentation;
95
96     @ManyToMany(mappedBy = "microServicePolicies", fetch = FetchType.EAGER)
97     private Set<Loop> usedByLoops = new HashSet<>();
98
99     public MicroServicePolicy() {
100         // serialization
101     }
102
103     /**
104      * The constructor that create the json representation from the policyTosca
105      * using the ToscaYamlToJsonConvertor.
106      *
107      * @param name
108      *        The name of the MicroService
109      * @param modelType
110      *        The model type of the MicroService
111      * @param policyTosca
112      *        The policy Tosca of the MicroService
113      * @param shared
114      *        The flag indicate whether the MicroService is shared
115      * @param usedByLoops
116      *        The list of loops that uses this MicroService
117      */
118     public MicroServicePolicy(String name, String modelType, String policyTosca, Boolean shared,
119         Set<Loop> usedByLoops) {
120         this.name = name;
121         this.modelType = modelType;
122         this.policyTosca = policyTosca;
123         this.shared = shared;
124         this.jsonRepresentation = JsonUtils.GSON_JPA_MODEL
125             .fromJson(new ToscaYamlToJsonConvertor(null).parseToscaYaml(policyTosca), JsonObject.class);
126         this.usedByLoops = usedByLoops;
127     }
128
129     private JsonObject createJsonFromPolicyTosca() {
130         Map<String, Object> map = new Yaml().load(this.getPolicyTosca());
131         JSONObject jsonObject = new JSONObject(map);
132         return new Gson().fromJson(jsonObject.toString(), JsonObject.class);
133     }
134
135     /**
136      * The constructor that does not make use of ToscaYamlToJsonConvertor but take
137      * the jsonRepresentation instead.
138      *
139      * @param name
140      *        The name of the MicroService
141      * @param modelType
142      *        The model type of the MicroService
143      * @param policyTosca
144      *        The policy Tosca of the MicroService
145      * @param shared
146      *        The flag indicate whether the MicroService is shared
147      * @param jsonRepresentation
148      *        The UI representation in json format
149      * @param usedByLoops
150      *        The list of loops that uses this MicroService
151      */
152     public MicroServicePolicy(String name, String modelType, String policyTosca, Boolean shared,
153         JsonObject jsonRepresentation, Set<Loop> usedByLoops) {
154         this.name = name;
155         this.modelType = modelType;
156         this.policyTosca = policyTosca;
157         this.shared = shared;
158         this.usedByLoops = usedByLoops;
159         this.jsonRepresentation = jsonRepresentation;
160     }
161
162     @Override
163     public String getName() {
164         return name;
165     }
166
167     public String getModelType() {
168         return modelType;
169     }
170
171     void setModelType(String modelType) {
172         this.modelType = modelType;
173     }
174
175     public JsonObject getProperties() {
176         return properties;
177     }
178
179     public void setProperties(JsonObject properties) {
180         this.properties = properties;
181     }
182
183     public Boolean getShared() {
184         return shared;
185     }
186
187     void setShared(Boolean shared) {
188         this.shared = shared;
189     }
190
191     public String getPolicyTosca() {
192         return policyTosca;
193     }
194
195     void setPolicyTosca(String policyTosca) {
196         this.policyTosca = policyTosca;
197     }
198
199     @Override
200     public JsonObject getJsonRepresentation() {
201         return jsonRepresentation;
202     }
203
204     void setJsonRepresentation(JsonObject jsonRepresentation) {
205         this.jsonRepresentation = jsonRepresentation;
206     }
207
208     public Set<Loop> getUsedByLoops() {
209         return usedByLoops;
210     }
211
212     void setUsedByLoops(Set<Loop> usedBy) {
213         this.usedByLoops = usedBy;
214     }
215
216     @Override
217     public int hashCode() {
218         final int prime = 31;
219         int result = 1;
220         result = prime * result + ((name == null) ? 0 : name.hashCode());
221         return result;
222     }
223
224     @Override
225     public boolean equals(Object obj) {
226         if (this == obj) {
227             return true;
228         }
229         if (obj == null) {
230             return false;
231         }
232         if (getClass() != obj.getClass()) {
233             return false;
234         }
235         MicroServicePolicy other = (MicroServicePolicy) obj;
236         if (name == null) {
237             if (other.name != null) {
238                 return false;
239             }
240         } else if (!name.equals(other.name)) {
241             return false;
242         }
243         return true;
244     }
245
246     private String getMicroServicePropertyNameFromTosca(JsonObject object) {
247         return object.getAsJsonObject("policy_types").getAsJsonObject(this.modelType).getAsJsonObject("properties")
248             .keySet().toArray(new String[1])[0];
249     }
250
251     @Override
252     public String createPolicyPayload() {
253         JsonObject toscaJson = createJsonFromPolicyTosca();
254
255         JsonObject policyPayloadResult = new JsonObject();
256
257         policyPayloadResult.add("tosca_definitions_version", toscaJson.get("tosca_definitions_version"));
258
259         JsonObject topologyTemplateNode = new JsonObject();
260         policyPayloadResult.add("topology_template", topologyTemplateNode);
261
262         JsonArray policiesArray = new JsonArray();
263         topologyTemplateNode.add("policies", policiesArray);
264
265         JsonObject thisPolicy = new JsonObject();
266         policiesArray.add(thisPolicy);
267
268         JsonObject policyDetails = new JsonObject();
269         thisPolicy.add(this.getName(), policyDetails);
270         policyDetails.addProperty("type", this.getModelType());
271         policyDetails.addProperty("version", "1.0.0");
272
273         JsonObject policyMetadata = new JsonObject();
274         policyDetails.add("metadata", policyMetadata);
275         policyMetadata.addProperty("policy-id", this.getName());
276
277         JsonObject policyProperties = new JsonObject();
278         policyDetails.add("properties", policyProperties);
279         policyProperties.add(this.getMicroServicePropertyNameFromTosca(toscaJson), this.getProperties());
280         String policyPayload = new GsonBuilder().setPrettyPrinting().create().toJson(policyPayloadResult);
281         logger.info("Micro service policy payload: " + policyPayload);
282         return policyPayload;
283     }
284
285 }