Merge "add issue"
[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        The name of the MicroService
108      * @param modelType   The model type of the MicroService
109      * @param policyTosca The policy Tosca of the MicroService
110      * @param shared      The flag indicate whether the MicroService is shared
111      * @param usedByLoops The list of loops that uses this MicroService
112      */
113     public MicroServicePolicy(String name, String modelType, String policyTosca, Boolean shared,
114             Set<Loop> usedByLoops) {
115         this.name = name;
116         this.modelType = modelType;
117         this.policyTosca = policyTosca;
118         this.shared = shared;
119         this.jsonRepresentation = JsonUtils.GSON_JPA_MODEL
120                 .fromJson(new ToscaYamlToJsonConvertor().parseToscaYaml(policyTosca, modelType), JsonObject.class);
121         this.usedByLoops = usedByLoops;
122     }
123
124     private JsonObject createJsonFromPolicyTosca() {
125         Map<String, Object> map = new Yaml().load(this.getPolicyTosca());
126         JSONObject jsonObject = new JSONObject(map);
127         return new Gson().fromJson(jsonObject.toString(), JsonObject.class);
128     }
129
130     /**
131      * The constructor that does not make use of ToscaYamlToJsonConvertor but take
132      * the jsonRepresentation instead.
133      *
134      * @param name               The name of the MicroService
135      * @param modelType          The model type of the MicroService
136      * @param policyTosca        The policy Tosca of the MicroService
137      * @param shared             The flag indicate whether the MicroService is
138      *                           shared
139      * @param jsonRepresentation The UI representation in json format
140      * @param usedByLoops        The list of loops that uses this MicroService
141      */
142     public MicroServicePolicy(String name, String modelType, String policyTosca, Boolean shared,
143             JsonObject jsonRepresentation, Set<Loop> usedByLoops) {
144         this.name = name;
145         this.modelType = modelType;
146         this.policyTosca = policyTosca;
147         this.shared = shared;
148         this.usedByLoops = usedByLoops;
149         this.jsonRepresentation = jsonRepresentation;
150     }
151
152     @Override
153     public String getName() {
154         return name;
155     }
156
157     public String getModelType() {
158         return modelType;
159     }
160
161     void setModelType(String modelType) {
162         this.modelType = modelType;
163     }
164
165     public JsonObject getProperties() {
166         return properties;
167     }
168
169     public void setProperties(JsonObject properties) {
170         this.properties = properties;
171     }
172
173     public Boolean getShared() {
174         return shared;
175     }
176
177     void setShared(Boolean shared) {
178         this.shared = shared;
179     }
180
181     public String getPolicyTosca() {
182         return policyTosca;
183     }
184
185     void setPolicyTosca(String policyTosca) {
186         this.policyTosca = policyTosca;
187     }
188
189     @Override
190     public JsonObject getJsonRepresentation() {
191         return jsonRepresentation;
192     }
193
194     void setJsonRepresentation(JsonObject jsonRepresentation) {
195         this.jsonRepresentation = jsonRepresentation;
196     }
197
198     public Set<Loop> getUsedByLoops() {
199         return usedByLoops;
200     }
201
202     void setUsedByLoops(Set<Loop> usedBy) {
203         this.usedByLoops = usedBy;
204     }
205
206     @Override
207     public int hashCode() {
208         final int prime = 31;
209         int result = 1;
210         result = prime * result + ((name == null) ? 0 : name.hashCode());
211         return result;
212     }
213
214     @Override
215     public boolean equals(Object obj) {
216         if (this == obj) {
217             return true;
218         }
219         if (obj == null) {
220             return false;
221         }
222         if (getClass() != obj.getClass()) {
223             return false;
224         }
225         MicroServicePolicy other = (MicroServicePolicy) obj;
226         if (name == null) {
227             if (other.name != null) {
228                 return false;
229             }
230         } else if (!name.equals(other.name)) {
231             return false;
232         }
233         return true;
234     }
235
236     private String getMicroServicePropertyNameFromTosca(JsonObject object) {
237         return object.getAsJsonObject("policy_types").getAsJsonObject(this.modelType).getAsJsonObject("properties")
238                 .keySet().toArray(new String[1])[0];
239     }
240
241     @Override
242     public String createPolicyPayload() {
243         JsonObject toscaJson = createJsonFromPolicyTosca();
244
245         JsonObject policyPayloadResult = new JsonObject();
246
247         policyPayloadResult.add("tosca_definitions_version", toscaJson.get("tosca_definitions_version"));
248
249         JsonObject topologyTemplateNode = new JsonObject();
250         policyPayloadResult.add("topology_template", topologyTemplateNode);
251
252         JsonArray policiesArray = new JsonArray();
253         topologyTemplateNode.add("policies", policiesArray);
254
255         JsonObject thisPolicy = new JsonObject();
256         policiesArray.add(thisPolicy);
257
258         JsonObject policyDetails = new JsonObject();
259         thisPolicy.add(this.getName(), policyDetails);
260         policyDetails.addProperty("type", this.getModelType());
261         policyDetails.addProperty("version", "1.0.0");
262
263         JsonObject policyMetadata = new JsonObject();
264         policyDetails.add("metadata", policyMetadata);
265         policyMetadata.addProperty("policy-id", this.getName());
266
267         JsonObject policyProperties = new JsonObject();
268         policyDetails.add("properties", policyProperties);
269         policyProperties.add(this.getMicroServicePropertyNameFromTosca(toscaJson), this.getProperties());
270         String policyPayload = new GsonBuilder().setPrettyPrinting().create().toJson(policyPayloadResult);
271         logger.info("Micro service policy payload: " + policyPayload);
272         return policyPayload;
273     }
274
275 }