Updating image version and fixing tests
[integration/csit.git] / plans / so / integration-etsi-testing / so-simulators / aai-simulator / src / main / java / org / onap / so / aaisimulator / service / providers / CustomerCacheServiceProviderImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019 Nordix Foundation.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20 package org.onap.so.aaisimulator.service.providers;
21
22 import static org.onap.so.aaisimulator.utils.CacheName.CUSTOMER_CACHE;
23 import static org.onap.so.aaisimulator.utils.Constants.CUSTOMER_GLOBAL_CUSTOMER_ID;
24 import static org.onap.so.aaisimulator.utils.Constants.GENERIC_VNF;
25 import static org.onap.so.aaisimulator.utils.Constants.GENERIC_VNF_VNF_ID;
26 import static org.onap.so.aaisimulator.utils.Constants.GENERIC_VNF_VNF_NAME;
27 import static org.onap.so.aaisimulator.utils.Constants.SERVICE_INSTANCE_SERVICE_INSTANCE_ID;
28 import static org.onap.so.aaisimulator.utils.Constants.SERVICE_INSTANCE_SERVICE_INSTANCE_NAME;
29 import static org.onap.so.aaisimulator.utils.Constants.SERVICE_SUBSCRIPTION_SERVICE_TYPE;
30 import static org.onap.so.aaisimulator.utils.HttpServiceUtils.getBiDirectionalRelationShipListRelatedLink;
31 import java.util.ArrayList;
32 import java.util.Collections;
33 import java.util.List;
34 import java.util.Optional;
35 import java.util.stream.Collectors;
36 import org.onap.aai.domain.yang.Customer;
37 import org.onap.aai.domain.yang.RelatedToProperty;
38 import org.onap.aai.domain.yang.Relationship;
39 import org.onap.aai.domain.yang.RelationshipData;
40 import org.onap.aai.domain.yang.RelationshipList;
41 import org.onap.aai.domain.yang.ServiceInstance;
42 import org.onap.aai.domain.yang.ServiceInstances;
43 import org.onap.aai.domain.yang.ServiceSubscription;
44 import org.onap.aai.domain.yang.ServiceSubscriptions;
45 import org.onap.so.simulator.cache.provider.AbstractCacheServiceProvider;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48 import org.springframework.beans.factory.annotation.Autowired;
49 import org.springframework.cache.Cache;
50 import org.springframework.cache.CacheManager;
51 import org.springframework.stereotype.Service;
52
53 /**
54  * @author waqas.ikram@ericsson.com
55  *
56  */
57 @Service
58 public class CustomerCacheServiceProviderImpl extends AbstractCacheServiceProvider
59         implements CustomerCacheServiceProvider {
60     private static final Logger LOGGER = LoggerFactory.getLogger(CustomerCacheServiceProviderImpl.class);
61
62     @Autowired
63     public CustomerCacheServiceProviderImpl(final CacheManager cacheManager) {
64         super(cacheManager);
65     }
66
67     @Override
68     public Optional<Customer> getCustomer(final String globalCustomerId) {
69         LOGGER.info("getting customer from cache using key: {}", globalCustomerId);
70         final Cache cache = getCache(CUSTOMER_CACHE.getName());
71         final Customer value = cache.get(globalCustomerId, Customer.class);
72         if (value != null) {
73             return Optional.of(value);
74         }
75         return Optional.empty();
76     }
77
78     @Override
79     public void putCustomer(final String globalCustomerId, final Customer customer) {
80         LOGGER.info("Adding customer: {} with key: {} in cache ...", customer, globalCustomerId);
81         final Cache cache = getCache(CUSTOMER_CACHE.getName());
82
83         cache.put(globalCustomerId, customer);
84     }
85
86     @Override
87     public Optional<ServiceSubscription> getServiceSubscription(final String globalCustomerId,
88             final String serviceType) {
89         LOGGER.info("getting service subscription from cache for globalCustomerId: {} and serviceType: {}",
90                 globalCustomerId, serviceType);
91
92         final Cache cache = getCache(CUSTOMER_CACHE.getName());
93
94         final Customer value = cache.get(globalCustomerId, Customer.class);
95
96         if (value != null) {
97             return Optional.ofNullable(value.getServiceSubscriptions().getServiceSubscription().stream()
98                     .filter(s -> serviceType.equals(s.getServiceType())).findFirst().orElse(null));
99         }
100         return Optional.empty();
101
102     }
103
104     @Override
105     public Optional<ServiceInstances> getServiceInstances(final String globalCustomerId, final String serviceType,
106             final String serviceInstanceName) {
107
108         final Cache cache = getCache(CUSTOMER_CACHE.getName());
109         final Customer value = cache.get(globalCustomerId, Customer.class);
110
111         if (value != null) {
112             final Optional<ServiceSubscription> serviceSubscription = value.getServiceSubscriptions()
113                     .getServiceSubscription().stream().filter(s -> serviceType.equals(s.getServiceType())).findFirst();
114
115             if (serviceSubscription.isPresent()) {
116                 LOGGER.info("Found service subscription ...");
117                 final ServiceInstances serviceInstances = serviceSubscription.get().getServiceInstances();
118                 if (serviceInstances != null) {
119                     final List<ServiceInstance> serviceInstancesList =
120                             serviceInstances.getServiceInstance().stream()
121                                     .filter(serviceInstance -> serviceInstanceName
122                                             .equals(serviceInstance.getServiceInstanceName()))
123                                     .collect(Collectors.toList());
124                     if (serviceInstancesList != null && !serviceInstancesList.isEmpty()) {
125                         LOGGER.info("Found {} service instances ", serviceInstancesList.size());
126                         final ServiceInstances result = new ServiceInstances();
127                         result.getServiceInstance().addAll(serviceInstancesList);
128                         return Optional.of(result);
129
130                     }
131                 }
132             }
133         }
134         return Optional.empty();
135     }
136
137     @Override
138     public Optional<ServiceInstance> getServiceInstance(final String globalCustomerId, final String serviceType,
139             final String serviceInstanceId) {
140         final Cache cache = getCache(CUSTOMER_CACHE.getName());
141         final Customer value = cache.get(globalCustomerId, Customer.class);
142
143         if (value != null) {
144             final Optional<ServiceSubscription> serviceSubscription = value.getServiceSubscriptions()
145                     .getServiceSubscription().stream().filter(s -> serviceType.equals(s.getServiceType())).findFirst();
146
147             if (serviceSubscription.isPresent()) {
148                 LOGGER.info("Found service subscription ...");
149                 final ServiceInstances serviceInstances = serviceSubscription.get().getServiceInstances();
150                 if (serviceInstances != null) {
151                     return Optional.ofNullable(serviceInstances.getServiceInstance().stream()
152                             .filter(serviceInstance -> serviceInstanceId.equals(serviceInstance.getServiceInstanceId()))
153                             .findFirst().orElse(null));
154                 }
155
156             }
157         }
158         LOGGER.error(
159                 "Unable to find ServiceInstance using globalCustomerId: {}, serviceType: {} and serviceInstanceId: {} ...",
160                 globalCustomerId, serviceType, serviceInstanceId);
161         return Optional.empty();
162     }
163
164     @Override
165     public boolean putServiceInstance(final String globalCustomerId, final String serviceType,
166             final String serviceInstanceId, final ServiceInstance serviceInstance) {
167         LOGGER.info("Adding serviceInstance: {} in cache ...", serviceInstance, globalCustomerId);
168
169         final Cache cache = getCache(CUSTOMER_CACHE.getName());
170         final Customer value = cache.get(globalCustomerId, Customer.class);
171
172         if (value != null) {
173             final Optional<ServiceSubscription> serviceSubscription = value.getServiceSubscriptions()
174                     .getServiceSubscription().stream().filter(s -> serviceType.equals(s.getServiceType())).findFirst();
175
176             if (serviceSubscription.isPresent()) {
177                 final ServiceInstances serviceInstances = getServiceInstances(serviceSubscription);
178
179
180                 if (!serviceInstances.getServiceInstance().stream()
181                         .filter(existing -> serviceInstanceId.equals(existing.getServiceInstanceId())).findFirst()
182                         .isPresent()) {
183                     return serviceInstances.getServiceInstance().add(serviceInstance);
184                 }
185                 LOGGER.error("Service {} already exists ....", serviceInstanceId);
186                 return false;
187             }
188             LOGGER.error("Couldn't find  service subscription with serviceType: {} in cache ", serviceType);
189             return false;
190         }
191         LOGGER.error("Couldn't find  Customer with key: {} in cache ", globalCustomerId);
192         return false;
193     }
194
195     @Override
196     public boolean putServiceSubscription(final String globalCustomerId, final String serviceType,
197             final ServiceSubscription serviceSubscription) {
198
199         final Optional<Customer> customerOptional = getCustomer(globalCustomerId);
200
201         if (customerOptional.isPresent()) {
202             final Customer customer = customerOptional.get();
203             if (customer.getServiceSubscriptions() == null) {
204                 final ServiceSubscriptions serviceSubscriptions = new ServiceSubscriptions();
205                 customer.setServiceSubscriptions(serviceSubscriptions);
206                 return serviceSubscriptions.getServiceSubscription().add(serviceSubscription);
207             }
208
209             final Optional<ServiceSubscription> serviceSubscriptionOptional = customer.getServiceSubscriptions()
210                     .getServiceSubscription().stream().filter(s -> serviceType.equals(s.getServiceType())).findFirst();
211
212             if (!serviceSubscriptionOptional.isPresent()) {
213                 return customer.getServiceSubscriptions().getServiceSubscription().add(serviceSubscription);
214             }
215             LOGGER.error("ServiceSubscription already exists {}", serviceSubscriptionOptional.get().getServiceType());
216             return false;
217         }
218         LOGGER.error("Unable to add ServiceSubscription to cache becuase customer does not exits ...");
219         return false;
220     }
221
222     @Override
223     public boolean patchServiceInstance(final String globalCustomerId, final String serviceType,
224             final String serviceInstanceId, final ServiceInstance serviceInstance) {
225         final Optional<ServiceInstance> instance = getServiceInstance(globalCustomerId, serviceType, serviceInstanceId);
226         if (instance.isPresent()) {
227             final ServiceInstance cachedServiceInstance = instance.get();
228             LOGGER.info("Changing OrchestrationStatus from {} to {} ", cachedServiceInstance.getOrchestrationStatus(),
229                     serviceInstance.getOrchestrationStatus());
230             cachedServiceInstance.setOrchestrationStatus(serviceInstance.getOrchestrationStatus());
231             return true;
232         }
233         LOGGER.error("Unable to find ServiceInstance ...");
234         return false;
235     }
236
237     @Override
238     public boolean deleteSericeInstance(final String globalCustomerId, final String serviceType,
239             final String serviceInstanceId, final String resourceVersion) {
240         final Cache cache = getCache(CUSTOMER_CACHE.getName());
241         final Customer value = cache.get(globalCustomerId, Customer.class);
242
243         if (value != null) {
244             final Optional<ServiceSubscription> serviceSubscription = value.getServiceSubscriptions()
245                     .getServiceSubscription().stream().filter(s -> serviceType.equals(s.getServiceType())).findFirst();
246
247             if (serviceSubscription.isPresent()) {
248                 LOGGER.info("Found service subscription ...");
249                 final ServiceInstances serviceInstances = serviceSubscription.get().getServiceInstances();
250                 if (serviceInstances != null) {
251
252                     serviceInstances.getServiceInstance().removeIf(serviceInstance -> {
253                         final String existingServiceInstanceId = serviceInstance.getServiceInstanceId();
254                         final String existingResourceVersion = serviceInstance.getResourceVersion();
255                         if (existingServiceInstanceId != null && existingServiceInstanceId.equals(serviceInstanceId)
256                                 && existingResourceVersion != null && existingResourceVersion.equals(resourceVersion)) {
257                             LOGGER.info("Removing ServiceInstance with serviceInstanceId: {} and resourceVersion: {}",
258                                     existingServiceInstanceId, existingResourceVersion);
259                             return true;
260                         }
261                         return false;
262                     });
263
264
265                     return true;
266                 }
267
268             }
269         }
270         return false;
271     }
272
273     private ServiceInstances getServiceInstances(final Optional<ServiceSubscription> optional) {
274         final ServiceSubscription serviceSubscription = optional.get();
275         final ServiceInstances serviceInstances = serviceSubscription.getServiceInstances();
276         if (serviceInstances == null) {
277             final ServiceInstances instances = new ServiceInstances();
278             serviceSubscription.setServiceInstances(instances);
279             return instances;
280         }
281         return serviceInstances;
282     }
283
284     @Override
285     public List<String> getRelatedToVnfIds(final String globalCustomerId, final String serviceType,
286             final String serviceInstanceId, final String vnfName) {
287         final Optional<ServiceInstance> optional = getServiceInstance(globalCustomerId, serviceType, serviceInstanceId);
288
289         if (optional.isPresent()) {
290             LOGGER.info("Found service instance ...");
291             final ServiceInstance serviceInstance = optional.get();
292             final RelationshipList relationshipList = serviceInstance.getRelationshipList();
293
294             if (relationshipList != null) {
295                 final List<Relationship> relationships = relationshipList.getRelationship().stream().filter(
296                         relationShip -> relationShip.getRelatedToProperty().stream().filter(relatedToProperty -> {
297                             final String propertyKey = relatedToProperty.getPropertyKey();
298                             final String propertyValue = relatedToProperty.getPropertyValue();
299                             return GENERIC_VNF_VNF_NAME.equals(propertyKey) && propertyValue != null
300                                     && propertyValue.equals(vnfName);
301                         }).findFirst().isPresent()).collect(Collectors.toList());
302                 LOGGER.info("Found relationships {} for vnf-name: {}", relationships, vnfName);
303                 return getGenericVnfIdsIfPresent(relationships);
304             }
305             LOGGER.warn("Relationship list is nulll ...");
306         }
307         LOGGER.error("Unable to find generic-vnf relationships with property value: {}... ", vnfName);
308         return Collections.emptyList();
309     }
310
311     @Override
312     public List<String> getRelatedToVnfIds(final String globalCustomerId, final String serviceType,
313             final String serviceInstanceId) {
314         final Optional<ServiceInstance> optional = getServiceInstance(globalCustomerId, serviceType, serviceInstanceId);
315
316         if (optional.isPresent()) {
317             LOGGER.info("Found service instance ...");
318             final ServiceInstance serviceInstance = optional.get();
319             final RelationshipList relationshipList = serviceInstance.getRelationshipList();
320
321             if (relationshipList != null) {
322                 final List<Relationship> relationships = relationshipList.getRelationship();
323                 LOGGER.info("Relationships found {}", relationships);
324                 return getGenericVnfIdsIfPresent(relationships);
325             }
326             LOGGER.warn("Relationship list is nulll ...");
327         }
328         LOGGER.error("Unable to find generic-vnf relationships ... ");
329         return Collections.emptyList();
330     }
331
332     private List<String> getGenericVnfIdsIfPresent(final List<Relationship> relationships) {
333         final List<String> vnfIdsFound = new ArrayList<>();
334         relationships.stream().forEach(relationship -> {
335             relationship.getRelationshipData().stream()
336                     .filter(existing -> GENERIC_VNF_VNF_ID.equals(existing.getRelationshipKey())).findFirst()
337                     .ifPresent(consume -> {
338                         vnfIdsFound.add(consume.getRelationshipValue());
339                     });
340         });
341         return vnfIdsFound;
342     }
343
344     @Override
345     public Optional<Relationship> addRelationShip(final String globalCustomerId, final String serviceType,
346             final String serviceInstanceId, final Relationship relationship, final String requestUri) {
347         final Optional<ServiceInstance> optional = getServiceInstance(globalCustomerId, serviceType, serviceInstanceId);
348         if (optional.isPresent()) {
349             final ServiceInstance serviceInstance = optional.get();
350             RelationshipList relationshipList = serviceInstance.getRelationshipList();
351             if (relationshipList == null) {
352                 relationshipList = new RelationshipList();
353                 serviceInstance.setRelationshipList(relationshipList);
354             }
355             relationshipList.getRelationship().add(relationship);
356
357             LOGGER.info("Successfully added relation to ServiceInstance");
358
359             final Relationship resultantRelationship = new Relationship();
360             resultantRelationship.setRelatedTo(GENERIC_VNF);
361             resultantRelationship.setRelationshipLabel(relationship.getRelationshipLabel());
362             resultantRelationship.setRelatedLink(getBiDirectionalRelationShipListRelatedLink(requestUri));
363
364             final List<RelationshipData> relationshipDataList = resultantRelationship.getRelationshipData();
365             relationshipDataList.add(getRelationshipData(CUSTOMER_GLOBAL_CUSTOMER_ID, globalCustomerId));
366             relationshipDataList.add(getRelationshipData(SERVICE_SUBSCRIPTION_SERVICE_TYPE, serviceType));
367             relationshipDataList.add(getRelationshipData(SERVICE_INSTANCE_SERVICE_INSTANCE_ID, serviceInstanceId));
368
369             final List<RelatedToProperty> relatedToProperty = resultantRelationship.getRelatedToProperty();
370             relatedToProperty.add(getRelatedToProperty(SERVICE_INSTANCE_SERVICE_INSTANCE_NAME,
371                     serviceInstance.getServiceInstanceName()));
372
373             return Optional.of(resultantRelationship);
374
375         }
376         LOGGER.error("Unable to find ServiceInstance ...");
377         return Optional.empty();
378     }
379
380     @Override
381     public void clearAll() {
382         clearCache(CUSTOMER_CACHE.getName());
383     }
384
385     private RelatedToProperty getRelatedToProperty(final String key, final String value) {
386         final RelatedToProperty relatedToProperty = new RelatedToProperty();
387         relatedToProperty.setPropertyKey(key);
388         relatedToProperty.setPropertyValue(value);
389         return relatedToProperty;
390     }
391
392     private RelationshipData getRelationshipData(final String key, final String value) {
393         final RelationshipData relationshipData = new RelationshipData();
394         relationshipData.setRelationshipKey(key);
395         relationshipData.setRelationshipValue(value);
396         return relationshipData;
397     }
398
399
400
401 }