Address sonar issues in models
[policy/models.git] / models-interactions / model-impl / aai / src / main / java / org / onap / policy / aai / AaiCqResponse.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *
4  * ================================================================================
5  * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.aai;
22
23 import com.google.gson.annotations.SerializedName;
24 import java.io.Serializable;
25 import java.io.StringReader;
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.LinkedList;
29 import java.util.List;
30 import java.util.Map;
31 import javax.xml.bind.JAXBContext;
32 import javax.xml.bind.JAXBException;
33 import javax.xml.bind.Unmarshaller;
34 import javax.xml.transform.stream.StreamSource;
35 import org.eclipse.persistence.jaxb.JAXBContextFactory;
36 import org.eclipse.persistence.jaxb.JAXBContextProperties;
37 import org.json.JSONArray;
38 import org.json.JSONObject;
39 import org.onap.aai.domain.yang.CloudRegion;
40 import org.onap.aai.domain.yang.GenericVnf;
41 import org.onap.aai.domain.yang.ModelVer;
42 import org.onap.aai.domain.yang.Relationship;
43 import org.onap.aai.domain.yang.RelationshipData;
44 import org.onap.aai.domain.yang.ServiceInstance;
45 import org.onap.aai.domain.yang.Tenant;
46 import org.onap.aai.domain.yang.VfModule;
47 import org.onap.aai.domain.yang.Vserver;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 public class AaiCqResponse implements Serializable {
52     private static final long serialVersionUID = 1L;
53     public static final String CONTEXT_KEY = AaiConstants.CONTEXT_PREFIX + "AaiCqResponse";
54     public static final String OPERATION = "CustomQuery";
55     private static final String GENERIC_VNF = "generic-vnf";
56     private static final String VF_MODULE = "vf-module";
57     private static final Logger LOGGER = LoggerFactory.getLogger(AaiCqResponse.class);
58     private static JAXBContext jaxbContext;
59     private static Unmarshaller unmarshaller;
60
61     // JABX initial stuff
62     static {
63         Map<String, Object> properties = new HashMap<>();
64         properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
65         properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
66         // Define JAXB context
67         try {
68             // @formatter:off
69             jaxbContext = JAXBContextFactory.createContext(new Class[] {
70                 Vserver.class,
71                 GenericVnf.class,
72                 VfModule.class,
73                 CloudRegion.class,
74                 ServiceInstance.class,
75                 Tenant.class,
76                 ModelVer.class
77             }, properties);
78             // @formatter:on
79             unmarshaller = jaxbContext.createUnmarshaller();
80         } catch (JAXBException e) {
81             LOGGER.error("Could not initialize JAXBContext", e);
82             LOGGER.info("Problem initiatlizing JAXBContext", e);
83         }
84     }
85
86     @SerializedName("results")
87     private List<Serializable> inventoryResponseItems = new LinkedList<>();
88
89     /**
90      * Constructor creates a custom query response from a valid json string.
91      *
92      * @param jsonString A&AI Custom Query response JSON string
93      */
94     public AaiCqResponse(String jsonString) {
95
96         // Read JSON String and add all AaiObjects
97         JSONObject responseObj = new JSONObject(jsonString);
98         JSONArray resultsArray = new JSONArray();
99         if (responseObj.has("results")) {
100             resultsArray = (JSONArray) responseObj.get("results");
101         }
102         for (int i = 0; i < resultsArray.length(); i++) {
103             final JSONObject resultObject = resultsArray.getJSONObject(i);
104
105             extractVserver(resultObject);
106             extractGenericVnf(resultObject);
107             extractServiceInstance(resultObject);
108             extractVfModule(resultObject);
109             extractCloudRegion(resultObject);
110             extractTenant(resultObject);
111             extractModelVer(resultObject);
112         }
113     }
114
115     private void extractVserver(final JSONObject resultObject) {
116         if (resultObject.has("vserver")) {
117
118             // Create the StreamSource by creating StringReader using the
119             // JSON input
120             StreamSource json = new StreamSource(
121                     new StringReader(resultObject.getJSONObject("vserver").toString()));
122
123             // Getting the vserver pojo again from the json
124             Vserver vserver = this.getAaiObject(json, Vserver.class);
125             this.inventoryResponseItems.add(vserver);
126         }
127     }
128
129     private void extractGenericVnf(final JSONObject resultObject) {
130         if (resultObject.has(GENERIC_VNF)) {
131             // Create the StreamSource by creating StringReader using the
132             // JSON input
133             StreamSource json = new StreamSource(
134                     new StringReader(resultObject.getJSONObject(GENERIC_VNF).toString()));
135
136             // Getting the generic vnf pojo again from the json
137             GenericVnf genericVnf = this.getAaiObject(json, GenericVnf.class);
138
139             this.inventoryResponseItems.add(genericVnf);
140         }
141     }
142
143     private void extractServiceInstance(final JSONObject resultObject) {
144         if (resultObject.has("service-instance")) {
145
146             // Create the StreamSource by creating StringReader using the
147             // JSON input
148             StreamSource json = new StreamSource(
149                     new StringReader(resultObject.getJSONObject("service-instance").toString()));
150
151             // Getting the employee pojo again from the json
152             ServiceInstance serviceInstance = this.getAaiObject(json, ServiceInstance.class);
153
154             this.inventoryResponseItems.add(serviceInstance);
155         }
156     }
157
158     private void extractVfModule(final JSONObject resultObject) {
159         if (resultObject.has(VF_MODULE)) {
160             // Create the StreamSource by creating StringReader using the
161             // JSON input
162             StreamSource json = new StreamSource(
163                     new StringReader(resultObject.getJSONObject(VF_MODULE).toString()));
164
165             // Getting the vf module pojo again from the json
166             VfModule vfModule = this.getAaiObject(json, VfModule.class);
167
168             this.inventoryResponseItems.add(vfModule);
169         }
170     }
171
172     private void extractCloudRegion(final JSONObject resultObject) {
173         if (resultObject.has("cloud-region")) {
174             // Create the StreamSource by creating StringReader using the
175             // JSON input
176             StreamSource json = new StreamSource(
177                     new StringReader(resultObject.getJSONObject("cloud-region").toString()));
178
179             // Getting the cloud region pojo again from the json
180             CloudRegion cloudRegion = this.getAaiObject(json, CloudRegion.class);
181
182             this.inventoryResponseItems.add(cloudRegion);
183         }
184     }
185
186     private void extractTenant(final JSONObject resultObject) {
187         if (resultObject.has("tenant")) {
188             // Create the StreamSource by creating StringReader using the
189             // JSON input
190             StreamSource json = new StreamSource(
191                     new StringReader(resultObject.getJSONObject("tenant").toString()));
192
193             // Getting the tenant pojo again from the json
194             Tenant tenant = this.getAaiObject(json, Tenant.class);
195
196             this.inventoryResponseItems.add(tenant);
197         }
198     }
199
200     private void extractModelVer(final JSONObject resultObject) {
201         if (resultObject.has("model-ver")) {
202             // Create the StreamSource by creating StringReader using the
203             // JSON input
204             StreamSource json = new StreamSource(
205                     new StringReader(resultObject.getJSONObject("model-ver").toString()));
206
207             // Getting the ModelVer pojo again from the json
208             ModelVer modelVer = this.getAaiObject(json, ModelVer.class);
209
210             this.inventoryResponseItems.add(modelVer);
211         }
212     }
213
214     private <T> T getAaiObject(StreamSource json, final Class<T> classOfResponse) {
215         try {
216             return unmarshaller.unmarshal(json, classOfResponse).getValue();
217         } catch (JAXBException e) {
218             LOGGER.error("JAXBCOntext error", e);
219             return null;
220         }
221     }
222
223     public List<Serializable> getInventoryResponseItems() {
224         return inventoryResponseItems;
225     }
226
227     public void setInventoryResponseItems(List<Serializable> inventoryResponseItems) {
228         this.inventoryResponseItems = inventoryResponseItems;
229     }
230
231     /**
232      * Get list of A&AI objects in the custom query.
233      *
234      * @param classOfResponse Class of the type of A&AI objects to be returned
235      * @return List A&AI objects matching the class
236      */
237     @SuppressWarnings("unchecked")
238     public <T> List<T> getItemListByType(Class<T> classOfResponse) {
239         List<T> returnItemList = new ArrayList<>();
240         for (Serializable i : this.inventoryResponseItems) {
241             if (i.getClass() == classOfResponse) {
242                 returnItemList.add((T) i);
243             }
244         }
245         return returnItemList;
246
247     }
248
249     /**
250      * Get Service Instance.
251      *
252      * @return Service Instance
253      */
254     public ServiceInstance getServiceInstance() {
255         ServiceInstance serviceInstance = null;
256         for (Serializable i : this.inventoryResponseItems) {
257             if (i.getClass() == ServiceInstance.class) {
258                 serviceInstance = (ServiceInstance) i;
259             }
260         }
261         return serviceInstance;
262
263     }
264
265     /**
266      * Get Tenant.
267      *
268      * @return Tenant
269      */
270     public Tenant getDefaultTenant() {
271         Tenant tenant = null;
272         for (Serializable i : this.inventoryResponseItems) {
273             if (i.getClass() == Tenant.class) {
274                 tenant = (Tenant) i;
275             }
276         }
277         return tenant;
278
279     }
280
281     /**
282      * Get Cloud Region.
283      *
284      * @return Cloud Region
285      */
286     public CloudRegion getDefaultCloudRegion() {
287         CloudRegion cloudRegion = null;
288         for (Serializable i : this.inventoryResponseItems) {
289             if (i.getClass() == CloudRegion.class) {
290                 cloudRegion = (CloudRegion) i;
291             }
292         }
293         return cloudRegion;
294
295     }
296
297     /**
298      * Get Generic Vnfs in the custom query.
299      *
300      * @return List of generic Vnf
301      */
302     public List<GenericVnf> getGenericVnfs() {
303         List<GenericVnf> genericVnfList = new ArrayList<>();
304         for (Serializable i : this.inventoryResponseItems) {
305             if (i.getClass() == GenericVnf.class) {
306                 genericVnfList.add((GenericVnf) i);
307             }
308         }
309         return genericVnfList;
310
311     }
312
313     /**
314      * Returns a generic Vnf matching vnf name.
315      *
316      * @param vnfName Name of the vnf to match
317      * @return generic Vnf
318      */
319     public GenericVnf getGenericVnfByVnfName(String vnfName) {
320         List<GenericVnf> genericVnfList = new ArrayList<>();
321         GenericVnf genericVnf = null;
322         for (Serializable i : this.inventoryResponseItems) {
323             if (i.getClass() == GenericVnf.class) {
324                 genericVnfList.add((GenericVnf) i);
325             }
326         }
327
328         for (GenericVnf genVnf : genericVnfList) {
329             if (vnfName.equals(genVnf.getVnfName())) {
330                 genericVnf = genVnf;
331             }
332
333         }
334         return genericVnf;
335
336     }
337
338     /**
339      * Returns a generic Vnf matching model invariant ID.
340      *
341      * @param modelInvariantId Name of the vnf to match
342      * @return generic Vnf
343      */
344     public GenericVnf getGenericVnfByModelInvariantId(String modelInvariantId) {
345         List<GenericVnf> genericVnfList = new ArrayList<>();
346         GenericVnf genericVnf = null;
347         for (Serializable i : this.inventoryResponseItems) {
348             if (i.getClass() == GenericVnf.class) {
349                 genericVnfList.add((GenericVnf) i);
350             }
351         }
352
353         for (GenericVnf genVnf : genericVnfList) {
354             if (modelInvariantId.equals(genVnf.getModelInvariantId())) {
355                 genericVnf = genVnf;
356             }
357
358         }
359         return genericVnf;
360
361     }
362
363     /**
364      * Returns a generic Vnf of a given VF Module ID.
365      *
366      * @param vfModuleModelInvariantId of the vf module for which vnf is to be returned
367      * @return generic Vnf
368      */
369     public GenericVnf getGenericVnfByVfModuleModelInvariantId(String vfModuleModelInvariantId) {
370         List<GenericVnf> genericVnfList = this.getGenericVnfs();
371
372         for (GenericVnf genVnf : genericVnfList) {
373             // Iterate through all the vfModules of that generic Vnf
374             for (VfModule vfMod : genVnf.getVfModules().getVfModule()) {
375                 if (vfMod.getModelInvariantId() != null
376                         && vfMod.getModelInvariantId().equals(vfModuleModelInvariantId)) {
377                     return genVnf;
378                 }
379             }
380         }
381         return null;
382     }
383
384     /**
385      * Get the generic vnf associated with the vserver in the custom query.
386      *
387      * @return Generic VNF
388      */
389     public GenericVnf getDefaultGenericVnf() {
390         GenericVnf genericVnf = null;
391
392         // Get the vserver associated with the query
393         Vserver vserver = this.getVserver();
394
395         // Get the relationships of the vserver
396         List<Relationship> relations = vserver.getRelationshipList().getRelationship();
397
398         // Find the relationship of the genericVNF
399         String genericVnfId = "";
400         List<RelationshipData> relationshipData = null;
401
402         // Iterate through the list of relationships and get generic vnf
403         // relationship data
404         for (Relationship r : relations) {
405             // Get the name of generic-vnf related to this server
406             if (GENERIC_VNF.equals(r.getRelatedTo())) {
407                 relationshipData = r.getRelationshipData();
408             }
409         }
410
411         // Iterate through relationship data, and get vnf-id
412         for (RelationshipData rd : relationshipData) {
413             // Get the id of the generic-vnf
414             if ("generic-vnf.vnf-id".equals(rd.getRelationshipKey())) {
415                 genericVnfId = rd.getRelationshipValue();
416             }
417         }
418
419         // Get the list of generic vnfs
420         List<GenericVnf> genericVnfList = this.getGenericVnfs();
421
422         for (GenericVnf genVnf : genericVnfList) {
423             if (genericVnfId.equals(genVnf.getVnfId())) {
424                 genericVnf = genVnf;
425             }
426         }
427
428         return genericVnf;
429     }
430
431     /**
432      * Get Vf Module associated with the vserver in the custom query.
433      *
434      * @return Vf Module
435      */
436     public VfModule getDefaultVfModule() {
437         GenericVnf genericVnf = null;
438         VfModule vfModule = null;
439
440         // Get the vserver associated with the query
441         Vserver vserver = this.getVserver();
442
443         // Get the relationships of the vserver
444         List<Relationship> relations = vserver.getRelationshipList().getRelationship();
445
446         // Find the relationship of VfModule
447         String vfModuleId = "";
448         List<RelationshipData> relationshipData = null;
449
450         // Iterate through the list of relationships and get vf module
451         // relationship data
452         for (Relationship r : relations) {
453             // Get relationship data of vfmodule related to this server
454             if (VF_MODULE.equals(r.getRelatedTo())) {
455                 relationshipData = r.getRelationshipData();
456             }
457         }
458
459         // Iterate through relationship data, and get vf-module-id
460         for (RelationshipData rd : relationshipData) {
461             // Get the id of the vf-module
462             if ("vf-module.vf-module-id".equals(rd.getRelationshipKey())) {
463                 vfModuleId = rd.getRelationshipValue();
464             }
465         }
466
467         // Get the generic VNF associated with this vserver query
468         genericVnf = this.getDefaultGenericVnf();
469
470         // Get the list of VFmodules associated with this generic Vnf
471         List<VfModule> vfModuleList = genericVnf.getVfModules().getVfModule();
472
473         for (VfModule vfMod : vfModuleList) {
474             if (vfModuleId.equals(vfMod.getVfModuleId())) {
475                 vfModule = vfMod;
476             }
477         }
478
479         return vfModule;
480     }
481
482     /**
483      * Get vf modules in the custom query.
484      *
485      * @return List of VfModule
486      */
487     public List<VfModule> getAllVfModules() {
488         List<VfModule> vfModuleList = new ArrayList<>();
489
490         for (GenericVnf genVnf : this.getGenericVnfs()) {
491             vfModuleList.addAll(genVnf.getVfModules().getVfModule());
492         }
493         return vfModuleList;
494
495     }
496
497     /**
498      * Get Vf Module matching a specific VF module name.
499      *
500      * @return VfModule
501      */
502     public VfModule getVfModuleByVfModuleName(String vfModuleName) {
503         VfModule vfModule = null;
504
505         for (VfModule vfMod : this.getAllVfModules()) {
506             if (vfModuleName.equals(vfMod.getVfModuleName())) {
507                 vfModule = vfMod;
508             }
509
510         }
511         return vfModule;
512     }
513
514     /**
515      * Get Vf Module matching a specific VF model invariant ID.
516      *
517      * @return VfModule
518      */
519     public VfModule getVfModuleByVfModelInvariantId(String vfModelInvariantId) {
520         VfModule vfModule = null;
521
522         for (VfModule vfMod : this.getAllVfModules()) {
523             if (vfMod.getModelInvariantId() != null && vfModelInvariantId.equals(vfMod.getModelInvariantId())) {
524                 vfModule = vfMod;
525             }
526
527         }
528         return vfModule;
529     }
530
531     /**
532      * Get verver in the custom query.
533      *
534      * @return Vserver
535      */
536     public Vserver getVserver() {
537         Vserver vserver = null;
538         int index = 0;
539         while (this.inventoryResponseItems.get(index).getClass() != Vserver.class) {
540             index = index + 1;
541         }
542         vserver = (Vserver) this.inventoryResponseItems.get(index);
543         return vserver;
544
545     }
546
547     /**
548      * Get Model Versions in the custom query.
549      *
550      * @return List of model Versions
551      */
552     public List<ModelVer> getAllModelVer() {
553         List<ModelVer> modelVerList = new ArrayList<>();
554         for (Serializable i : this.inventoryResponseItems) {
555             if (i.getClass() == ModelVer.class) {
556                 modelVerList.add((ModelVer) i);
557             }
558         }
559         return modelVerList;
560     }
561
562     /**
563      * Get ModelVer matching a specific version id.
564      *
565      * @return VfModule
566      */
567     public ModelVer getModelVerByVersionId(String versionId) {
568         ModelVer modelVer = null;
569
570         for (ModelVer modVersion : this.getAllModelVer()) {
571             if (versionId.equals(modVersion.getModelVersionId())) {
572                 modelVer = modVersion;
573             }
574
575         }
576         return modelVer;
577     }
578
579     /**
580      * Get the count of vfModules matching customizationId, InvariantId and VersionId.
581      *
582      * @param custId ModelCustomizationId
583      * @param invId ModelInvariantId
584      * @param verId ModelVersionId
585      * @return Returns the count of vf modules
586      */
587     public int getVfModuleCount(String custId, String invId, String verId) {
588         List<VfModule> vfModuleList = this.getAllVfModules();
589         int count = 0;
590         for (VfModule vfModule : vfModuleList) {
591             if (vfModule.getModelCustomizationId() == null || vfModule.getModelInvariantId() == null
592                     || vfModule.getModelVersionId() == null) {
593                 continue;
594             }
595
596             if (vfModule.getModelCustomizationId().equals(custId) && vfModule.getModelInvariantId().equals(invId)
597                     && vfModule.getModelVersionId().equals(verId)) {
598                 count = count + 1;
599             }
600         }
601         return count;
602     }
603
604 }