Merge "Added more unit tests and fix import"
[clamp.git] / src / main / java / org / onap / clamp / loop / Loop.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.loop;
25
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28 import com.google.gson.GsonBuilder;
29 import com.google.gson.JsonArray;
30 import com.google.gson.JsonObject;
31 import com.google.gson.annotations.Expose;
32
33 import java.io.Serializable;
34 import java.util.ArrayList;
35 import java.util.HashSet;
36 import java.util.List;
37 import java.util.Set;
38
39 import javax.persistence.CascadeType;
40 import javax.persistence.Column;
41 import javax.persistence.Entity;
42 import javax.persistence.EnumType;
43 import javax.persistence.Enumerated;
44 import javax.persistence.FetchType;
45 import javax.persistence.Id;
46 import javax.persistence.JoinColumn;
47 import javax.persistence.JoinTable;
48 import javax.persistence.ManyToMany;
49 import javax.persistence.OneToMany;
50 import javax.persistence.OrderBy;
51 import javax.persistence.Table;
52 import javax.persistence.Transient;
53
54 import org.hibernate.annotations.Type;
55 import org.hibernate.annotations.TypeDef;
56 import org.hibernate.annotations.TypeDefs;
57 import org.onap.clamp.dao.model.jsontype.StringJsonUserType;
58 import org.onap.clamp.loop.log.LoopLog;
59 import org.onap.clamp.policy.microservice.MicroServicePolicy;
60 import org.onap.clamp.policy.operational.OperationalPolicy;
61
62 @Entity
63 @Table(name = "loops")
64 @TypeDefs({ @TypeDef(name = "json", typeClass = StringJsonUserType.class) })
65 public class Loop implements Serializable {
66
67     /**
68      * The serial version id.
69      */
70     private static final long serialVersionUID = -286522707701388642L;
71
72     @Transient
73     private static final EELFLogger logger = EELFManager.getInstance().getLogger(Loop.class);
74
75     @Id
76     @Expose
77     @Column(nullable = false, name = "name", unique = true)
78     private String name;
79
80     @Expose
81     @Column(name = "dcae_deployment_id")
82     private String dcaeDeploymentId;
83
84     @Expose
85     @Column(name = "dcae_deployment_status_url")
86     private String dcaeDeploymentStatusUrl;
87
88     @Expose
89     @Column(name = "dcae_blueprint_id")
90     private String dcaeBlueprintId;
91
92     @Column(columnDefinition = "MEDIUMTEXT", name = "svg_representation")
93     private String svgRepresentation;
94
95     @Expose
96     @Type(type = "json")
97     @Column(columnDefinition = "json", name = "global_properties_json")
98     private JsonObject globalPropertiesJson;
99
100     @Expose
101     @Type(type = "json")
102     @Column(columnDefinition = "json", name = "model_properties_json")
103     private JsonObject modelPropertiesJson;
104
105     @Column(columnDefinition = "MEDIUMTEXT", nullable = false, name = "blueprint_yaml")
106     private String blueprint;
107
108     @Expose
109     @Column(nullable = false, name = "last_computed_state")
110     @Enumerated(EnumType.STRING)
111     private LoopState lastComputedState;
112
113     @Expose
114     @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "loop")
115     private Set<OperationalPolicy> operationalPolicies = new HashSet<>();
116
117     @Expose
118     @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
119     @JoinTable(name = "loops_microservicepolicies", joinColumns = @JoinColumn(name = "loop_id"), inverseJoinColumns = @JoinColumn(name = "microservicepolicy_id"))
120     private Set<MicroServicePolicy> microServicePolicies = new HashSet<>();
121
122     @Expose
123     @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "loop")
124     @OrderBy("id DESC")
125     private Set<LoopLog> loopLogs = new HashSet<>();
126
127     public Loop() {
128     }
129
130     /**
131      * Constructor.
132      */
133     public Loop(String name, String blueprint, String svgRepresentation) {
134         this.name = name;
135         this.svgRepresentation = svgRepresentation;
136         this.blueprint = blueprint;
137         this.lastComputedState = LoopState.DESIGN;
138         this.globalPropertiesJson = new JsonObject();
139     }
140
141     public String getName() {
142         return name;
143     }
144
145     void setName(String name) {
146         this.name = name;
147     }
148
149     public String getDcaeDeploymentId() {
150         return dcaeDeploymentId;
151     }
152
153     void setDcaeDeploymentId(String dcaeDeploymentId) {
154         this.dcaeDeploymentId = dcaeDeploymentId;
155     }
156
157     public String getDcaeDeploymentStatusUrl() {
158         return dcaeDeploymentStatusUrl;
159     }
160
161     void setDcaeDeploymentStatusUrl(String dcaeDeploymentStatusUrl) {
162         this.dcaeDeploymentStatusUrl = dcaeDeploymentStatusUrl;
163     }
164
165     public String getSvgRepresentation() {
166         return svgRepresentation;
167     }
168
169     void setSvgRepresentation(String svgRepresentation) {
170         this.svgRepresentation = svgRepresentation;
171     }
172
173     public String getBlueprint() {
174         return blueprint;
175     }
176
177     void setBlueprint(String blueprint) {
178         this.blueprint = blueprint;
179     }
180
181     public LoopState getLastComputedState() {
182         return lastComputedState;
183     }
184
185     void setLastComputedState(LoopState lastComputedState) {
186         this.lastComputedState = lastComputedState;
187     }
188
189     public Set<OperationalPolicy> getOperationalPolicies() {
190         return operationalPolicies;
191     }
192
193     void setOperationalPolicies(Set<OperationalPolicy> operationalPolicies) {
194         this.operationalPolicies = operationalPolicies;
195     }
196
197     public Set<MicroServicePolicy> getMicroServicePolicies() {
198         return microServicePolicies;
199     }
200
201     void setMicroServicePolicies(Set<MicroServicePolicy> microServicePolicies) {
202         this.microServicePolicies = microServicePolicies;
203     }
204
205     public JsonObject getGlobalPropertiesJson() {
206         return globalPropertiesJson;
207     }
208
209     void setGlobalPropertiesJson(JsonObject globalPropertiesJson) {
210         this.globalPropertiesJson = globalPropertiesJson;
211     }
212
213     public Set<LoopLog> getLoopLogs() {
214         return loopLogs;
215     }
216
217     void setLoopLogs(Set<LoopLog> loopLogs) {
218         this.loopLogs = loopLogs;
219     }
220
221     void addOperationalPolicy(OperationalPolicy opPolicy) {
222         operationalPolicies.add(opPolicy);
223         opPolicy.setLoop(this);
224     }
225
226     void addMicroServicePolicy(MicroServicePolicy microServicePolicy) {
227         microServicePolicies.add(microServicePolicy);
228         microServicePolicy.getUsedByLoops().add(this);
229     }
230
231     void addLog(LoopLog log) {
232         loopLogs.add(log);
233         log.setLoop(this);
234     }
235
236     public String getDcaeBlueprintId() {
237         return dcaeBlueprintId;
238     }
239
240     void setDcaeBlueprintId(String dcaeBlueprintId) {
241         this.dcaeBlueprintId = dcaeBlueprintId;
242     }
243
244     public JsonObject getModelPropertiesJson() {
245         return modelPropertiesJson;
246     }
247
248     void setModelPropertiesJson(JsonObject modelPropertiesJson) {
249         this.modelPropertiesJson = modelPropertiesJson;
250     }
251
252     /**
253      * Generate the loop name.
254      *
255      * @param serviceName
256      *        The service name
257      * @param serviceVersion
258      *        The service version
259      * @param resourceName
260      *        The resource name
261      * @param blueprintFileName
262      *        The blueprint file name
263      * @return The generated loop name
264      */
265     static String generateLoopName(String serviceName, String serviceVersion, String resourceName,
266         String blueprintFilename) {
267         StringBuilder buffer = new StringBuilder("LOOP_").append(serviceName).append("_v").append(serviceVersion)
268             .append("_").append(resourceName).append("_").append(blueprintFilename.replaceAll(".yaml", ""));
269         return buffer.toString().replace('.', '_').replaceAll(" ", "");
270     }
271
272     /**
273      * Generates the Json that must be sent to policy to add all policies to Active
274      * PDP group.
275      *
276      * @return The json, payload to send
277      */
278     public String createPoliciesPayloadPdpGroup() {
279         JsonObject jsonObject = new JsonObject();
280         JsonArray jsonArray = new JsonArray();
281         jsonObject.add("policies", jsonArray);
282
283         for (String policyName : this.listPolicyNamesPdpGroup()) {
284             JsonObject policyNode = new JsonObject();
285             jsonArray.add(policyNode);
286             policyNode.addProperty("policy-id", policyName);
287         }
288         String payload = new GsonBuilder().setPrettyPrinting().create().toJson(jsonObject);
289         logger.info("PdpGroup policy payload: " + payload);
290         return payload;
291     }
292
293     /**
294      * Generates the list of policy names that must be send/remove to/from active
295      * PDP group.
296      *
297      * @return A list of policy names
298      */
299     public List<String> listPolicyNamesPdpGroup() {
300         List<String> policyNamesList = new ArrayList<>();
301         for (OperationalPolicy opPolicy : this.getOperationalPolicies()) {
302             policyNamesList.add(opPolicy.getName());
303             for (String guardName : opPolicy.createGuardPolicyPayloads().keySet()) {
304                 policyNamesList.add(guardName);
305             }
306         }
307         for (MicroServicePolicy microServicePolicy : this.getMicroServicePolicies()) {
308             policyNamesList.add(microServicePolicy.getName());
309         }
310         return policyNamesList;
311     }
312
313     @Override
314     public int hashCode() {
315         final int prime = 31;
316         int result = 1;
317         result = prime * result + ((name == null) ? 0 : name.hashCode());
318         return result;
319     }
320
321     @Override
322     public boolean equals(Object obj) {
323         if (this == obj) {
324             return true;
325         }
326         if (obj == null) {
327             return false;
328         }
329         if (getClass() != obj.getClass()) {
330             return false;
331         }
332         Loop other = (Loop) obj;
333         if (name == null) {
334             if (other.name != null) {
335                 return false;
336             }
337         } else if (!name.equals(other.name)) {
338             return false;
339         }
340         return true;
341     }
342
343 }