diff options
author | 2020-08-24 12:54:04 +0530 | |
---|---|---|
committer | 2020-08-31 07:03:21 +0000 | |
commit | 836bd90e99887e4d92edb0528dc69a693a13512b (patch) | |
tree | 01481822ae671670278527c777101ed7849956b7 /test/mocks/aai-simulator/aai-sim/src/main | |
parent | 13b842ccd307ed4a2860b0044cf00d326f3866b9 (diff) |
AAI-Simulator: Pulling from PNF-SW-UP CSIT to Integration repo
Issue-ID: INT-1704
Signed-off-by: ajay_dp001 <ajay.deep.singh@est.tech>
Change-Id: Ifc6a71f8303d3b27b40650dea5564365b08b1372
Signed-off-by: mrichomme <morgan.richomme@orange.com>
Diffstat (limited to 'test/mocks/aai-simulator/aai-sim/src/main')
55 files changed, 6084 insertions, 0 deletions
diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/AaiSimulatorApplication.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/AaiSimulatorApplication.java new file mode 100755 index 000000000..abe186a6c --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/AaiSimulatorApplication.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +import org.springframework.cache.annotation.EnableCaching; + +/** + * @author waqas.ikram@ericsson.com + * + */ +@EnableCaching +@SpringBootApplication(scanBasePackages = {"org.onap"}) +public class AaiSimulatorApplication extends SpringBootServletInitializer { + + public static void main(final String[] args) { + SpringApplication.run(AaiSimulatorApplication.class, args); + } +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/configration/ApplicationConfigration.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/configration/ApplicationConfigration.java new file mode 100755 index 000000000..6e53c1483 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/configration/ApplicationConfigration.java @@ -0,0 +1,109 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.configration; + +import java.util.ArrayList; +import java.util.List; +import javax.net.ssl.SSLContext; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.ssl.SSLContextBuilder; +import org.onap.aaisimulator.utils.CacheName; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.cache.concurrent.ConcurrentMapCache; +import org.springframework.cache.support.SimpleCacheManager; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.core.io.Resource; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.web.client.RestTemplate; +import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule; + +/** + * @author waqas.ikram@ericsson.com + * + */ +@Configuration +public class ApplicationConfigration { + private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationConfigration.class); + + + @Bean + public Jackson2ObjectMapperBuilderCustomizer jacksonCustomizer() { + return (mapperBuilder) -> mapperBuilder.modulesToInstall(new JaxbAnnotationModule()); + } + + @Bean + public CacheManager cacheManager() { + final SimpleCacheManager manager = new SimpleCacheManager(); + + final List<Cache> caches = new ArrayList<>(); + for (final CacheName cacheName : CacheName.values()) { + caches.add(getCache(cacheName.getName())); + } + manager.setCaches(caches); + return manager; + } + + private Cache getCache(final String name) { + LOGGER.info("Creating cache with name: {}", name); + return new ConcurrentMapCache(name); + } + + @Profile("!test") + @Bean + public RestTemplate restTemplate(@Value("${http.client.ssl.trust-store:#{null}}") final Resource trustStore, + @Value("${http.client.ssl.trust-store-password:#{null}}") final String trustStorePassword) + throws Exception { + LOGGER.info("Setting up RestTemplate .... "); + final RestTemplate restTemplate = new RestTemplate(); + + final HttpComponentsClientHttpRequestFactory factory = + new HttpComponentsClientHttpRequestFactory(httpClient(trustStore, trustStorePassword)); + + restTemplate.setRequestFactory(factory); + return restTemplate; + } + + private CloseableHttpClient httpClient(final Resource trustStore, final String trustStorePassword) + throws Exception { + LOGGER.info("Creating SSLConnectionSocketFactory with custom SSLContext and HostnameVerifier ... "); + return HttpClients.custom().setSSLSocketFactory(getSSLConnectionSocketFactory(trustStore, trustStorePassword)) + .build(); + } + + private SSLConnectionSocketFactory getSSLConnectionSocketFactory(final Resource trustStore, + final String trustStorePassword) throws Exception { + return new SSLConnectionSocketFactory(getSslContext(trustStore, trustStorePassword)); + } + + private SSLContext getSslContext(final Resource trustStore, final String trustStorePassword) + throws Exception, Exception { + return new SSLContextBuilder().loadTrustMaterial(trustStore.getURL(), trustStorePassword.toCharArray()).build(); + } + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/configration/WebSecurityConfigImpl.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/configration/WebSecurityConfigImpl.java new file mode 100755 index 000000000..2a2d04d8c --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/configration/WebSecurityConfigImpl.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.configration; + +import org.onap.aaisimulator.utils.Constants; +import org.onap.aaisimulator.configuration.SimulatorSecurityConfigurer; +import org.onap.aaisimulator.model.UserCredentials; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; + +/** + * @author waqas.ikram@ericsson.com + * + */ +@Configuration +@EnableWebSecurity +public class WebSecurityConfigImpl extends SimulatorSecurityConfigurer { + + @Autowired + public WebSecurityConfigImpl(final UserCredentials userCredentials) { + super(userCredentials.getUsers()); + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + http.csrf().disable().authorizeRequests().antMatchers(Constants.BUSINESS_URL + "/**/**").authenticated().and() + .httpBasic(); + } + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/AaiSimulatorController.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/AaiSimulatorController.java new file mode 100755 index 000000000..f2ce98ecc --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/AaiSimulatorController.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.controller; + +import static org.onap.aaisimulator.utils.Constants.HEALTHY; +import javax.ws.rs.core.MediaType; +import org.onap.aaisimulator.utils.Constants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; + +/** + * @author waqas.ikram@ericsson.com + * + */ +@Controller +@RequestMapping(path = Constants.BASE_URL) +public class AaiSimulatorController { + private static final Logger LOGGER = LoggerFactory.getLogger(AaiSimulatorController.class); + + @ResponseBody + @GetMapping(value = "/healthcheck", produces = MediaType.TEXT_PLAIN) + @ResponseStatus(code = HttpStatus.OK) + public String healthCheck() { + LOGGER.info("Running health check ..."); + return HEALTHY; + } + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/BusinessController.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/BusinessController.java new file mode 100755 index 000000000..8559e8aa7 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/BusinessController.java @@ -0,0 +1,356 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.controller; + +import static org.onap.aaisimulator.utils.Constants.BI_DIRECTIONAL_RELATIONSHIP_LIST_URL; +import static org.onap.aaisimulator.utils.Constants.CUSTOMER_TYPE; +import static org.onap.aaisimulator.utils.Constants.CUSTOMER_URL; +import static org.onap.aaisimulator.utils.Constants.GENERIC_VNF; +import static org.onap.aaisimulator.utils.Constants.GENERIC_VNF_VNF_ID; +import static org.onap.aaisimulator.utils.Constants.SERVICE_RESOURCE_TYPE; +import static org.onap.aaisimulator.utils.Constants.SERVICE_SUBSCRIPTION; +import static org.onap.aaisimulator.utils.Constants.X_HTTP_METHOD_OVERRIDE; +import static org.onap.aaisimulator.utils.RequestErrorResponseUtils.getRequestErrorResponseEntity; +import static org.onap.aaisimulator.utils.RequestErrorResponseUtils.getResourceVersion; +import java.util.Optional; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.MediaType; +import org.onap.aai.domain.yang.Customer; +import org.onap.aai.domain.yang.GenericVnf; +import org.onap.aai.domain.yang.GenericVnfs; +import org.onap.aai.domain.yang.Relationship; +import org.onap.aai.domain.yang.RelationshipData; +import org.onap.aai.domain.yang.ServiceInstance; +import org.onap.aai.domain.yang.ServiceInstances; +import org.onap.aai.domain.yang.ServiceSubscription; +import org.onap.aaisimulator.models.NodeServiceInstance; +import org.onap.aaisimulator.service.providers.CustomerCacheServiceProvider; +import org.onap.aaisimulator.service.providers.GenericVnfCacheServiceProvider; +import org.onap.aaisimulator.service.providers.NodesCacheServiceProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; + +/** + * @author waqas.ikram@ericsson.com + * + */ +@Controller +@RequestMapping(path = CUSTOMER_URL) +public class BusinessController { + + private static final Logger LOGGER = LoggerFactory.getLogger(BusinessController.class); + private final CustomerCacheServiceProvider cacheServiceProvider; + private final NodesCacheServiceProvider nodesCacheServiceProvider; + private final GenericVnfCacheServiceProvider genericVnfCacheServiceProvider; + + @Autowired + public BusinessController(final CustomerCacheServiceProvider cacheServiceProvider, + final NodesCacheServiceProvider nodesCacheServiceProvider, + final GenericVnfCacheServiceProvider genericVnfCacheServiceProvider) { + this.cacheServiceProvider = cacheServiceProvider; + this.nodesCacheServiceProvider = nodesCacheServiceProvider; + this.genericVnfCacheServiceProvider = genericVnfCacheServiceProvider; + } + + @GetMapping(value = "{global-customer-id}", produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> getCustomer(@PathVariable("global-customer-id") final String globalCustomerId, + final HttpServletRequest request) { + LOGGER.info("Will retrieve customer for 'global customer id': {} ...", globalCustomerId); + + final Optional<Customer> optional = cacheServiceProvider.getCustomer(globalCustomerId); + if (optional.isPresent()) { + final Customer customer = optional.get(); + LOGGER.info("found customer {} in cache", customer); + return ResponseEntity.ok(customer); + } + + LOGGER.error("Couldn't find {} in cache", globalCustomerId); + return getRequestErrorResponseEntity(request, CUSTOMER_TYPE); + } + + @PutMapping(value = "/{global-customer-id}", consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}, + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> putCustomer(@RequestBody final Customer customer, + @PathVariable("global-customer-id") final String globalCustomerId, final HttpServletRequest request) { + LOGGER.info("Will put customer for 'global customer id': {} ...", globalCustomerId); + + if (customer.getResourceVersion() == null || customer.getResourceVersion().isEmpty()) { + customer.setResourceVersion(getResourceVersion()); + + } + cacheServiceProvider.putCustomer(globalCustomerId, customer); + return ResponseEntity.accepted().build(); + + } + + @GetMapping(value = "/{global-customer-id}/service-subscriptions/service-subscription/{service-type}", + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> getCustomer(@PathVariable("global-customer-id") final String globalCustomerId, + @PathVariable("service-type") final String serviceType, final HttpServletRequest request) { + LOGGER.info("Will retrieve service subscription for 'global customer id': {} and 'service type': {} ...", + globalCustomerId, serviceType); + + final Optional<ServiceSubscription> optional = + cacheServiceProvider.getServiceSubscription(globalCustomerId, serviceType); + if (optional.isPresent()) { + final ServiceSubscription serviceSubscription = optional.get(); + LOGGER.info("found service subscription {} in cache", serviceSubscription); + return ResponseEntity.ok(serviceSubscription); + } + + LOGGER.error("Couldn't find 'global customer id': {} and 'service type': {} in cache", globalCustomerId, + serviceType); + return getRequestErrorResponseEntity(request, SERVICE_SUBSCRIPTION); + } + + @PutMapping(value = "/{global-customer-id}/service-subscriptions/service-subscription/{service-type}", + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> putServiceSubscription(@PathVariable("global-customer-id") final String globalCustomerId, + @PathVariable("service-type") final String serviceType, + @RequestBody final ServiceSubscription serviceSubscription, final HttpServletRequest request) { + LOGGER.info("Will add service subscription for 'global customer id': {} and 'service type': {} ...", + globalCustomerId, serviceType); + + if (cacheServiceProvider.putServiceSubscription(globalCustomerId, serviceType, serviceSubscription)) { + LOGGER.info("Successfully add service subscription in cache ..."); + return ResponseEntity.accepted().build(); + } + + LOGGER.error("Couldn't add service subscription using 'global customer id': {} and 'service type': {}", + globalCustomerId, serviceType); + return getRequestErrorResponseEntity(request, SERVICE_SUBSCRIPTION); + } + + @GetMapping( + value = "/{global-customer-id}/service-subscriptions/service-subscription/{service-type}/service-instances", + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> getSericeInstances(@PathVariable("global-customer-id") final String globalCustomerId, + @PathVariable("service-type") final String serviceType, + @RequestParam(name = "service-instance-name") final String serviceInstanceName, + @RequestParam(name = "depth", required = false) final Integer depth, final HttpServletRequest request) { + + LOGGER.info( + "Will retrieve service instances for 'global customer id': {}, 'service type': {} and 'service instance name: '{} with depth: {}...", + globalCustomerId, serviceType, serviceInstanceName, depth); + + final Optional<ServiceInstances> optional = + cacheServiceProvider.getServiceInstances(globalCustomerId, serviceType, serviceInstanceName); + if (optional.isPresent()) { + final ServiceInstances serviceInstances = optional.get(); + LOGGER.info("found service instance {} in cache", serviceInstances); + return ResponseEntity.ok(serviceInstances); + } + LOGGER.error( + "Couldn't find 'global customer id': {}, 'service type': {} and 'service instance name': {} with depth: {} in cache", + globalCustomerId, serviceType, serviceInstanceName, depth); + return getRequestErrorResponseEntity(request); + } + + @GetMapping( + value = "/{global-customer-id}/service-subscriptions/service-subscription/{service-type}/service-instances/service-instance/{service-instance-id}", + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> getSericeInstance(@PathVariable("global-customer-id") final String globalCustomerId, + @PathVariable("service-type") final String serviceType, + @PathVariable(name = "service-instance-id") final String serviceInstanceId, + @RequestParam(name = "depth", required = false) final Integer depth, + @RequestParam(name = "resultIndex", required = false) final Integer resultIndex, + @RequestParam(name = "resultSize", required = false) final Integer resultSize, + @RequestParam(name = "format", required = false) final String format, final HttpServletRequest request) { + + LOGGER.info( + "Will retrieve service instances for 'global customer id': {}, 'service type': {} and 'service instance id: '{} with depth: {}, resultIndex:{}, resultSize: {} and format: {}...", + globalCustomerId, serviceType, serviceInstanceId, depth, resultIndex, resultSize, format); + + final Optional<ServiceInstance> optional = + cacheServiceProvider.getServiceInstance(globalCustomerId, serviceType, serviceInstanceId); + if (optional.isPresent()) { + final ServiceInstance serviceInstance = optional.get(); + LOGGER.info("found service instance {} in cache", serviceInstance); + return ResponseEntity.ok(serviceInstance); + } + LOGGER.error( + "Couldn't find 'global customer id': {}, 'service type': {} and 'service instance id': {} with depth: {}, resultIndex:{}, resultSize: {} and format: {} in cache", + globalCustomerId, serviceType, serviceInstanceId, depth, resultIndex, resultSize, format); + return getRequestErrorResponseEntity(request); + } + + @PutMapping( + value = "/{global-customer-id}/service-subscriptions/service-subscription/{service-type}/service-instances/service-instance/{service-instance-id}", + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> putSericeInstance(@PathVariable("global-customer-id") final String globalCustomerId, + @PathVariable("service-type") final String serviceType, + @PathVariable(name = "service-instance-id") final String serviceInstanceId, + @RequestHeader(value = X_HTTP_METHOD_OVERRIDE, required = false) final String invocationId, + @RequestBody final ServiceInstance serviceInstance, final HttpServletRequest request) { + + LOGGER.info( + "Will add service instance for 'global customer id': {}, 'service type': {} and 'service instance id: '{} ...", + globalCustomerId, serviceType, serviceInstanceId); + + if (serviceInstance.getResourceVersion() == null || serviceInstance.getResourceVersion().isEmpty()) { + serviceInstance.setResourceVersion(getResourceVersion()); + } + + if (cacheServiceProvider.putServiceInstance(globalCustomerId, serviceType, serviceInstanceId, + serviceInstance)) { + nodesCacheServiceProvider.putNodeServiceInstance(serviceInstanceId, new NodeServiceInstance( + globalCustomerId, serviceType, serviceInstanceId, SERVICE_RESOURCE_TYPE, request.getRequestURI())); + return ResponseEntity.accepted().build(); + } + + LOGGER.error("Couldn't add 'global customer id': {}, 'service type': {} and 'service instance id': {} to cache", + globalCustomerId, serviceType, serviceInstanceId); + return getRequestErrorResponseEntity(request); + } + + @PostMapping( + value = "/{global-customer-id}/service-subscriptions/service-subscription/{service-type}/service-instances/service-instance/{service-instance-id}", + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> patchSericeInstance(@PathVariable("global-customer-id") final String globalCustomerId, + @PathVariable("service-type") final String serviceType, + @PathVariable(name = "service-instance-id") final String serviceInstanceId, + @RequestHeader(value = X_HTTP_METHOD_OVERRIDE, required = false) final String xHttpHeaderOverride, + @RequestBody final ServiceInstance serviceInstance, final HttpServletRequest request) { + + LOGGER.info( + "Will post service instance for 'global customer id': {}, 'service type': {}, 'service instance id: '{} and '{}': {}...", + globalCustomerId, serviceType, serviceInstanceId, X_HTTP_METHOD_OVERRIDE, xHttpHeaderOverride); + + if (HttpMethod.PATCH.toString().equalsIgnoreCase(xHttpHeaderOverride)) { + cacheServiceProvider.patchServiceInstance(globalCustomerId, serviceType, serviceInstanceId, + serviceInstance); + return ResponseEntity.accepted().build(); + } + LOGGER.error("{} not supported ... ", xHttpHeaderOverride); + + return getRequestErrorResponseEntity(request); + } + + + @GetMapping( + value = "/{global-customer-id}/service-subscriptions/service-subscription/{service-type}/service-instances/service-instance/{service-instance-id}/related-to/generic-vnfs", + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> getRelatedToGenericVnf(@PathVariable("global-customer-id") final String globalCustomerId, + @PathVariable("service-type") final String serviceType, + @PathVariable(name = "service-instance-id") final String serviceInstanceId, + @RequestParam(name = "vnf-name", required = true) final String vnfName, final HttpServletRequest request) { + + LOGGER.info( + "Will retrieve generic vnf related to information for 'global customer id': {}, 'service type': {} and 'service instance id: '{} with vnfname: {}...", + globalCustomerId, serviceType, serviceInstanceId, vnfName); + + final Optional<Relationship> optional = + cacheServiceProvider.getRelationship(globalCustomerId, serviceType, serviceInstanceId, vnfName); + + if (optional.isPresent()) { + + final Relationship relationship = optional.get(); + final Optional<RelationshipData> relationshipDataOptional = relationship.getRelationshipData().stream() + .filter(existing -> GENERIC_VNF_VNF_ID.equals(existing.getRelationshipKey())).findFirst(); + + if (relationshipDataOptional.isPresent()) { + final RelationshipData relationshipData = relationshipDataOptional.get(); + final String vnfId = relationshipData.getRelationshipValue(); + final Optional<GenericVnf> genericVnfOptional = genericVnfCacheServiceProvider.getGenericVnf(vnfId); + if (genericVnfOptional.isPresent()) { + final GenericVnfs genericVnfs = new GenericVnfs(); + genericVnfs.getGenericVnf().add(genericVnfOptional.get()); + LOGGER.info("found service instance {} in cache", relationship); + return ResponseEntity.ok(genericVnfs); + } + } + } + LOGGER.error( + "Couldn't find generic vnf related to information for 'global customer id': {}, 'service type': {} and 'service instance id: '{} with vnfname: {}...", + globalCustomerId, serviceType, serviceInstanceId, vnfName); + return getRequestErrorResponseEntity(request, GENERIC_VNF); + } + + @PutMapping( + value = "/{global-customer-id}/service-subscriptions/service-subscription/{service-type}/service-instances/service-instance/{service-instance-id}" + + BI_DIRECTIONAL_RELATIONSHIP_LIST_URL, + consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}, + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> putSericeInstanceRelationShip( + @PathVariable("global-customer-id") final String globalCustomerId, + @PathVariable("service-type") final String serviceType, + @PathVariable(name = "service-instance-id") final String serviceInstanceId, + @RequestBody final Relationship relationship, final HttpServletRequest request) { + + LOGGER.info( + "Will add {} relationship for 'global customer id': {}, 'service type': {} and 'service instance id: '{} ...", + relationship.getRelatedTo(), globalCustomerId, serviceType, serviceInstanceId); + final Optional<Relationship> optional = cacheServiceProvider.addRelationShip(globalCustomerId, serviceType, + serviceInstanceId, relationship, request.getRequestURI()); + + if (optional.isPresent()) { + final Relationship resultantRelationship = optional.get(); + LOGGER.info("Relationship add, sending resultant relationship: {} in response ...", resultantRelationship); + return ResponseEntity.accepted().body(resultantRelationship); + } + + LOGGER.error( + "Couldn't add {} relationship for 'global customer id': {}, 'service type': {} and 'service instance id: '{} ...", + relationship.getRelatedTo(), globalCustomerId, serviceType, serviceInstanceId); + + return getRequestErrorResponseEntity(request); + } + + @DeleteMapping( + value = "/{global-customer-id}/service-subscriptions/service-subscription/{service-type}/service-instances/service-instance/{service-instance-id}", + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> deleteSericeInstance(@PathVariable("global-customer-id") final String globalCustomerId, + @PathVariable("service-type") final String serviceType, + @PathVariable(name = "service-instance-id") final String serviceInstanceId, + @RequestParam(name = "resource-version") final String resourceVersion, final HttpServletRequest request) { + + LOGGER.info( + "Will delete SericeInstance for 'global-customer-id': {}, 'service-type': {}, 'service-instance-id': {} and 'resource-version': {}", + globalCustomerId, serviceType, serviceInstanceId, resourceVersion); + + if (cacheServiceProvider.deleteSericeInstance(globalCustomerId, serviceType, serviceInstanceId, + resourceVersion)) { + LOGGER.info( + "Successfully deleted SericeInstance from cache for 'global-customer-id': {}, 'service-type': {}, 'service-instance-id': {} and 'resource-version': {}", + globalCustomerId, serviceType, serviceInstanceId, resourceVersion); + return ResponseEntity.noContent().build(); + } + + LOGGER.error( + "Unable to delete SericeInstance from cache for 'global-customer-id': {}, 'service-type': {}, 'service-instance-id': {} and 'resource-version': {}", + globalCustomerId, serviceType, serviceInstanceId, resourceVersion); + + return getRequestErrorResponseEntity(request); + + } +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/CloudRegionsController.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/CloudRegionsController.java new file mode 100755 index 000000000..39bdb7d4b --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/CloudRegionsController.java @@ -0,0 +1,396 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.controller; + +import static org.onap.aaisimulator.utils.Constants.BI_DIRECTIONAL_RELATIONSHIP_LIST_URL; +import static org.onap.aaisimulator.utils.Constants.CLOUD_REGION; +import static org.onap.aaisimulator.utils.Constants.CLOUD_REGIONS; +import static org.onap.aaisimulator.utils.Constants.ESR_SYSTEM_INFO_LIST; +import static org.onap.aaisimulator.utils.Constants.RELATIONSHIP_LIST_RELATIONSHIP_URL; +import static org.onap.aaisimulator.utils.Constants.VSERVER; +import static org.onap.aaisimulator.utils.HttpServiceUtils.getHeaders; +import static org.onap.aaisimulator.utils.RequestErrorResponseUtils.getRequestErrorResponseEntity; +import static org.onap.aaisimulator.utils.RequestErrorResponseUtils.getResourceVersion; +import java.util.Optional; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.MediaType; +import org.onap.aai.domain.yang.CloudRegion; +import org.onap.aai.domain.yang.EsrSystemInfo; +import org.onap.aai.domain.yang.EsrSystemInfoList; +import org.onap.aai.domain.yang.Relationship; +import org.onap.aai.domain.yang.Tenant; +import org.onap.aai.domain.yang.Vserver; +import org.onap.aaisimulator.models.CloudRegionKey; +import org.onap.aaisimulator.service.providers.CloudRegionCacheServiceProvider; +import org.onap.aaisimulator.utils.HttpServiceUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +@Controller +@RequestMapping(path = CLOUD_REGIONS) +public class CloudRegionsController { + private static final Logger LOGGER = LoggerFactory.getLogger(CloudRegionsController.class); + + private final CloudRegionCacheServiceProvider cacheServiceProvider; + + @Autowired + public CloudRegionsController(final CloudRegionCacheServiceProvider cacheServiceProvider) { + this.cacheServiceProvider = cacheServiceProvider; + } + + @PutMapping(value = "{cloud-owner}/{cloud-region-id}", + consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}, + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> putCloudRegion(@RequestBody final CloudRegion cloudRegion, + @PathVariable("cloud-owner") final String cloudOwner, + @PathVariable("cloud-region-id") final String cloudRegionId, final HttpServletRequest request) { + + final CloudRegionKey key = new CloudRegionKey(cloudOwner, cloudRegionId); + + if (key.isValid()) { + LOGGER.info("Will add CloudRegion to cache with key 'key': {} ....", key); + if (cloudRegion.getResourceVersion() == null || cloudRegion.getResourceVersion().isEmpty()) { + cloudRegion.setResourceVersion(getResourceVersion()); + } + cacheServiceProvider.putCloudRegion(key, cloudRegion); + return ResponseEntity.accepted().build(); + } + + LOGGER.error("Unable to add CloudRegion in cache because of invalid key {}", key); + return getRequestErrorResponseEntity(request, CLOUD_REGION); + } + + @GetMapping(value = "{cloud-owner}/{cloud-region-id}", + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> getCloudRegion(@PathVariable("cloud-owner") final String cloudOwner, + @PathVariable("cloud-region-id") final String cloudRegionId, + @RequestParam(name = "depth", required = false) final Integer depth, final HttpServletRequest request) { + final CloudRegionKey key = new CloudRegionKey(cloudOwner, cloudRegionId); + LOGGER.info("Retrieving CloudRegion using key : {} with depth: {}...", key, depth); + if (key.isValid()) { + final Optional<CloudRegion> optional = cacheServiceProvider.getCloudRegion(key); + if (optional.isPresent()) { + final CloudRegion cloudRegion = optional.get(); + LOGGER.info("found CloudRegion {} in cache", cloudRegion); + return ResponseEntity.ok(cloudRegion); + } + } + LOGGER.error("Unable to find CloudRegion in cache using {}", key); + return getRequestErrorResponseEntity(request, CLOUD_REGION); + } + + @PutMapping(value = "{cloud-owner}/{cloud-region-id}" + BI_DIRECTIONAL_RELATIONSHIP_LIST_URL, + consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}, + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> putRelationShip(@PathVariable("cloud-owner") final String cloudOwner, + @PathVariable("cloud-region-id") final String cloudRegionId, @RequestBody final Relationship relationship, + final HttpServletRequest request) { + LOGGER.info("Will add {} relationship to : {} ...", relationship.getRelatedTo()); + + final CloudRegionKey key = new CloudRegionKey(cloudOwner, cloudRegionId); + + final Optional<Relationship> optional = + cacheServiceProvider.addRelationShip(key, relationship, request.getRequestURI()); + + if (optional.isPresent()) { + final Relationship resultantRelationship = optional.get(); + LOGGER.info("Relationship add, sending resultant relationship: {} in response ...", resultantRelationship); + return ResponseEntity.accepted().body(resultantRelationship); + } + + LOGGER.error("Couldn't add {} relationship for 'key': {} ...", relationship.getRelatedTo(), key); + return getRequestErrorResponseEntity(request, VSERVER); + + } + + @PutMapping(value = "{cloud-owner}/{cloud-region-id}/tenants/tenant/{tenant-id}", + consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}, + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> putTenant(@RequestBody final Tenant tenant, + @PathVariable("cloud-owner") final String cloudOwner, + @PathVariable("cloud-region-id") final String cloudRegionId, + @PathVariable("tenant-id") final String tenantId, final HttpServletRequest request) { + + final CloudRegionKey key = new CloudRegionKey(cloudOwner, cloudRegionId); + + if (key.isValid()) { + LOGGER.info("Will add Tenant to cache with key 'key': {} ....", key); + if (tenant.getResourceVersion() == null || tenant.getResourceVersion().isEmpty()) { + tenant.setResourceVersion(getResourceVersion()); + } + if (cacheServiceProvider.putTenant(key, tenantId, tenant)) { + return ResponseEntity.accepted().build(); + } + } + + LOGGER.error("Unable to add Tenant in cache using key {}", key); + return getRequestErrorResponseEntity(request, CLOUD_REGION); + } + + @GetMapping(value = "{cloud-owner}/{cloud-region-id}/tenants/tenant/{tenant-id}", + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> getTenant(@PathVariable("cloud-owner") final String cloudOwner, + @PathVariable("cloud-region-id") final String cloudRegionId, + @PathVariable("tenant-id") final String tenantId, final HttpServletRequest request) { + final CloudRegionKey key = new CloudRegionKey(cloudOwner, cloudRegionId); + LOGGER.info("Retrieving Tenant using key : {} and tenant-id:{} ...", key, tenantId); + if (key.isValid()) { + final Optional<Tenant> optional = cacheServiceProvider.getTenant(key, tenantId); + if (optional.isPresent()) { + final Tenant tenant = optional.get(); + LOGGER.info("found Tenant {} in cache", tenant); + return ResponseEntity.ok(tenant); + } + } + LOGGER.error("Unable to find Tenant in cache key : {} and tenant-id:{} ...", key, tenantId); + return getRequestErrorResponseEntity(request, CLOUD_REGION); + } + + @PutMapping( + value = "{cloud-owner}/{cloud-region-id}/tenants/tenant/{tenant-id}" + RELATIONSHIP_LIST_RELATIONSHIP_URL, + consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}, + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> putRelationShip(@RequestBody final Relationship relationship, + @PathVariable("cloud-owner") final String cloudOwner, + @PathVariable("cloud-region-id") final String cloudRegionId, + @PathVariable("tenant-id") final String tenantId, final HttpServletRequest request) { + + final CloudRegionKey key = new CloudRegionKey(cloudOwner, cloudRegionId); + LOGGER.info("Will put RelationShip for key : {} and tenant-id:{} ...", key, tenantId); + + if (relationship.getRelatedLink() != null) { + final String targetBaseUrl = HttpServiceUtils.getBaseUrl(request).toString(); + final HttpHeaders incomingHeader = getHeaders(request); + final boolean result = cacheServiceProvider.addRelationShip(incomingHeader, targetBaseUrl, + request.getRequestURI(), key, tenantId, relationship); + if (result) { + LOGGER.info("added created bi directional relationship with {}", relationship.getRelatedLink()); + return ResponseEntity.accepted().build(); + } + + } + LOGGER.error("Unable to add relationship for related link: {}", relationship.getRelatedLink()); + return getRequestErrorResponseEntity(request, CLOUD_REGION); + } + + @PutMapping(value = "{cloud-owner}/{cloud-region-id}/esr-system-info-list/esr-system-info/{esr-system-info-id}", + consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}, + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> putEsrSystemInfo(@RequestBody final EsrSystemInfo esrSystemInfo, + @PathVariable("esr-system-info-id") final String esrSystemInfoId, + @PathVariable("cloud-owner") final String cloudOwner, + @PathVariable("cloud-region-id") final String cloudRegionId, final HttpServletRequest request) { + + final CloudRegionKey key = new CloudRegionKey(cloudOwner, cloudRegionId); + + LOGGER.info("Will put esrSystemInfo for 'key': {} ...", key); + + if (esrSystemInfo.getResourceVersion() == null || esrSystemInfo.getResourceVersion().isEmpty()) { + esrSystemInfo.setResourceVersion(getResourceVersion()); + + } + + if (cacheServiceProvider.putEsrSystemInfo(key, esrSystemInfoId, esrSystemInfo)) { + LOGGER.info("Successfully added EsrSystemInfo key : {} ...", key, esrSystemInfo); + return ResponseEntity.accepted().build(); + } + LOGGER.error("Unable to add EsrSystemInfo in cache for key : {} ...", key); + + return getRequestErrorResponseEntity(request, ESR_SYSTEM_INFO_LIST); + } + + @GetMapping(value = "{cloud-owner}/{cloud-region-id}/esr-system-info-list", + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> getEsrSystemInfoList(@PathVariable("cloud-owner") final String cloudOwner, + @PathVariable("cloud-region-id") final String cloudRegionId, final HttpServletRequest request) { + final CloudRegionKey key = new CloudRegionKey(cloudOwner, cloudRegionId); + LOGGER.info("Retrieving EsrSystemInfoList using key : {} ...", key); + if (key.isValid()) { + final Optional<EsrSystemInfoList> optional = cacheServiceProvider.getEsrSystemInfoList(key); + if (optional.isPresent()) { + final EsrSystemInfoList esrSystemInfoList = optional.get(); + LOGGER.info("found EsrSystemInfoList {} in cache", esrSystemInfoList); + return ResponseEntity.ok(esrSystemInfoList); + } + } + LOGGER.error("Unable to find EsrSystemInfoList in cache using key : {} ...", key); + return getRequestErrorResponseEntity(request, CLOUD_REGION); + } + + @PutMapping(value = "{cloud-owner}/{cloud-region-id}/tenants/tenant/{tenant-id}/vservers/vserver/{vserver-id}", + consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}, + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> putVserver(@RequestBody final Vserver vServer, + @PathVariable("cloud-owner") final String cloudOwner, + @PathVariable("cloud-region-id") final String cloudRegionId, + @PathVariable("tenant-id") final String tenantId, @PathVariable("vserver-id") final String vServerId, + final HttpServletRequest request) { + + final CloudRegionKey key = new CloudRegionKey(cloudOwner, cloudRegionId); + if (vServer.getResourceVersion() == null || vServer.getResourceVersion().isEmpty()) { + vServer.setResourceVersion(getResourceVersion()); + } + LOGGER.info("Will put Vserver in cache using using key: {}, tenantId: {}, vServerId: {} ...", key, tenantId, + vServerId); + + if (cacheServiceProvider.putVserver(key, tenantId, vServerId, vServer)) { + + if (vServer.getRelationshipList() != null) { + for (final Relationship relationship : vServer.getRelationshipList().getRelationship()) { + if (relationship.getRelatedLink() != null) { + final String requestUri = request.getRequestURI(); + final String targetBaseUrl = + HttpServiceUtils.getBaseUrl(request.getRequestURL(), requestUri).toString(); + final HttpHeaders incomingHeader = getHeaders(request); + final boolean result = cacheServiceProvider.addVServerRelationShip(incomingHeader, + targetBaseUrl, requestUri, key, tenantId, vServerId, relationship); + if (!result) { + LOGGER.error( + "Unable to add Vserver relationship in cache using key: {}, tenantId: {}, vServerId: {}", + key, tenantId, vServerId); + return getRequestErrorResponseEntity(request, CLOUD_REGION); + } + LOGGER.info("Successfully added relationship with {}", relationship.getRelatedLink()); + } + } + } + + LOGGER.info("Successfully added Vserver for key: {}, tenantId: {}, vServerId: {} ...", key, tenantId, + vServerId); + return ResponseEntity.accepted().build(); + } + LOGGER.error("Unable to add Vserver in cache using key: {}, tenantId: {}, vServerId: {}", key, tenantId, + vServerId); + return getRequestErrorResponseEntity(request, CLOUD_REGION); + } + + @GetMapping(value = "{cloud-owner}/{cloud-region-id}/tenants/tenant/{tenant-id}/vservers/vserver/{vserver-id}", + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> getVserver(@PathVariable("cloud-owner") final String cloudOwner, + @PathVariable("cloud-region-id") final String cloudRegionId, + @PathVariable("tenant-id") final String tenantId, @PathVariable("vserver-id") final String vServerId, + final HttpServletRequest request) { + + final CloudRegionKey key = new CloudRegionKey(cloudOwner, cloudRegionId); + LOGGER.info("Retrieving Vserver using key: {}, tenant-id: {} and vserver-id: {}...", key, tenantId, vServerId); + final Optional<Vserver> optional = cacheServiceProvider.getVserver(key, tenantId, vServerId); + if (optional.isPresent()) { + final Vserver vServer = optional.get(); + LOGGER.info("found Vserver {} in cache", vServer); + return ResponseEntity.ok(vServer); + } + LOGGER.error("Unable to find Vserver in cache using key: {}, tenant-id: {} and vserver-id: {}...", key, + tenantId, vServerId); + return getRequestErrorResponseEntity(request, CLOUD_REGION); + } + + + @DeleteMapping(value = "{cloud-owner}/{cloud-region-id}/tenants/tenant/{tenant-id}/vservers/vserver/{vserver-id}", + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> deleteVserver(@PathVariable("cloud-owner") final String cloudOwner, + @PathVariable("cloud-region-id") final String cloudRegionId, + @PathVariable("tenant-id") final String tenantId, @PathVariable("vserver-id") final String vServerId, + @RequestParam(name = "resource-version") final String resourceVersion, final HttpServletRequest request) { + + final CloudRegionKey key = new CloudRegionKey(cloudOwner, cloudRegionId); + LOGGER.info("Will delete Vserver using key: {}, tenant-id: {}, vserver-id: {} and resource-version: {}...", key, + tenantId, vServerId, resourceVersion); + + + if (cacheServiceProvider.deleteVserver(key, tenantId, vServerId, resourceVersion)) { + LOGGER.info( + "Successfully delete Vserver from cache for key: {}, tenant-id: {}, vserver-id: {} and resource-version: {}", + key, tenantId, vServerId, resourceVersion); + return ResponseEntity.noContent().build(); + } + + LOGGER.error( + "Unable to delete Vserver from cache using key: {}, tenant-id: {}, vserver-id: {} and resource-version: {} ...", + key, tenantId, vServerId, resourceVersion); + return getRequestErrorResponseEntity(request, CLOUD_REGION); + } + + @PutMapping( + value = "{cloud-owner}/{cloud-region-id}/tenants/tenant/{tenant-id}/vservers/vserver/{vserver-id}" + + RELATIONSHIP_LIST_RELATIONSHIP_URL, + consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}, + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> putVserverRelationShip(@PathVariable("cloud-owner") final String cloudOwner, + @PathVariable("cloud-region-id") final String cloudRegionId, + @PathVariable("tenant-id") final String tenantId, @PathVariable("vserver-id") final String vServerId, + @RequestBody final Relationship relationship, final HttpServletRequest request) { + final CloudRegionKey key = new CloudRegionKey(cloudOwner, cloudRegionId); + LOGGER.info("Will add {} relationship to : {} ...", relationship.getRelatedTo()); + + if (relationship.getRelatedLink() != null) { + final String targetBaseUrl = HttpServiceUtils.getBaseUrl(request).toString(); + final HttpHeaders incomingHeader = getHeaders(request); + final boolean result = cacheServiceProvider.addVServerRelationShip(incomingHeader, targetBaseUrl, + request.getRequestURI(), key, tenantId, vServerId, relationship); + if (result) { + LOGGER.info("added created bi directional relationship with {}", relationship.getRelatedLink()); + return ResponseEntity.accepted().build(); + } + } + LOGGER.error("Couldn't add {} relationship for 'key': {} ...", relationship.getRelatedTo(), key); + return getRequestErrorResponseEntity(request, CLOUD_REGION); + + } + + @PutMapping( + value = "{cloud-owner}/{cloud-region-id}/tenants/tenant/{tenant-id}/vservers/vserver/{vserver-id}" + + BI_DIRECTIONAL_RELATIONSHIP_LIST_URL, + consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}, + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> putBiDirectionalVServerRelationShip(@PathVariable("cloud-owner") final String cloudOwner, + @PathVariable("cloud-region-id") final String cloudRegionId, + @PathVariable("tenant-id") final String tenantId, @PathVariable("vserver-id") final String vServerId, + @RequestBody final Relationship relationship, final HttpServletRequest request) { + final CloudRegionKey key = new CloudRegionKey(cloudOwner, cloudRegionId); + LOGGER.info("Will add {} relationship to : {} ...", relationship.getRelatedTo()); + + final Optional<Relationship> optional = cacheServiceProvider.addvServerRelationShip(key, tenantId, vServerId, + relationship, request.getRequestURI()); + + if (optional.isPresent()) { + final Relationship resultantRelationship = optional.get(); + LOGGER.info("Relationship add, sending resultant relationship: {} in response ...", resultantRelationship); + return ResponseEntity.accepted().body(resultantRelationship); + } + LOGGER.error("Couldn't add {} relationship for 'key': {} ...", relationship.getRelatedTo(), key); + return getRequestErrorResponseEntity(request, CLOUD_REGION); + + } +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/ExternalSystemEsrController.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/ExternalSystemEsrController.java new file mode 100755 index 000000000..00c296f49 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/ExternalSystemEsrController.java @@ -0,0 +1,175 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.controller; + +import static org.onap.aaisimulator.utils.Constants.ESR_SYSTEM_INFO; +import static org.onap.aaisimulator.utils.Constants.ESR_SYSTEM_INFO_LIST; +import static org.onap.aaisimulator.utils.Constants.ESR_VNFM; +import static org.onap.aaisimulator.utils.Constants.EXTERNAL_SYSTEM_ESR_VNFM_LIST_URL; +import static org.onap.aaisimulator.utils.Constants.RELATIONSHIP_LIST_RELATIONSHIP_URL; +import static org.onap.aaisimulator.utils.HttpServiceUtils.getHeaders; +import static org.onap.aaisimulator.utils.RequestErrorResponseUtils.getRequestErrorResponseEntity; +import static org.onap.aaisimulator.utils.RequestErrorResponseUtils.getResourceVersion; +import java.util.List; +import java.util.Optional; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.MediaType; +import org.onap.aai.domain.yang.EsrSystemInfo; +import org.onap.aai.domain.yang.EsrSystemInfoList; +import org.onap.aai.domain.yang.EsrVnfm; +import org.onap.aai.domain.yang.EsrVnfmList; +import org.onap.aai.domain.yang.Relationship; +import org.onap.aaisimulator.service.providers.ExternalSystemCacheServiceProvider; +import org.onap.aaisimulator.utils.HttpServiceUtils; +import org.onap.aaisimulator.utils.RequestErrorResponseUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +@Controller +@RequestMapping(path = EXTERNAL_SYSTEM_ESR_VNFM_LIST_URL) +public class ExternalSystemEsrController { + private static final Logger LOGGER = LoggerFactory.getLogger(ExternalSystemEsrController.class); + + private final ExternalSystemCacheServiceProvider cacheServiceProvider; + + @Autowired + public ExternalSystemEsrController(final ExternalSystemCacheServiceProvider cacheServiceProvider) { + this.cacheServiceProvider = cacheServiceProvider; + } + + @PutMapping(value = "/esr-vnfm/{vnfm-id}", consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}, + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> putEsrVnfm(@RequestBody final EsrVnfm esrVnfm, + @PathVariable("vnfm-id") final String vnfmId, final HttpServletRequest request) { + LOGGER.info("Will put esr-vnfm to cache for 'vnfm id': {} ...", esrVnfm.getVnfmId()); + + if (esrVnfm.getResourceVersion() == null || esrVnfm.getResourceVersion().isEmpty()) { + esrVnfm.setResourceVersion(getResourceVersion()); + + } + cacheServiceProvider.putEsrVnfm(vnfmId, esrVnfm); + return ResponseEntity.accepted().build(); + } + + @GetMapping(value = "/esr-vnfm/{vnfm-id}", produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> getEsrVnfm(@PathVariable("vnfm-id") final String vnfmId, + @RequestParam(name = "depth", required = false) final Integer depth, final HttpServletRequest request) { + LOGGER.info("Will retrieve ESR VNFM for 'vnfm id': {} with depth: {}...", vnfmId, depth); + + final Optional<EsrVnfm> optional = cacheServiceProvider.getEsrVnfm(vnfmId); + if (optional.isPresent()) { + final EsrVnfm esrVnfm = optional.get(); + LOGGER.info("found esrVnfm {} in cache", esrVnfm); + return ResponseEntity.ok(esrVnfm); + } + + LOGGER.error("Couldn't Esr Vnfm for 'vnfm id': {} with depth: {}...", vnfmId, depth); + return getRequestErrorResponseEntity(request, ESR_VNFM); + } + + @GetMapping(produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> getEsrVnfmList(final HttpServletRequest request) { + LOGGER.info("Will retrieve a list of all ESR VNFMs"); + + final List<EsrVnfm> esrVnfms = cacheServiceProvider.getAllEsrVnfm(); + LOGGER.info("found {} Esr Vnfms in cache", esrVnfms.size()); + + final EsrVnfmList esrVnfmList = new EsrVnfmList(); + esrVnfmList.getEsrVnfm().addAll(esrVnfms); + + return ResponseEntity.ok(esrVnfmList); + } + + @PutMapping(value = "/esr-vnfm/{vnfm-id}/esr-system-info-list/esr-system-info/{esr-system-info-id}", + consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}, + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> putEsrSystemInfo(@RequestBody final EsrSystemInfo esrSystemInfo, + @PathVariable("vnfm-id") final String vnfmId, + @PathVariable("esr-system-info-id") final String esrSystemInfoId, final HttpServletRequest request) { + LOGGER.info("Will put esrSystemInfo for 'vnfm id': {} and 'esr-system-info-id': {} ...", vnfmId, esrSystemInfo); + + if (esrSystemInfo.getResourceVersion() == null || esrSystemInfo.getResourceVersion().isEmpty()) { + esrSystemInfo.setResourceVersion(getResourceVersion()); + + } + + if (cacheServiceProvider.putEsrSystemInfo(vnfmId, esrSystemInfoId, esrSystemInfo)) { + LOGGER.info("Successfully added EsrSystemInfo for 'vnfm id': {} and 'esr-system-info-id': {} ...", vnfmId, + esrSystemInfo); + return ResponseEntity.accepted().build(); + } + LOGGER.error("Unable to add esrSystemInfo for 'vnfm id': {} and 'esr-system-info-id': {} ...", vnfmId, + esrSystemInfo); + return getRequestErrorResponseEntity(request, ESR_SYSTEM_INFO_LIST); + } + + @GetMapping(value = "/esr-vnfm/{vnfm-id}/esr-system-info-list", + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> getEsrSystemInfoList(@PathVariable("vnfm-id") final String vnfmId, + final HttpServletRequest request) { + LOGGER.info("Will retrieve esrSystemInfoList for 'vnfm id': {} ...", vnfmId); + + final Optional<EsrSystemInfoList> optional = cacheServiceProvider.getEsrSystemInfoList(vnfmId); + if (optional.isPresent()) { + final EsrSystemInfoList esrSystemInfoList = optional.get(); + LOGGER.info("found esrSystemInfoList {} in cache", esrSystemInfoList); + return ResponseEntity.ok(esrSystemInfoList); + } + + LOGGER.error("Couldn't find esrSystemInfoList for 'vnfm id': {} ...", vnfmId); + return getRequestErrorResponseEntity(request, ESR_SYSTEM_INFO); + } + + @PutMapping(value = "/esr-vnfm/{vnfm-id}" + RELATIONSHIP_LIST_RELATIONSHIP_URL, + consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}, + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> putEsrVnfmRelationShip(@RequestBody final Relationship relationship, + @PathVariable("vnfm-id") final String vnfmId, final HttpServletRequest request) { + LOGGER.info("Will put RelationShip for 'vnfm-id': {} ...", vnfmId); + + if (relationship.getRelatedLink() != null) { + final String targetBaseUrl = HttpServiceUtils.getBaseUrl(request).toString(); + final HttpHeaders incomingHeader = getHeaders(request); + final boolean result = cacheServiceProvider.addRelationShip(incomingHeader, targetBaseUrl, + request.getRequestURI(), vnfmId, relationship); + if (result) { + LOGGER.info("added created bi directional relationship with {}", relationship.getRelatedLink()); + return ResponseEntity.accepted().build(); + } + } + LOGGER.error("Unable to add relationship for related link: {}", relationship.getRelatedLink()); + return RequestErrorResponseUtils.getRequestErrorResponseEntity(request, ESR_VNFM); + } + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/GenericVnfsController.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/GenericVnfsController.java new file mode 100755 index 000000000..2f922ea88 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/GenericVnfsController.java @@ -0,0 +1,215 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.controller; + +import static org.onap.aaisimulator.utils.Constants.APPLICATION_MERGE_PATCH_JSON; +import static org.onap.aaisimulator.utils.Constants.BI_DIRECTIONAL_RELATIONSHIP_LIST_URL; +import static org.onap.aaisimulator.utils.Constants.GENERIC_VNF; +import static org.onap.aaisimulator.utils.Constants.GENERIC_VNFS_URL; +import static org.onap.aaisimulator.utils.Constants.RELATIONSHIP_LIST_RELATIONSHIP_URL; +import static org.onap.aaisimulator.utils.Constants.X_HTTP_METHOD_OVERRIDE; +import static org.onap.aaisimulator.utils.HttpServiceUtils.getHeaders; +import static org.onap.aaisimulator.utils.RequestErrorResponseUtils.getRequestErrorResponseEntity; +import static org.onap.aaisimulator.utils.RequestErrorResponseUtils.getResourceVersion; +import java.util.List; +import java.util.Optional; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.MediaType; +import org.onap.aai.domain.yang.GenericVnf; +import org.onap.aai.domain.yang.GenericVnfs; +import org.onap.aai.domain.yang.Relationship; +import org.onap.aaisimulator.service.providers.GenericVnfCacheServiceProvider; +import org.onap.aaisimulator.utils.HttpServiceUtils; +import org.onap.aaisimulator.utils.RequestErrorResponseUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +@Controller +@RequestMapping(path = GENERIC_VNFS_URL) +public class GenericVnfsController { + + private static final Logger LOGGER = LoggerFactory.getLogger(GenericVnfsController.class); + + private final GenericVnfCacheServiceProvider cacheServiceProvider; + + + @Autowired + public GenericVnfsController(final GenericVnfCacheServiceProvider cacheServiceProvider) { + this.cacheServiceProvider = cacheServiceProvider; + } + + @PutMapping(value = "/generic-vnf/{vnf-id}", consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}, + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> putGenericVnf(@RequestBody final GenericVnf genericVnf, + @PathVariable("vnf-id") final String vnfId, final HttpServletRequest request) { + LOGGER.info("Will add GenericVnf to cache with 'vnf-id': {} ...", vnfId); + + if (genericVnf.getResourceVersion() == null || genericVnf.getResourceVersion().isEmpty()) { + genericVnf.setResourceVersion(getResourceVersion()); + + } + cacheServiceProvider.putGenericVnf(vnfId, genericVnf); + return ResponseEntity.accepted().build(); + + } + + @GetMapping(value = "/generic-vnf/{vnf-id}", produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> getGenericVnf(@PathVariable("vnf-id") final String vnfId, + @RequestParam(name = "depth", required = false) final Integer depth, + @RequestParam(name = "resultIndex", required = false) final Integer resultIndex, + @RequestParam(name = "resultSize", required = false) final Integer resultSize, + @RequestParam(name = "format", required = false) final String format, final HttpServletRequest request) { + LOGGER.info( + "Will get GenericVnf for 'vnf-id': {} with depth: {}, resultIndex: {}, resultSize:{}, format: {} ...", + vnfId, depth, resultIndex, resultSize, format); + + final Optional<GenericVnf> optional = cacheServiceProvider.getGenericVnf(vnfId); + + if (optional.isPresent()) { + final GenericVnf genericVnf = optional.get(); + LOGGER.info("found GenericVnf {} in cache", genericVnf); + return ResponseEntity.ok(genericVnf); + } + + LOGGER.error( + "Unable to find GenericVnf in cache for 'vnf-id': {} with depth: {}, resultIndex: {}, resultSize:{}, format:{} ...", + vnfId, depth, resultIndex, resultSize, format); + return getRequestErrorResponseEntity(request, GENERIC_VNF); + + } + + @PutMapping(value = "/generic-vnf/{vnf-id}" + RELATIONSHIP_LIST_RELATIONSHIP_URL, + consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}, + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> putGenericVnfRelationShip(@RequestBody final Relationship relationship, + @PathVariable("vnf-id") final String vnfId, final HttpServletRequest request) { + LOGGER.info("Will put RelationShip for 'vnf-id': {} ...", vnfId); + + if (relationship.getRelatedLink() != null) { + final String targetBaseUrl = HttpServiceUtils.getBaseUrl(request).toString(); + final HttpHeaders incomingHeader = getHeaders(request); + final boolean result = cacheServiceProvider.addRelationShip(incomingHeader, targetBaseUrl, + request.getRequestURI(), vnfId, relationship); + if (result) { + LOGGER.info("added created bi directional relationship with {}", relationship.getRelatedLink()); + return ResponseEntity.accepted().build(); + } + } + LOGGER.error("Unable to add relationship for related link: {}", relationship.getRelatedLink()); + return RequestErrorResponseUtils.getRequestErrorResponseEntity(request, GENERIC_VNF); + } + + @PutMapping(value = "/generic-vnf/{vnf-id}" + BI_DIRECTIONAL_RELATIONSHIP_LIST_URL, + consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}, + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> putBiDirectionalRelationShip(@RequestBody final Relationship relationship, + @PathVariable("vnf-id") final String vnfId, final HttpServletRequest request) { + LOGGER.info("Will put RelationShip for 'vnf-id': {} ...", vnfId); + + final Optional<Relationship> optional = + cacheServiceProvider.addRelationShip(vnfId, relationship, request.getRequestURI()); + + if (optional.isPresent()) { + final Relationship resultantRelationship = optional.get(); + LOGGER.info("Relationship add, sending resultant relationship: {} in response ...", resultantRelationship); + return ResponseEntity.accepted().body(resultantRelationship); + } + + LOGGER.error("Unable to add relationship for related link: {}", relationship.getRelatedLink()); + return RequestErrorResponseUtils.getRequestErrorResponseEntity(request, GENERIC_VNF); + } + + @PostMapping(value = "/generic-vnf/{vnf-id}", + consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, APPLICATION_MERGE_PATCH_JSON}, + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> patchGenericVnf(@RequestBody final GenericVnf genericVnf, + @PathVariable("vnf-id") final String vnfId, + @RequestHeader(value = X_HTTP_METHOD_OVERRIDE, required = false) final String xHttpHeaderOverride, + final HttpServletRequest request) { + + LOGGER.info("Will post GenericVnf to cache with 'vnf-id': {} and '{}': {} ...", vnfId, X_HTTP_METHOD_OVERRIDE, + xHttpHeaderOverride); + + if (HttpMethod.PATCH.toString().equalsIgnoreCase(xHttpHeaderOverride)) { + if (cacheServiceProvider.patchGenericVnf(vnfId, genericVnf)) { + return ResponseEntity.accepted().build(); + } + LOGGER.error("Unable to apply patch to GenericVnf using 'vnf-id': {} ... ", vnfId); + return getRequestErrorResponseEntity(request, GENERIC_VNF); + } + LOGGER.error("{} not supported ... ", xHttpHeaderOverride); + + return getRequestErrorResponseEntity(request, GENERIC_VNF); + } + + @GetMapping(produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> getGenericVnfs(@RequestParam(name = "selflink") final String selflink, + final HttpServletRequest request) { + LOGGER.info("will retrieve GenericVnfs using selflink: {}", selflink); + + final List<GenericVnf> genericVnfList = cacheServiceProvider.getGenericVnfs(selflink); + + if (genericVnfList.isEmpty()) { + LOGGER.error("No matching generic vnfs found using selflink: {}", selflink); + return getRequestErrorResponseEntity(request, GENERIC_VNF); + } + + LOGGER.info("found {} GenericVnfs in cache", genericVnfList.size()); + final GenericVnfs genericVnfs = new GenericVnfs(); + genericVnfs.getGenericVnf().addAll(genericVnfList); + return ResponseEntity.ok(genericVnfs); + } + + @DeleteMapping(value = "/generic-vnf/{vnf-id}", produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> deleteGenericVnf(@PathVariable("vnf-id") final String vnfId, + @RequestParam(name = "resource-version") final String resourceVersion, final HttpServletRequest request) { + LOGGER.info("Will delete GenericVnf for 'vnf-id': {} and 'resource-version': {}", vnfId, resourceVersion); + + if (cacheServiceProvider.deleteGenericVnf(vnfId, resourceVersion)) { + LOGGER.info("Successfully delete GenericVnf from cache for 'vnf-id': {} and 'resource-version': {}", vnfId, + resourceVersion); + return ResponseEntity.noContent().build(); + } + + LOGGER.error("Unable to delete GenericVnf for 'vnf-id': {} and 'resource-version': {} ...", vnfId, + resourceVersion); + return getRequestErrorResponseEntity(request, GENERIC_VNF); + + } + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/LinesOfBusinessController.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/LinesOfBusinessController.java new file mode 100755 index 000000000..de1c5b995 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/LinesOfBusinessController.java @@ -0,0 +1,138 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.controller; + +import static org.onap.aaisimulator.utils.Constants.BI_DIRECTIONAL_RELATIONSHIP_LIST_URL; +import static org.onap.aaisimulator.utils.Constants.LINES_OF_BUSINESS_URL; +import static org.onap.aaisimulator.utils.Constants.LINE_OF_BUSINESS; +import static org.onap.aaisimulator.utils.RequestErrorResponseUtils.getRequestErrorResponseEntity; +import static org.onap.aaisimulator.utils.RequestErrorResponseUtils.getResourceVersion; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.MediaType; +import org.onap.aai.domain.yang.LineOfBusiness; +import org.onap.aai.domain.yang.Relationship; +import org.onap.aaisimulator.models.Format; +import org.onap.aaisimulator.models.Results; +import org.onap.aaisimulator.service.providers.LinesOfBusinessCacheServiceProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +@Controller +@RequestMapping(path = LINES_OF_BUSINESS_URL) +public class LinesOfBusinessController { + private static final Logger LOGGER = LoggerFactory.getLogger(LinesOfBusinessController.class); + + private final LinesOfBusinessCacheServiceProvider cacheServiceProvider; + + @Autowired + public LinesOfBusinessController(final LinesOfBusinessCacheServiceProvider cacheServiceProvider) { + this.cacheServiceProvider = cacheServiceProvider; + } + + @PutMapping(value = "{line-of-business-name}", consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}, + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> putLineOfBusiness(@RequestBody final LineOfBusiness lineOfBusiness, + @PathVariable("line-of-business-name") final String lineOfBusinessName, final HttpServletRequest request) { + + LOGGER.info("Will add LineOfBusiness to cache with key 'line-of-business-name': {} ...", + lineOfBusiness.getLineOfBusinessName()); + + if (lineOfBusiness.getResourceVersion() == null || lineOfBusiness.getResourceVersion().isEmpty()) { + lineOfBusiness.setResourceVersion(getResourceVersion()); + + } + cacheServiceProvider.putLineOfBusiness(lineOfBusinessName, lineOfBusiness); + return ResponseEntity.accepted().build(); + } + + + @GetMapping(value = "{line-of-business-name}", produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> getLineOfBusiness(@PathVariable("line-of-business-name") final String lineOfBusinessName, + @RequestParam(name = "depth", required = false) final Integer depth, + @RequestParam(name = "resultIndex", required = false) final Integer resultIndex, + @RequestParam(name = "resultSize", required = false) final Integer resultSize, + @RequestParam(name = "format", required = false) final String format, final HttpServletRequest request) { + + LOGGER.info( + "retrieving Platform for 'platform-name': {} with depth: {}, resultIndex: {}, resultSize:{}, format: {} ...", + lineOfBusinessName, depth, resultIndex, resultSize, format); + + final Optional<LineOfBusiness> optional = cacheServiceProvider.getLineOfBusiness(lineOfBusinessName); + if (optional.isPresent()) { + + final Format value = Format.forValue(format); + switch (value) { + case RAW: + final LineOfBusiness platform = optional.get(); + LOGGER.info("found LineOfBusiness {} in cache", platform); + return ResponseEntity.ok(platform); + case COUNT: + final Map<String, Object> map = new HashMap<>(); + map.put(LINE_OF_BUSINESS, 1); + return ResponseEntity.ok(new Results(map)); + default: + break; + } + LOGGER.error("invalid format type :{}", format); + } + LOGGER.error("Unable to find LineOfBusiness in cache using {}", lineOfBusinessName); + return getRequestErrorResponseEntity(request, LINE_OF_BUSINESS); + } + + @PutMapping(value = "/{line-of-business-name}" + BI_DIRECTIONAL_RELATIONSHIP_LIST_URL, + consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}, + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> putRelationShip(@PathVariable("line-of-business-name") final String lineOfBusinessName, + @RequestBody final Relationship relationship, final HttpServletRequest request) { + LOGGER.info("Will add {} relationship to : {} ...", relationship.getRelatedTo()); + + final Optional<Relationship> optional = + cacheServiceProvider.addRelationShip(lineOfBusinessName, relationship, request.getRequestURI()); + + if (optional.isPresent()) { + final Relationship resultantRelationship = optional.get(); + LOGGER.info("Relationship add, sending resultant relationship: {} in response ...", resultantRelationship); + return ResponseEntity.accepted().body(resultantRelationship); + } + + LOGGER.error("Couldn't add {} relationship for 'line-of-business-name': {} ...", relationship.getRelatedTo(), + lineOfBusinessName); + + return getRequestErrorResponseEntity(request, LINE_OF_BUSINESS); + + } + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/NodesController.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/NodesController.java new file mode 100755 index 000000000..101f372c3 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/NodesController.java @@ -0,0 +1,115 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.controller; + +import static org.onap.aaisimulator.utils.Constants.GENERIC_VNF; +import static org.onap.aaisimulator.utils.Constants.NODES_URL; +import static org.onap.aaisimulator.utils.Constants.RESOURCE_LINK; +import static org.onap.aaisimulator.utils.Constants.RESOURCE_TYPE; +import static org.onap.aaisimulator.utils.RequestErrorResponseUtils.getRequestErrorResponseEntity; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.MediaType; +import org.onap.aai.domain.yang.GenericVnfs; +import org.onap.aai.domain.yang.ServiceInstance; +import org.onap.aaisimulator.models.Format; +import org.onap.aaisimulator.models.NodeServiceInstance; +import org.onap.aaisimulator.models.Results; +import org.onap.aaisimulator.service.providers.NodesCacheServiceProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; + +/** + * @author waqas.ikram@ericsson.com + * + */ +@Controller +@RequestMapping(path = NODES_URL) +public class NodesController { + + + private static final Logger LOGGER = LoggerFactory.getLogger(NodesController.class); + + private final NodesCacheServiceProvider cacheServiceProvider; + + @Autowired + public NodesController(final NodesCacheServiceProvider cacheServiceProvider) { + this.cacheServiceProvider = cacheServiceProvider; + } + + @GetMapping(value = "/service-instances/service-instance/{service-instance-id}", + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> getProject(@PathVariable(name = "service-instance-id") final String serviceInstanceId, + @RequestParam(name = "format", required = false) final String format, final HttpServletRequest request) { + LOGGER.info("retrieving service instance using 'service-instance-id': {} and format: {}...", serviceInstanceId, + format); + + final Optional<NodeServiceInstance> optional = cacheServiceProvider.getNodeServiceInstance(serviceInstanceId); + if (!optional.isPresent()) { + LOGGER.error("Couldn't find {} in cache", serviceInstanceId); + return getRequestErrorResponseEntity(request); + } + + final Format value = Format.forValue(format); + final NodeServiceInstance nodeServiceInstance = optional.get(); + switch (value) { + case PATHED: + LOGGER.info("found project {} in cache", nodeServiceInstance); + final Map<String, Object> map = new LinkedHashMap<>(); + map.put(RESOURCE_TYPE, nodeServiceInstance.getResourceType()); + map.put(RESOURCE_LINK, nodeServiceInstance.getResourceLink()); + return ResponseEntity.ok(new Results(map)); + case RAW: + final Optional<ServiceInstance> serviceInstance = + cacheServiceProvider.getServiceInstance(nodeServiceInstance); + if (serviceInstance.isPresent()) { + return ResponseEntity.ok(serviceInstance.get()); + } + LOGGER.error("Unable to find Service instance in cahce using {}", nodeServiceInstance); + return getRequestErrorResponseEntity(request); + default: + break; + } + LOGGER.error("invalid format type :{}", format); + return getRequestErrorResponseEntity(request); + } + + @GetMapping(value = "/generic-vnfs", produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> getGenericVnfs(@RequestParam(name = "vnf-name") final String vnfName, + final HttpServletRequest request) { + LOGGER.info("will find GenericVnfs for name: {}", vnfName); + final Optional<GenericVnfs> optional = cacheServiceProvider.getGenericVnfs(vnfName); + if (optional.isPresent()) { + LOGGER.info("found matching GenericVnfs for name: {}", vnfName); + return ResponseEntity.ok(optional.get()); + } + LOGGER.error("Unable to find GenericVnfs in cahce using {}", vnfName); + return getRequestErrorResponseEntity(request, GENERIC_VNF); + } +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/OwningEntityController.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/OwningEntityController.java new file mode 100755 index 000000000..0a08d648c --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/OwningEntityController.java @@ -0,0 +1,137 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.controller; + +import static org.onap.aaisimulator.utils.Constants.OWNING_ENTITY; +import static org.onap.aaisimulator.utils.Constants.OWNING_ENTITY_URL; +import static org.onap.aaisimulator.utils.HttpServiceUtils.getHeaders; +import static org.onap.aaisimulator.utils.RequestErrorResponseUtils.getRequestErrorResponseEntity; +import static org.onap.aaisimulator.utils.RequestErrorResponseUtils.getResourceVersion; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.MediaType; +import org.onap.aai.domain.yang.OwningEntity; +import org.onap.aai.domain.yang.Relationship; +import org.onap.aaisimulator.models.Format; +import org.onap.aaisimulator.models.Results; +import org.onap.aaisimulator.service.providers.OwnEntityCacheServiceProvider; +import org.onap.aaisimulator.utils.HttpServiceUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; + +/** + * @author waqas.ikram@ericsson.com + * + */ +@Controller +@RequestMapping(path = OWNING_ENTITY_URL) +public class OwningEntityController { + + private static final Logger LOGGER = LoggerFactory.getLogger(OwningEntityController.class); + + private final OwnEntityCacheServiceProvider cacheServiceProvider; + + @Autowired + public OwningEntityController(final OwnEntityCacheServiceProvider cacheServiceProvider) { + this.cacheServiceProvider = cacheServiceProvider; + } + + @PutMapping(value = "{owning-entity-id}", consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}, + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> putOwningEntity(@RequestBody final OwningEntity owningEntity, + @PathVariable("owning-entity-id") final String owningEntityId, final HttpServletRequest request) { + LOGGER.info("Will add OwningEntity to cache with key 'owning-entity-id': {} ...", + owningEntity.getOwningEntityId()); + + if (owningEntity.getResourceVersion() == null || owningEntity.getResourceVersion().isEmpty()) { + owningEntity.setResourceVersion(getResourceVersion()); + + } + cacheServiceProvider.putOwningEntity(owningEntityId, owningEntity); + return ResponseEntity.accepted().build(); + } + + @GetMapping(value = "{owning-entity-id}", produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> getOwningEntity(@PathVariable("owning-entity-id") final String owningEntityId, + @RequestParam(name = "resultIndex", required = false) final Integer resultIndex, + @RequestParam(name = "resultSize", required = false) final Integer resultSize, + @RequestParam(name = "format", required = false) final String format, final HttpServletRequest request) { + LOGGER.info("retrieving owning entity for 'owning-entity-id': {} ...", owningEntityId); + + final Optional<OwningEntity> optional = cacheServiceProvider.getOwningEntity(owningEntityId); + if (!optional.isPresent()) { + LOGGER.error("Couldn't find {} in cache", owningEntityId); + return getRequestErrorResponseEntity(request); + } + + final Format value = Format.forValue(format); + switch (value) { + case RAW: + final OwningEntity owningEntity = optional.get(); + LOGGER.info("found OwningEntity {} in cache", owningEntity); + return ResponseEntity.ok(owningEntity); + case COUNT: + final Map<String, Object> map = new HashMap<>(); + map.put(OWNING_ENTITY, 1); + return ResponseEntity.ok(new Results(map)); + default: + break; + } + LOGGER.error("invalid format type :{}", format); + return getRequestErrorResponseEntity(request); + } + + @PutMapping(value = "/{owning-entity-id}/relationship-list/relationship", + consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}, + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> putOwningEntityRelationShip(@RequestBody final Relationship relationship, + @PathVariable("owning-entity-id") final String owningEntityId, final HttpServletRequest request) { + + LOGGER.info("adding relationship for owning-entity-id: {} ...", owningEntityId); + + if (relationship.getRelatedLink() != null) { + final String targetBaseUrl = HttpServiceUtils.getBaseUrl(request).toString(); + final HttpHeaders incomingHeader = getHeaders(request); + + final boolean result = cacheServiceProvider.addRelationShip(incomingHeader, targetBaseUrl, + request.getRequestURI(), owningEntityId, relationship); + if (result) { + LOGGER.info("added created bi directional relationship with {}", relationship.getRelatedLink()); + return ResponseEntity.accepted().build(); + } + } + + LOGGER.error("Unable to add relationship for related link: {}", relationship.getRelatedLink()); + return getRequestErrorResponseEntity(request); + } + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/PlatformController.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/PlatformController.java new file mode 100755 index 000000000..5eef96077 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/PlatformController.java @@ -0,0 +1,134 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.controller; + +import static org.onap.aaisimulator.utils.Constants.BI_DIRECTIONAL_RELATIONSHIP_LIST_URL; +import static org.onap.aaisimulator.utils.Constants.PLATFORM; +import static org.onap.aaisimulator.utils.Constants.PLATFORMS_URL; +import static org.onap.aaisimulator.utils.RequestErrorResponseUtils.getRequestErrorResponseEntity; +import static org.onap.aaisimulator.utils.RequestErrorResponseUtils.getResourceVersion; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.MediaType; +import org.onap.aai.domain.yang.Platform; +import org.onap.aai.domain.yang.Relationship; +import org.onap.aaisimulator.models.Format; +import org.onap.aaisimulator.models.Results; +import org.onap.aaisimulator.service.providers.PlatformCacheServiceProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +@Controller +@RequestMapping(path = PLATFORMS_URL) +public class PlatformController { + private static final Logger LOGGER = LoggerFactory.getLogger(PlatformController.class); + + private final PlatformCacheServiceProvider cacheServiceProvider; + + @Autowired + public PlatformController(final PlatformCacheServiceProvider cacheServiceProvider) { + this.cacheServiceProvider = cacheServiceProvider; + } + + @PutMapping(value = "{platform-name}", consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}, + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> putPlatform(@RequestBody final Platform platform, + @PathVariable("platform-name") final String platformName, final HttpServletRequest request) { + LOGGER.info("Will add Platform to cache with key 'platform-name': {} ...", platform.getPlatformName()); + + if (platform.getResourceVersion() == null || platform.getResourceVersion().isEmpty()) { + platform.setResourceVersion(getResourceVersion()); + + } + cacheServiceProvider.putPlatform(platformName, platform); + return ResponseEntity.accepted().build(); + } + + @GetMapping(value = "/{platform-name}", produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> getPlatform(@PathVariable("platform-name") final String platformName, + @RequestParam(name = "depth", required = false) final Integer depth, + @RequestParam(name = "resultIndex", required = false) final Integer resultIndex, + @RequestParam(name = "resultSize", required = false) final Integer resultSize, + @RequestParam(name = "format", required = false) final String format, final HttpServletRequest request) { + + LOGGER.info( + "retrieving Platform for 'platform-name': {} with depth: {}, resultIndex: {}, resultSize:{}, format: {} ...", + platformName, depth, resultIndex, resultSize, format); + final Optional<Platform> optional = cacheServiceProvider.getPlatform(platformName); + if (optional.isPresent()) { + + final Format value = Format.forValue(format); + switch (value) { + case RAW: + final Platform platform = optional.get(); + LOGGER.info("found Platform {} in cache", platform); + return ResponseEntity.ok(platform); + case COUNT: + final Map<String, Object> map = new HashMap<>(); + map.put(PLATFORM, 1); + return ResponseEntity.ok(new Results(map)); + default: + break; + } + LOGGER.error("invalid format type :{}", format); + + } + LOGGER.error("Unable to find Platform in cahce using {}", platformName); + return getRequestErrorResponseEntity(request, PLATFORM); + } + + @PutMapping(value = "/{platform-name}" + BI_DIRECTIONAL_RELATIONSHIP_LIST_URL, + consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}, + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> putRelationShip(@PathVariable("platform-name") final String platformName, + @RequestBody final Relationship relationship, final HttpServletRequest request) { + LOGGER.info("Will add {} relationship to : {} ...", relationship.getRelatedTo()); + + final Optional<Relationship> optional = + cacheServiceProvider.addRelationShip(platformName, relationship, request.getRequestURI()); + + if (optional.isPresent()) { + final Relationship resultantRelationship = optional.get(); + LOGGER.info("Relationship add, sending resultant relationship: {} in response ...", resultantRelationship); + return ResponseEntity.accepted().body(resultantRelationship); + } + + LOGGER.error("Couldn't add {} relationship for 'platform-name': {} ...", relationship.getRelatedTo(), + platformName); + + return getRequestErrorResponseEntity(request, PLATFORM); + + } +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/PnfsController.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/PnfsController.java new file mode 100755 index 000000000..6311af6e2 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/PnfsController.java @@ -0,0 +1,159 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.controller; + + +import org.onap.aai.domain.yang.v15.Pnf; +import org.onap.aai.domain.yang.v15.Pnfs; +import org.onap.aaisimulator.service.providers.PnfCacheServiceProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.MediaType; +import java.util.List; +import java.util.Optional; + +import static org.onap.aaisimulator.utils.Constants.APPLICATION_MERGE_PATCH_JSON; +import static org.onap.aaisimulator.utils.Constants.PNF; +import static org.onap.aaisimulator.utils.Constants.PNFS_URL; +import static org.onap.aaisimulator.utils.Constants.X_HTTP_METHOD_OVERRIDE; +import static org.onap.aaisimulator.utils.RequestErrorResponseUtils.getRequestErrorResponseEntity; +import static org.onap.aaisimulator.utils.RequestErrorResponseUtils.getResourceVersion; + +/** + * @author Raj Gumma (raj.gumma@est.tech) + */ +@Controller +@RequestMapping(path = PNFS_URL) +public class PnfsController { + + private static final Logger LOGGER = LoggerFactory.getLogger(PnfsController.class); + + private final PnfCacheServiceProvider cacheServiceProvider; + + + @Autowired + public PnfsController(final PnfCacheServiceProvider cacheServiceProvider) { + this.cacheServiceProvider = cacheServiceProvider; + } + + @PutMapping(value = "/pnf/{pnf-id}", consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}, + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> putPnf(@RequestBody final Pnf pnf, + @PathVariable("pnf-id") final String pnfId, final HttpServletRequest request) { + LOGGER.info("Will add Pnf to cache with 'pnf-id': {} ...", pnfId); + + if (pnf.getResourceVersion() == null || pnf.getResourceVersion().isEmpty()) { + pnf.setResourceVersion(getResourceVersion()); + } + cacheServiceProvider.putPnf(pnfId, pnf); + return ResponseEntity.accepted().build(); + } + + @GetMapping(value = "/pnf/{pnf-id}", produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> getPnf(@PathVariable("pnf-id") final String pnfId, final HttpServletRequest request) { + LOGGER.info("Will get Pnf for 'pnf-id': {} ", pnfId); + + final Optional<Pnf> optional = cacheServiceProvider.getPnf(pnfId); + + if (optional.isPresent()) { + final Pnf pnf = optional.get(); + LOGGER.info("found Pnf {} in cache", pnf); + return ResponseEntity.ok(pnf); + } + + LOGGER.error("Unable to find Pnf in cache for 'pnf-id': {}", pnfId); + return getRequestErrorResponseEntity(request, "pnf"); + + } + + @PostMapping(value = "/pnf/{pnf-id}", + consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, APPLICATION_MERGE_PATCH_JSON}, + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> patchPnf(@RequestBody final Pnf pnf, + @PathVariable("pnf-id") final String pnfId, + @RequestHeader(value = X_HTTP_METHOD_OVERRIDE, required = false) final String xHttpHeaderOverride, + final HttpServletRequest request) { + + LOGGER.info("Will post Pnf to cache with 'pnf-id': {} and '{}': {} ...", pnfId, X_HTTP_METHOD_OVERRIDE, + xHttpHeaderOverride); + + if (HttpMethod.PATCH.toString().equalsIgnoreCase(xHttpHeaderOverride)) { + if (cacheServiceProvider.patchPnf(pnfId, pnf)) { + return ResponseEntity.accepted().build(); + } + LOGGER.error("Unable to apply patch to Pnf using 'pnf-id': {} ... ", pnfId); + return getRequestErrorResponseEntity(request, PNF); + } + LOGGER.error("{} not supported ... ", xHttpHeaderOverride); + + return getRequestErrorResponseEntity(request, PNF); + } + + @GetMapping(produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> getPnfs(@RequestParam(name = "selflink") final String selflink, + final HttpServletRequest request) { + LOGGER.info("will retrieve Pnfs using selflink: {}", selflink); + + final List<Pnf> pnfList = cacheServiceProvider.getPnfs(selflink); + + if (pnfList.isEmpty()) { + LOGGER.error("No matching pnfs found using selflink: {}", selflink); + return getRequestErrorResponseEntity(request, PNF); + } + + LOGGER.info("found {} Pnfs in cache", pnfList.size()); + final Pnfs pnfs = new Pnfs(); + pnfs.getPnf().addAll(pnfList); + return ResponseEntity.ok(pnfs); + } + + @DeleteMapping(value = "/pnf/{pnf-id}", produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> deletePnf(@PathVariable("pnf-id") final String pnfId, + @RequestParam(name = "resource-version") final String resourceVersion, final HttpServletRequest request) { + LOGGER.info("Will delete Pnf for 'pnf-id': {} and 'resource-version': {}", pnfId, resourceVersion); + + if (cacheServiceProvider.deletePnf(pnfId, resourceVersion)) { + LOGGER.info("Successfully delete Pnf from cache for 'pnf-id': {} and 'resource-version': {}", pnfId, + resourceVersion); + return ResponseEntity.noContent().build(); + } + + LOGGER.error("Unable to delete Pnf for 'pnf-id': {} and 'resource-version': {} ...", pnfId, + resourceVersion); + return getRequestErrorResponseEntity(request, PNF); + + } + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/ProjectController.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/ProjectController.java new file mode 100755 index 000000000..c901aa819 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/ProjectController.java @@ -0,0 +1,137 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.controller; + +import static org.onap.aaisimulator.utils.Constants.PROJECT; +import static org.onap.aaisimulator.utils.Constants.PROJECT_URL; +import static org.onap.aaisimulator.utils.Constants.RELATIONSHIP_LIST_RELATIONSHIP_URL; +import static org.onap.aaisimulator.utils.HttpServiceUtils.getHeaders; +import static org.onap.aaisimulator.utils.RequestErrorResponseUtils.getRequestErrorResponseEntity; +import static org.onap.aaisimulator.utils.RequestErrorResponseUtils.getResourceVersion; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.MediaType; +import org.onap.aai.domain.yang.Project; +import org.onap.aai.domain.yang.Relationship; +import org.onap.aaisimulator.models.Format; +import org.onap.aaisimulator.models.Results; +import org.onap.aaisimulator.service.providers.ProjectCacheServiceProvider; +import org.onap.aaisimulator.utils.HttpServiceUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; + +/** + * @author waqas.ikram@ericsson.com + * + */ +@Controller +@RequestMapping(path = PROJECT_URL) +public class ProjectController { + private static final Logger LOGGER = LoggerFactory.getLogger(ProjectController.class); + + private final ProjectCacheServiceProvider cacheServiceProvider; + + @Autowired + public ProjectController(final ProjectCacheServiceProvider cacheServiceProvider) { + this.cacheServiceProvider = cacheServiceProvider; + } + + @PutMapping(value = "/{project-name}", consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}, + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> putProject(@RequestBody final Project project, + @PathVariable("project-name") final String projectName, final HttpServletRequest request) { + LOGGER.info("Will put project for 'project-name': {} ...", project.getProjectName()); + + if (project.getResourceVersion() == null || project.getResourceVersion().isEmpty()) { + project.setResourceVersion(getResourceVersion()); + + } + cacheServiceProvider.putProject(projectName, project); + return ResponseEntity.accepted().build(); + + } + + @GetMapping(value = "/{project-name}", produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> getProject(@PathVariable("project-name") final String projectName, + @RequestParam(name = "resultIndex", required = false) final Integer resultIndex, + @RequestParam(name = "resultSize", required = false) final Integer resultSize, + @RequestParam(name = "format", required = false) final String format, final HttpServletRequest request) { + LOGGER.info("retrieving project for 'project-name': {} ...", projectName); + + final Optional<Project> optional = cacheServiceProvider.getProject(projectName); + if (!optional.isPresent()) { + LOGGER.error("Couldn't find {} in cache", projectName); + return getRequestErrorResponseEntity(request); + } + + final Format value = Format.forValue(format); + switch (value) { + case RAW: + final Project project = optional.get(); + LOGGER.info("found project {} in cache", project); + return ResponseEntity.ok(project); + case COUNT: + final Map<String, Object> map = new HashMap<>(); + map.put(PROJECT, 1); + return ResponseEntity.ok(new Results(map)); + default: + break; + } + LOGGER.error("invalid format type :{}", format); + return getRequestErrorResponseEntity(request); + } + + @PutMapping(value = "/{project-name}" + RELATIONSHIP_LIST_RELATIONSHIP_URL, + consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}, + produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity<?> putProjectRelationShip(@RequestBody final Relationship relationship, + @PathVariable("project-name") final String projectName, final HttpServletRequest request) { + + LOGGER.info("adding relationship for project-name: {} ...", projectName); + + if (relationship.getRelatedLink() != null) { + final String targetBaseUrl = HttpServiceUtils.getBaseUrl(request).toString(); + final HttpHeaders incomingHeader = getHeaders(request); + + final boolean result = cacheServiceProvider.addRelationShip(incomingHeader, targetBaseUrl, + request.getRequestURI(), projectName, relationship); + if (result) { + LOGGER.info("added created bi directional relationship with {}", relationship.getRelatedLink()); + return ResponseEntity.accepted().build(); + } + } + + LOGGER.error("Unable to add relationship for related link: {}", relationship.getRelatedLink()); + return getRequestErrorResponseEntity(request); + } + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/ServiceDesignAndCreationController.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/ServiceDesignAndCreationController.java new file mode 100644 index 000000000..7f12341e7 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/controller/ServiceDesignAndCreationController.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.controller; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +import static org.onap.aaisimulator.utils.Constants.SERVICE_DESIGN_AND_CREATION_URL; + +/** + * @author Eliezio Oliveira (eliezio.oliveira@est.tech) + */ +@RestController +@RequestMapping(path = SERVICE_DESIGN_AND_CREATION_URL) +public class ServiceDesignAndCreationController { + + private static final Logger LOGGER = LoggerFactory.getLogger(ServiceDesignAndCreationController.class); + + @Value("${SERVICE_DESIGN_AND_CREATION_RESPONSES_LOCATION:./}") + private String responsesLocation; + + @GetMapping(path = "/models/model/{model-invariant-id}/model-vers", + produces = MediaType.APPLICATION_XML_VALUE) + public ResponseEntity<String> getModelVers(@PathVariable("model-invariant-id") String modelInvariantId) { + Path responsesPath = Paths.get(responsesLocation).toAbsolutePath(); + LOGGER.info("Will get ModelVer for 'model-invariant-id': {}, looking under {}", + modelInvariantId, responsesPath.toString()); + + Path responsePath = responsesPath.resolve(modelInvariantId + ".xml"); + if (!responsePath.toFile().exists()) { + LOGGER.error("{} not found", responsePath.toString()); + return ResponseEntity.notFound().build(); + } + try { + String content = new String(Files.readAllBytes(responsePath), StandardCharsets.UTF_8); + LOGGER.info("{} found with {} characters", responsePath.toString(), content.length()); + return ResponseEntity.ok().body(content); + } catch (IOException e) { + LOGGER.error("Failed to read response from {}: {}}", responsePath.toString(), e.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); + } + } +}
\ No newline at end of file diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/exception/InvalidRestRequestException.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/exception/InvalidRestRequestException.java new file mode 100755 index 000000000..f587b9b81 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/exception/InvalidRestRequestException.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.aaisimulator.exception; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +public class InvalidRestRequestException extends RuntimeException { + private static final long serialVersionUID = -1158414939006977465L; + + public InvalidRestRequestException(final String message) { + super(message); + } + + public InvalidRestRequestException(final String message, final Throwable cause) { + super(message, cause); + } +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/exception/RestProcessingException.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/exception/RestProcessingException.java new file mode 100755 index 000000000..11218c8d7 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/exception/RestProcessingException.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.exception; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +public class RestProcessingException extends RuntimeException { + + private static final long serialVersionUID = 16862313537198441L; + + public RestProcessingException(final String message) { + super(message); + } + + public RestProcessingException(final String message, final Throwable cause) { + super(message, cause); + } +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/models/CloudRegionKey.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/models/CloudRegionKey.java new file mode 100755 index 000000000..b557434ac --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/models/CloudRegionKey.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.models; + +import java.io.Serializable; +import org.springframework.util.ObjectUtils; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +public class CloudRegionKey implements Serializable { + + private static final long serialVersionUID = 6175094050996035737L; + + private final String cloudOwner; + + private final String cloudRegionId; + + public CloudRegionKey(final String cloudOwner, final String cloudRegionId) { + this.cloudOwner = cloudOwner; + this.cloudRegionId = cloudRegionId; + } + + /** + * @return the cloudOwner + */ + public String getCloudOwner() { + return cloudOwner; + } + + /** + * @return the cloudRegionId + */ + public String getCloudRegionId() { + return cloudRegionId; + } + + public boolean isValid() { + return cloudOwner != null && !cloudOwner.isEmpty() && cloudRegionId != null && !cloudRegionId.isEmpty(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (ObjectUtils.nullSafeHashCode(cloudOwner)); + result = prime * result + (ObjectUtils.nullSafeHashCode(cloudRegionId)); + + return result; + } + + @Override + public boolean equals(final Object obj) { + if (obj instanceof CloudRegionKey) { + final CloudRegionKey other = (CloudRegionKey) obj; + return ObjectUtils.nullSafeEquals(cloudOwner, other.cloudOwner) + && ObjectUtils.nullSafeEquals(cloudRegionId, other.cloudRegionId); + } + return false; + } + + @Override + public String toString() { + return "CloudRegionKey [cloudOwner=" + cloudOwner + ", cloudRegionId=" + cloudRegionId + "]"; + } + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/models/Format.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/models/Format.java new file mode 100755 index 000000000..174e4166b --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/models/Format.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.models; + +/** + * @author waqas.ikram@ericsson.com + * + */ +public enum Format { + + COUNT("count"), RAW("raw"), PATHED("pathed"); + + private final String value; + + private Format(final String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public static Format forValue(final String value) { + for (final Format format : Format.values()) { + if (format.getValue().equals(value)) { + return format; + } + } + return RAW; + } + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/models/NodeServiceInstance.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/models/NodeServiceInstance.java new file mode 100755 index 000000000..6b4762f9e --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/models/NodeServiceInstance.java @@ -0,0 +1,139 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.models; + +import java.io.Serializable; + +/** + * @author waqas.ikram@ericsson.com + * + */ +public class NodeServiceInstance implements Serializable { + + private static final long serialVersionUID = -3314166327618070948L; + + private String globalCustomerId; + private String serviceType; + private String serviceInstanceId; + private String resourceType; + private String resourceLink; + + public NodeServiceInstance() {} + + + public NodeServiceInstance(final String globalCustomerId, final String serviceType, final String serviceInstanceId, + final String resourceType, final String resourceLink) { + this.globalCustomerId = globalCustomerId; + this.serviceType = serviceType; + this.serviceInstanceId = serviceInstanceId; + this.resourceType = resourceType; + this.resourceLink = resourceLink; + } + + + /** + * @return the globalCustomerId + */ + public String getGlobalCustomerId() { + return globalCustomerId; + } + + + /** + * @param globalCustomerId the globalCustomerId to set + */ + public void setGlobalCustomerId(final String globalCustomerId) { + this.globalCustomerId = globalCustomerId; + } + + + /** + * @return the serviceType + */ + public String getServiceType() { + return serviceType; + } + + + /** + * @param serviceType the serviceType to set + */ + public void setServiceType(final String serviceType) { + this.serviceType = serviceType; + } + + + /** + * @return the serviceInstanceId + */ + public String getServiceInstanceId() { + return serviceInstanceId; + } + + + /** + * @param serviceInstanceId the serviceInstanceId to set + */ + public void setServiceInstanceId(final String serviceInstanceId) { + this.serviceInstanceId = serviceInstanceId; + } + + + /** + * @return the resourceType + */ + public String getResourceType() { + return resourceType; + } + + + /** + * @param resourceType the resourceType to set + */ + public void setResourceType(final String resourceType) { + this.resourceType = resourceType; + } + + + /** + * @return the resourceLink + */ + public String getResourceLink() { + return resourceLink; + } + + + /** + * @param resourceLink the resourceLink to set + */ + public void setResourceLink(final String resourceLink) { + this.resourceLink = resourceLink; + } + + + @Override + public String toString() { + return "NodeServiceInstance [globalCustomerId=" + globalCustomerId + ", serviceType=" + serviceType + + ", serviceInstanceId=" + serviceInstanceId + ", resourceType=" + resourceType + ", resourceLink=" + + resourceLink + "]"; + } + + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/models/Results.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/models/Results.java new file mode 100755 index 000000000..8954327fd --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/models/Results.java @@ -0,0 +1,67 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.models; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * @author waqas.ikram@ericsson.com + * + */ +public class Results implements Serializable { + + private static final long serialVersionUID = 3967660859271162759L; + + @JsonProperty("results") + private List<Map<String, Object>> values = new ArrayList<>(); + + public Results() {} + + public Results(final Map<String, Object> value) { + this.values.add(value); + } + + /** + * @return the values + */ + public List<Map<String, Object>> getValues() { + return values; + } + + /** + * @param values the values to set + */ + public void setValues(final List<Map<String, Object>> values) { + this.values = values; + } + + + @JsonIgnore + @Override + public String toString() { + return "Result [values=" + values + "]"; + } + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/Clearable.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/Clearable.java new file mode 100755 index 000000000..d20d41228 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/Clearable.java @@ -0,0 +1,28 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.service.providers; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +public interface Clearable { + void clearAll(); +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/CloudRegionCacheServiceProvider.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/CloudRegionCacheServiceProvider.java new file mode 100755 index 000000000..3f440ec3c --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/CloudRegionCacheServiceProvider.java @@ -0,0 +1,69 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.service.providers; + +import java.util.Optional; +import org.onap.aai.domain.yang.CloudRegion; +import org.onap.aai.domain.yang.EsrSystemInfo; +import org.onap.aai.domain.yang.EsrSystemInfoList; +import org.onap.aai.domain.yang.Relationship; +import org.onap.aai.domain.yang.Tenant; +import org.onap.aai.domain.yang.Vserver; +import org.onap.aaisimulator.models.CloudRegionKey; +import org.springframework.http.HttpHeaders; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +public interface CloudRegionCacheServiceProvider extends Clearable { + + void putCloudRegion(final CloudRegionKey cloudRegionKey, final CloudRegion cloudRegion); + + Optional<CloudRegion> getCloudRegion(final CloudRegionKey cloudRegionKey); + + Optional<Relationship> addRelationShip(final CloudRegionKey key, final Relationship relationship, + final String requestUri); + + boolean putTenant(final CloudRegionKey key, final String tenantId, Tenant tenant); + + Optional<Tenant> getTenant(final CloudRegionKey key, final String tenantId); + + boolean addRelationShip(final HttpHeaders incomingHeader, final String targetBaseUrl, final String requestURI, + final CloudRegionKey key, final String tenantId, final Relationship relationship); + + Optional<EsrSystemInfoList> getEsrSystemInfoList(final CloudRegionKey key); + + boolean putEsrSystemInfo(final CloudRegionKey key, final String esrSystemInfoId, final EsrSystemInfo esrSystemInfo); + + boolean putVserver(final CloudRegionKey key, final String tenantId, final String vServerId, Vserver vServer); + + Optional<Vserver> getVserver(final CloudRegionKey key, final String tenantId, final String vServerId); + + boolean deleteVserver(final CloudRegionKey key, final String tenantId, final String vServerId, + final String resourceVersion); + + Optional<Relationship> addvServerRelationShip(final CloudRegionKey key, final String tenantId, + final String vServerId, final Relationship relationship, final String requestUri); + + boolean addVServerRelationShip(final HttpHeaders incomingHeader, final String targetBaseUrl, final String requestURI, final CloudRegionKey key, + final String tenantId, final String vServerId, final Relationship relationship); + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/CloudRegionCacheServiceProviderImpl.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/CloudRegionCacheServiceProviderImpl.java new file mode 100755 index 000000000..a26c0eb50 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/CloudRegionCacheServiceProviderImpl.java @@ -0,0 +1,471 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.service.providers; + +import static org.onap.aaisimulator.utils.CacheName.CLOUD_REGION_CACHE; +import static org.onap.aaisimulator.utils.Constants.BELONGS_TO; +import static org.onap.aaisimulator.utils.Constants.CLOUD_REGION; +import static org.onap.aaisimulator.utils.Constants.CLOUD_REGION_CLOUD_OWNER; +import static org.onap.aaisimulator.utils.Constants.CLOUD_REGION_CLOUD_REGION_ID; +import static org.onap.aaisimulator.utils.Constants.CLOUD_REGION_OWNER_DEFINED_TYPE; +import static org.onap.aaisimulator.utils.Constants.HOSTED_ON; +import static org.onap.aaisimulator.utils.Constants.LOCATED_IN; +import static org.onap.aaisimulator.utils.Constants.TENANT; +import static org.onap.aaisimulator.utils.Constants.TENANT_TENANT_ID; +import static org.onap.aaisimulator.utils.Constants.TENANT_TENANT_NAME; +import static org.onap.aaisimulator.utils.Constants.VSERVER; +import static org.onap.aaisimulator.utils.Constants.VSERVER_VSERVER_ID; +import static org.onap.aaisimulator.utils.Constants.VSERVER_VSERVER_NAME; +import static org.onap.aaisimulator.utils.HttpServiceUtils.getBiDirectionalRelationShipListRelatedLink; +import static org.onap.aaisimulator.utils.HttpServiceUtils.getRelationShipListRelatedLink; +import static org.onap.aaisimulator.utils.HttpServiceUtils.getTargetUrl; +import java.util.List; +import java.util.Optional; +import org.onap.aai.domain.yang.CloudRegion; +import org.onap.aai.domain.yang.EsrSystemInfo; +import org.onap.aai.domain.yang.EsrSystemInfoList; +import org.onap.aai.domain.yang.RelatedToProperty; +import org.onap.aai.domain.yang.Relationship; +import org.onap.aai.domain.yang.RelationshipData; +import org.onap.aai.domain.yang.RelationshipList; +import org.onap.aai.domain.yang.Tenant; +import org.onap.aai.domain.yang.Tenants; +import org.onap.aai.domain.yang.Vserver; +import org.onap.aai.domain.yang.Vservers; +import org.onap.aaisimulator.models.CloudRegionKey; +import org.onap.aaisimulator.cache.provider.AbstractCacheServiceProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.http.HttpHeaders; +import org.springframework.stereotype.Service; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +@Service +public class CloudRegionCacheServiceProviderImpl extends AbstractCacheServiceProvider + implements CloudRegionCacheServiceProvider { + + + + private static final Logger LOGGER = LoggerFactory.getLogger(CloudRegionCacheServiceProviderImpl.class); + + private final HttpRestServiceProvider httpRestServiceProvider; + + @Autowired + public CloudRegionCacheServiceProviderImpl(final CacheManager cacheManager, + final HttpRestServiceProvider httpRestServiceProvider) { + super(cacheManager); + this.httpRestServiceProvider = httpRestServiceProvider; + } + + @Override + public void putCloudRegion(final CloudRegionKey cloudRegionKey, final CloudRegion cloudRegion) { + LOGGER.info("Adding CloudRegion to cache with key: {} ...", cloudRegionKey); + final Cache cache = getCache(CLOUD_REGION_CACHE.getName()); + cache.put(cloudRegionKey, cloudRegion); + + } + + @Override + public Optional<CloudRegion> getCloudRegion(final CloudRegionKey cloudRegionKey) { + LOGGER.info("getting CloudRegion from cache using key: {}", cloudRegionKey); + final Cache cache = getCache(CLOUD_REGION_CACHE.getName()); + final CloudRegion value = cache.get(cloudRegionKey, CloudRegion.class); + if (value != null) { + return Optional.of(value); + } + LOGGER.error("Unable to find CloudRegion in cache using key:{} ", cloudRegionKey); + return Optional.empty(); + } + + @Override + public Optional<Relationship> addRelationShip(final CloudRegionKey key, final Relationship relationship, + final String requestUri) { + final Optional<CloudRegion> optional = getCloudRegion(key); + if (optional.isPresent()) { + final CloudRegion cloudRegion = optional.get(); + RelationshipList relationshipList = cloudRegion.getRelationshipList(); + if (relationshipList == null) { + relationshipList = new RelationshipList(); + cloudRegion.setRelationshipList(relationshipList); + } + relationshipList.getRelationship().add(relationship); + + LOGGER.info("Successfully added relation to CloudRegion with key: {}", key); + + + final Relationship resultantRelationship = new Relationship(); + resultantRelationship.setRelatedTo(CLOUD_REGION); + resultantRelationship.setRelationshipLabel(LOCATED_IN); + resultantRelationship.setRelatedLink(getBiDirectionalRelationShipListRelatedLink(requestUri)); + + final List<RelationshipData> relationshipDataList = resultantRelationship.getRelationshipData(); + relationshipDataList.add(getRelationshipData(CLOUD_REGION_CLOUD_OWNER, cloudRegion.getCloudOwner())); + relationshipDataList.add(getRelationshipData(CLOUD_REGION_CLOUD_REGION_ID, cloudRegion.getCloudRegionId())); + + final List<RelatedToProperty> relatedToPropertyList = resultantRelationship.getRelatedToProperty(); + + final RelatedToProperty relatedToProperty = new RelatedToProperty(); + relatedToProperty.setPropertyKey(CLOUD_REGION_OWNER_DEFINED_TYPE); + relatedToProperty.setPropertyValue(cloudRegion.getOwnerDefinedType()); + relatedToPropertyList.add(relatedToProperty); + + return Optional.of(resultantRelationship); + + } + LOGGER.error("Unable to find CloudRegion using key: {} ...", key); + return Optional.empty(); + } + + @Override + public boolean putTenant(final CloudRegionKey key, final String tenantId, final Tenant tenant) { + final Optional<CloudRegion> optional = getCloudRegion(key); + if (optional.isPresent()) { + final CloudRegion cloudRegion = optional.get(); + Tenants tenants = cloudRegion.getTenants(); + if (tenants == null) { + tenants = new Tenants(); + cloudRegion.setTenants(tenants); + } + + final Optional<Tenant> existingTenantOptional = tenants.getTenant().stream() + .filter(existing -> existing.getTenantId() != null && existing.getTenantId().equals(tenantId)) + .findFirst(); + + if (!existingTenantOptional.isPresent()) { + return tenants.getTenant().add(tenant); + } + + LOGGER.warn("Tenant already exists ..."); + return false; + } + LOGGER.error("Unable to add Tenant using key: {} ...", key); + return false; + } + + @Override + public Optional<Tenant> getTenant(final CloudRegionKey key, final String tenantId) { + final Optional<CloudRegion> optional = getCloudRegion(key); + if (optional.isPresent()) { + final CloudRegion cloudRegion = optional.get(); + final Tenants tenants = cloudRegion.getTenants(); + if (tenants != null) { + return tenants.getTenant().stream().filter(existing -> existing.getTenantId().equals(tenantId)) + .findFirst(); + } + } + + LOGGER.error("Unable to find Tenant using key: {} and tenantId: {} ...", key, tenantId); + return Optional.empty(); + } + + @Override + public boolean addRelationShip(final HttpHeaders incomingHeader, final String targetBaseUrl, + final String requestUriString, final CloudRegionKey key, final String tenantId, + final Relationship relationship) { + try { + final Optional<Tenant> optional = getTenant(key, tenantId); + if (optional.isPresent()) { + final Tenant tenant = optional.get(); + final String targetUrl = getTargetUrl(targetBaseUrl, relationship.getRelatedLink()); + + final Relationship outGoingRelationShip = getRelationship(requestUriString, key, tenant); + final Optional<Relationship> optionalRelationship = httpRestServiceProvider.put(incomingHeader, + outGoingRelationShip, targetUrl, Relationship.class); + + if (optionalRelationship.isPresent()) { + final Relationship resultantRelationship = optionalRelationship.get(); + RelationshipList relationshipList = tenant.getRelationshipList(); + if (relationshipList == null) { + relationshipList = new RelationshipList(); + tenant.setRelationshipList(relationshipList); + } + + if (relationshipList.getRelationship().add(resultantRelationship)) { + LOGGER.info("added relationship {} in cache successfully", resultantRelationship); + return true; + } + } + + + } + } catch (final Exception exception) { + LOGGER.error("Unable to add two-way relationship for CloudRegion: {} and tenant: {}", key, tenantId, + exception); + } + LOGGER.error("Unable to add relationship in cache for CloudRegion: {} and tenant: {}", key, tenantId); + return false; + } + + @Override + public Optional<EsrSystemInfoList> getEsrSystemInfoList(final CloudRegionKey key) { + final Optional<CloudRegion> optional = getCloudRegion(key); + if (optional.isPresent()) { + final CloudRegion cloudRegion = optional.get(); + final EsrSystemInfoList esrSystemInfoList = cloudRegion.getEsrSystemInfoList(); + if (esrSystemInfoList != null) { + return Optional.of(esrSystemInfoList); + } + } + LOGGER.error("Unable to find EsrSystemInfoList in cache for CloudRegion: {} ", key); + + return Optional.empty(); + } + + @Override + public boolean putEsrSystemInfo(final CloudRegionKey key, final String esrSystemInfoId, + final EsrSystemInfo esrSystemInfo) { + final Optional<CloudRegion> optional = getCloudRegion(key); + if (optional.isPresent()) { + final CloudRegion cloudRegion = optional.get(); + final List<EsrSystemInfo> esrSystemInfoList = getEsrSystemInfoList(cloudRegion); + + final Optional<EsrSystemInfo> existingEsrSystemInfo = + esrSystemInfoList.stream().filter(existing -> existing.getEsrSystemInfoId() != null + && existing.getEsrSystemInfoId().equals(esrSystemInfoId)).findFirst(); + if (existingEsrSystemInfo.isPresent()) { + LOGGER.error("EsrSystemInfo already exists {}", existingEsrSystemInfo.get()); + return false; + } + + return esrSystemInfoList.add(esrSystemInfo); + + } + return false; + } + + @Override + public boolean putVserver(final CloudRegionKey key, final String tenantId, final String vServerId, + final Vserver vServer) { + final Optional<Tenant> optional = getTenant(key, tenantId); + if (optional.isPresent()) { + final Tenant tenant = optional.get(); + Vservers vServers = tenant.getVservers(); + if (vServers == null) { + vServers = new Vservers(); + tenant.setVservers(vServers); + } + final List<Vserver> vServerList = vServers.getVserver(); + + final Optional<Vserver> existingVserver = vServerList.stream() + .filter(existing -> existing.getVserverId() != null && existing.getVserverId().equals(vServerId)) + .findFirst(); + + if (existingVserver.isPresent()) { + LOGGER.error("Vserver already exists {}", existingVserver.get()); + return false; + } + return vServerList.add(vServer); + + } + return false; + } + + @Override + public Optional<Vserver> getVserver(final CloudRegionKey key, final String tenantId, final String vServerId) { + final Optional<Tenant> optional = getTenant(key, tenantId); + if (optional.isPresent()) { + final Tenant tenant = optional.get(); + final Vservers vServers = tenant.getVservers(); + if (vServers != null) { + return vServers.getVserver().stream() + .filter(vServer -> vServer.getVserverId() != null && vServer.getVserverId().equals(vServerId)) + .findFirst(); + } + } + LOGGER.error("Unable to find vServer in cache ... "); + return Optional.empty(); + } + + @Override + public boolean deleteVserver(final CloudRegionKey key, final String tenantId, final String vServerId, + final String resourceVersion) { + final Optional<Vserver> optional = getVserver(key, tenantId, vServerId); + if (optional.isPresent()) { + final Optional<Tenant> tenantOptional = getTenant(key, tenantId); + if (tenantOptional.isPresent()) { + final Tenant tenant = tenantOptional.get(); + final Vservers vServers = tenant.getVservers(); + if (vServers != null) { + return vServers.getVserver().removeIf(vServer -> { + if (vServer.getVserverId() != null && vServer.getVserverId().equals(vServerId) + && vServer.getResourceVersion() != null + && vServer.getResourceVersion().equals(resourceVersion)) { + LOGGER.info("Will remove Vserver from cache with vServerId: {} and resource-version: {} ", + vServerId, vServer.getResourceVersion()); + return true; + } + return false; + }); + } + + } + + } + LOGGER.error( + "Unable to find Vserver for using key: {}, tenant-id: {}, vserver-id: {} and resource-version: {} ...", + key, tenantId, vServerId, resourceVersion); + + return false; + } + + @Override + public Optional<Relationship> addvServerRelationShip(final CloudRegionKey key, final String tenantId, + final String vServerId, final Relationship relationship, final String requestUri) { + final Optional<Vserver> optional = getVserver(key, tenantId, vServerId); + if (optional.isPresent()) { + final Vserver vServer = optional.get(); + RelationshipList relationshipList = vServer.getRelationshipList(); + if (relationshipList == null) { + relationshipList = new RelationshipList(); + vServer.setRelationshipList(relationshipList); + } + relationshipList.getRelationship().add(relationship); + LOGGER.info("Successfully added relation to Vserver with key: {}, tenantId: {} and vServerId: {}", key, + tenantId, vServerId); + final String relatedLink = getBiDirectionalRelationShipListRelatedLink(requestUri); + + final Relationship resultantRelationship = getVserverRelationship(key, tenantId, vServer, relatedLink); + + return Optional.of(resultantRelationship); + } + + LOGGER.error("Unable to find Vserver using key: {}, tenantId: {} and vServerId: {}...", key, tenantId, + vServerId); + return Optional.empty(); + } + + private Relationship getVserverRelationship(final CloudRegionKey key, final String tenantId, final Vserver vServer, + final String relatedLink) { + final Relationship resultantRelationship = new Relationship(); + resultantRelationship.setRelatedTo(VSERVER); + resultantRelationship.setRelationshipLabel(HOSTED_ON); + resultantRelationship.setRelatedLink(relatedLink); + + final List<RelationshipData> relationshipDataList = resultantRelationship.getRelationshipData(); + relationshipDataList.add(getRelationshipData(CLOUD_REGION_CLOUD_OWNER, key.getCloudOwner())); + relationshipDataList.add(getRelationshipData(CLOUD_REGION_CLOUD_REGION_ID, key.getCloudRegionId())); + relationshipDataList.add(getRelationshipData(TENANT_TENANT_ID, tenantId)); + relationshipDataList.add(getRelationshipData(VSERVER_VSERVER_ID, vServer.getVserverId())); + + final List<RelatedToProperty> relatedToPropertyList = resultantRelationship.getRelatedToProperty(); + + final RelatedToProperty relatedToProperty = new RelatedToProperty(); + relatedToProperty.setPropertyKey(VSERVER_VSERVER_NAME); + relatedToProperty.setPropertyValue(vServer.getVserverName()); + relatedToPropertyList.add(relatedToProperty); + return resultantRelationship; + } + + @Override + public boolean addVServerRelationShip(final HttpHeaders incomingHeader, final String targetBaseUrl, + final String requestUriString, final CloudRegionKey key, final String tenantId, final String vServerId, + final Relationship relationship) { + try { + final Optional<Vserver> optional = getVserver(key, tenantId, vServerId); + if (optional.isPresent()) { + final Vserver vServer = optional.get(); + final String targetUrl = getTargetUrl(targetBaseUrl, relationship.getRelatedLink()); + final Relationship outGoingRelationShip = getVserverRelationship(key, tenantId, vServer, + getRelationShipListRelatedLink(requestUriString)); + final Optional<Relationship> optionalRelationship = httpRestServiceProvider.put(incomingHeader, + outGoingRelationShip, targetUrl, Relationship.class); + if (optionalRelationship.isPresent()) { + final Relationship resultantRelationship = optionalRelationship.get(); + + RelationshipList relationshipList = vServer.getRelationshipList(); + if (relationshipList == null) { + relationshipList = new RelationshipList(); + vServer.setRelationshipList(relationshipList); + } + + final Optional<Relationship> relationShipExists = relationshipList.getRelationship().stream() + .filter(relation -> relation.getRelatedTo().equals(resultantRelationship.getRelatedTo()) + && relation.getRelatedLink().equals(resultantRelationship.getRelatedLink())) + .findAny(); + + if (relationShipExists.isPresent()) { + LOGGER.info("relationship {} already exists in cache ", resultantRelationship); + return true; + } + + LOGGER.info("added relationship {} in cache successfully", resultantRelationship); + return relationshipList.getRelationship().add(resultantRelationship); + } + + } + } catch (final Exception exception) { + LOGGER.error("Unable to add two-way relationship for key: {}, tenantId: {} and vServerId: {}", key, + tenantId, vServerId, exception); + } + LOGGER.error("Unable to add Vserver relationship for key: {}, tenantId: {} and vServerId: {}...", key, tenantId, + vServerId); + return false; + } + + private List<EsrSystemInfo> getEsrSystemInfoList(final CloudRegion cloudRegion) { + EsrSystemInfoList esrSystemInfoList = cloudRegion.getEsrSystemInfoList(); + if (esrSystemInfoList == null) { + esrSystemInfoList = new EsrSystemInfoList(); + cloudRegion.setEsrSystemInfoList(esrSystemInfoList); + } + return esrSystemInfoList.getEsrSystemInfo(); + } + + private Relationship getRelationship(final String requestUriString, final CloudRegionKey cloudRegionKey, + final Tenant tenant) { + final Relationship relationShip = new Relationship(); + relationShip.setRelatedTo(TENANT); + relationShip.setRelationshipLabel(BELONGS_TO); + relationShip.setRelatedLink(getRelationShipListRelatedLink(requestUriString)); + + + final List<RelationshipData> relationshipDataList = relationShip.getRelationshipData(); + relationshipDataList.add(getRelationshipData(CLOUD_REGION_CLOUD_OWNER, cloudRegionKey.getCloudOwner())); + relationshipDataList.add(getRelationshipData(CLOUD_REGION_CLOUD_REGION_ID, cloudRegionKey.getCloudRegionId())); + relationshipDataList.add(getRelationshipData(TENANT_TENANT_ID, tenant.getTenantId())); + + + final RelatedToProperty relatedToProperty = new RelatedToProperty(); + relatedToProperty.setPropertyKey(TENANT_TENANT_NAME); + relatedToProperty.setPropertyValue(tenant.getTenantName()); + relationShip.getRelatedToProperty().add(relatedToProperty); + return relationShip; + } + + private RelationshipData getRelationshipData(final String key, final String value) { + final RelationshipData relationshipData = new RelationshipData(); + relationshipData.setRelationshipKey(key); + relationshipData.setRelationshipValue(value); + return relationshipData; + } + + @Override + public void clearAll() { + clearCache(CLOUD_REGION_CACHE.getName()); + + } + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/CustomerCacheServiceProvider.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/CustomerCacheServiceProvider.java new file mode 100755 index 000000000..ad225ff0b --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/CustomerCacheServiceProvider.java @@ -0,0 +1,65 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.service.providers; + +import java.util.Optional; +import org.onap.aai.domain.yang.Customer; +import org.onap.aai.domain.yang.Relationship; +import org.onap.aai.domain.yang.ServiceInstance; +import org.onap.aai.domain.yang.ServiceInstances; +import org.onap.aai.domain.yang.ServiceSubscription; + +/** + * @author waqas.ikram@ericsson.com + * + */ +public interface CustomerCacheServiceProvider extends Clearable { + + Optional<Customer> getCustomer(final String globalCustomerId); + + void putCustomer(final String globalCustomerId, final Customer customer); + + Optional<ServiceSubscription> getServiceSubscription(final String globalCustomerId, final String serviceType); + + boolean putServiceSubscription(final String globalCustomerId, final String serviceType, + final ServiceSubscription serviceSubscription); + + Optional<ServiceInstances> getServiceInstances(final String globalCustomerId, final String serviceType, + final String serviceInstanceName); + + Optional<ServiceInstance> getServiceInstance(final String globalCustomerId, final String serviceType, + final String serviceInstanceId); + + boolean putServiceInstance(final String globalCustomerId, final String serviceType, final String serviceInstanceId, + final ServiceInstance serviceInstance); + + boolean patchServiceInstance(final String globalCustomerId, final String serviceType, + final String serviceInstanceId, final ServiceInstance serviceInstance); + + Optional<Relationship> getRelationship(final String globalCustomerId, final String serviceType, + final String serviceInstanceId, final String vnfName); + + Optional<Relationship> addRelationShip(final String globalCustomerId, final String serviceType, + final String serviceInstanceId, final Relationship relationship, final String requestUri); + + boolean deleteSericeInstance(final String globalCustomerId, final String serviceType, + final String serviceInstanceId, final String resourceVersion); + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/CustomerCacheServiceProviderImpl.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/CustomerCacheServiceProviderImpl.java new file mode 100755 index 000000000..e755c44a5 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/CustomerCacheServiceProviderImpl.java @@ -0,0 +1,365 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.service.providers; + +import static org.onap.aaisimulator.utils.CacheName.CUSTOMER_CACHE; +import static org.onap.aaisimulator.utils.Constants.CUSTOMER_GLOBAL_CUSTOMER_ID; +import static org.onap.aaisimulator.utils.Constants.GENERIC_VNF; +import static org.onap.aaisimulator.utils.Constants.GENERIC_VNF_VNF_NAME; +import static org.onap.aaisimulator.utils.Constants.SERVICE_INSTANCE_SERVICE_INSTANCE_ID; +import static org.onap.aaisimulator.utils.Constants.SERVICE_INSTANCE_SERVICE_INSTANCE_NAME; +import static org.onap.aaisimulator.utils.Constants.SERVICE_SUBSCRIPTION_SERVICE_TYPE; +import static org.onap.aaisimulator.utils.HttpServiceUtils.getBiDirectionalRelationShipListRelatedLink; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import org.onap.aai.domain.yang.Customer; +import org.onap.aai.domain.yang.RelatedToProperty; +import org.onap.aai.domain.yang.Relationship; +import org.onap.aai.domain.yang.RelationshipData; +import org.onap.aai.domain.yang.RelationshipList; +import org.onap.aai.domain.yang.ServiceInstance; +import org.onap.aai.domain.yang.ServiceInstances; +import org.onap.aai.domain.yang.ServiceSubscription; +import org.onap.aai.domain.yang.ServiceSubscriptions; +import org.onap.aaisimulator.cache.provider.AbstractCacheServiceProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.stereotype.Service; + +/** + * @author waqas.ikram@ericsson.com + * + */ +@Service +public class CustomerCacheServiceProviderImpl extends AbstractCacheServiceProvider + implements CustomerCacheServiceProvider { + private static final Logger LOGGER = LoggerFactory.getLogger(CustomerCacheServiceProviderImpl.class); + + @Autowired + public CustomerCacheServiceProviderImpl(final CacheManager cacheManager) { + super(cacheManager); + } + + @Override + public Optional<Customer> getCustomer(final String globalCustomerId) { + LOGGER.info("getting customer from cache using key: {}", globalCustomerId); + final Cache cache = getCache(CUSTOMER_CACHE.getName()); + final Customer value = cache.get(globalCustomerId, Customer.class); + if (value != null) { + return Optional.of(value); + } + return Optional.empty(); + } + + @Override + public void putCustomer(final String globalCustomerId, final Customer customer) { + LOGGER.info("Adding customer: {} with key: {} in cache ...", customer, globalCustomerId); + final Cache cache = getCache(CUSTOMER_CACHE.getName()); + + cache.put(globalCustomerId, customer); + } + + @Override + public Optional<ServiceSubscription> getServiceSubscription(final String globalCustomerId, + final String serviceType) { + LOGGER.info("getting service subscription from cache for globalCustomerId: {} and serviceType: {}", + globalCustomerId, serviceType); + + final Cache cache = getCache(CUSTOMER_CACHE.getName()); + + final Customer value = cache.get(globalCustomerId, Customer.class); + + if (value != null) { + return Optional.ofNullable(value.getServiceSubscriptions().getServiceSubscription().stream() + .filter(s -> serviceType.equals(s.getServiceType())).findFirst().orElse(null)); + } + return Optional.empty(); + + } + + @Override + public Optional<ServiceInstances> getServiceInstances(final String globalCustomerId, final String serviceType, + final String serviceInstanceName) { + + final Cache cache = getCache(CUSTOMER_CACHE.getName()); + final Customer value = cache.get(globalCustomerId, Customer.class); + + if (value != null) { + final Optional<ServiceSubscription> serviceSubscription = value.getServiceSubscriptions() + .getServiceSubscription().stream().filter(s -> serviceType.equals(s.getServiceType())).findFirst(); + + if (serviceSubscription.isPresent()) { + LOGGER.info("Found service subscription ..."); + final ServiceInstances serviceInstances = serviceSubscription.get().getServiceInstances(); + if (serviceInstances != null) { + final List<ServiceInstance> serviceInstancesList = + serviceInstances.getServiceInstance().stream() + .filter(serviceInstance -> serviceInstanceName + .equals(serviceInstance.getServiceInstanceName())) + .collect(Collectors.toList()); + if (serviceInstancesList != null && !serviceInstancesList.isEmpty()) { + LOGGER.info("Found {} service instances ", serviceInstancesList.size()); + final ServiceInstances result = new ServiceInstances(); + result.getServiceInstance().addAll(serviceInstancesList); + return Optional.of(result); + + } + } + } + } + return Optional.empty(); + } + + @Override + public Optional<ServiceInstance> getServiceInstance(final String globalCustomerId, final String serviceType, + final String serviceInstanceId) { + final Cache cache = getCache(CUSTOMER_CACHE.getName()); + final Customer value = cache.get(globalCustomerId, Customer.class); + + if (value != null) { + final Optional<ServiceSubscription> serviceSubscription = value.getServiceSubscriptions() + .getServiceSubscription().stream().filter(s -> serviceType.equals(s.getServiceType())).findFirst(); + + if (serviceSubscription.isPresent()) { + LOGGER.info("Found service subscription ..."); + final ServiceInstances serviceInstances = serviceSubscription.get().getServiceInstances(); + if (serviceInstances != null) { + return Optional.ofNullable(serviceInstances.getServiceInstance().stream() + .filter(serviceInstance -> serviceInstanceId.equals(serviceInstance.getServiceInstanceId())) + .findFirst().orElse(null)); + } + + } + } + LOGGER.error( + "Unable to find ServiceInstance using globalCustomerId: {}, serviceType: {} and serviceInstanceId: {} ...", + globalCustomerId, serviceType, serviceInstanceId); + return Optional.empty(); + } + + @Override + public boolean putServiceInstance(final String globalCustomerId, final String serviceType, + final String serviceInstanceId, final ServiceInstance serviceInstance) { + LOGGER.info("Adding serviceInstance: {} in cache ...", serviceInstance, globalCustomerId); + + final Cache cache = getCache(CUSTOMER_CACHE.getName()); + final Customer value = cache.get(globalCustomerId, Customer.class); + + if (value != null) { + final Optional<ServiceSubscription> serviceSubscription = value.getServiceSubscriptions() + .getServiceSubscription().stream().filter(s -> serviceType.equals(s.getServiceType())).findFirst(); + + if (serviceSubscription.isPresent()) { + final ServiceInstances serviceInstances = getServiceInstances(serviceSubscription); + + + if (!serviceInstances.getServiceInstance().stream() + .filter(existing -> serviceInstanceId.equals(existing.getServiceInstanceId())).findFirst() + .isPresent()) { + return serviceInstances.getServiceInstance().add(serviceInstance); + } + LOGGER.error("Service {} already exists ....", serviceInstanceId); + return false; + } + LOGGER.error("Couldn't find service subscription with serviceType: {} in cache ", serviceType); + return false; + } + LOGGER.error("Couldn't find Customer with key: {} in cache ", globalCustomerId); + return false; + } + + @Override + public boolean putServiceSubscription(final String globalCustomerId, final String serviceType, + final ServiceSubscription serviceSubscription) { + + final Optional<Customer> customerOptional = getCustomer(globalCustomerId); + + if (customerOptional.isPresent()) { + final Customer customer = customerOptional.get(); + if (customer.getServiceSubscriptions() == null) { + final ServiceSubscriptions serviceSubscriptions = new ServiceSubscriptions(); + customer.setServiceSubscriptions(serviceSubscriptions); + return serviceSubscriptions.getServiceSubscription().add(serviceSubscription); + } + + final Optional<ServiceSubscription> serviceSubscriptionOptional = customer.getServiceSubscriptions() + .getServiceSubscription().stream().filter(s -> serviceType.equals(s.getServiceType())).findFirst(); + + if (!serviceSubscriptionOptional.isPresent()) { + return customer.getServiceSubscriptions().getServiceSubscription().add(serviceSubscription); + } + LOGGER.error("ServiceSubscription already exists {}", serviceSubscriptionOptional.get().getServiceType()); + return false; + } + LOGGER.error("Unable to add ServiceSubscription to cache becuase customer does not exits ..."); + return false; + } + + @Override + public boolean patchServiceInstance(final String globalCustomerId, final String serviceType, + final String serviceInstanceId, final ServiceInstance serviceInstance) { + final Optional<ServiceInstance> instance = getServiceInstance(globalCustomerId, serviceType, serviceInstanceId); + if (instance.isPresent()) { + final ServiceInstance cachedServiceInstance = instance.get(); + LOGGER.info("Changing OrchestrationStatus from {} to {} ", cachedServiceInstance.getOrchestrationStatus(), + serviceInstance.getOrchestrationStatus()); + cachedServiceInstance.setOrchestrationStatus(serviceInstance.getOrchestrationStatus()); + return true; + } + LOGGER.error("Unable to find ServiceInstance ..."); + return false; + } + + @Override + public boolean deleteSericeInstance(final String globalCustomerId, final String serviceType, + final String serviceInstanceId, final String resourceVersion) { + final Cache cache = getCache(CUSTOMER_CACHE.getName()); + final Customer value = cache.get(globalCustomerId, Customer.class); + + if (value != null) { + final Optional<ServiceSubscription> serviceSubscription = value.getServiceSubscriptions() + .getServiceSubscription().stream().filter(s -> serviceType.equals(s.getServiceType())).findFirst(); + + if (serviceSubscription.isPresent()) { + LOGGER.info("Found service subscription ..."); + final ServiceInstances serviceInstances = serviceSubscription.get().getServiceInstances(); + if (serviceInstances != null) { + + serviceInstances.getServiceInstance().removeIf(serviceInstance -> { + final String existingServiceInstanceId = serviceInstance.getServiceInstanceId(); + final String existingResourceVersion = serviceInstance.getResourceVersion(); + if (existingServiceInstanceId != null && existingServiceInstanceId.equals(serviceInstanceId) + && existingResourceVersion != null && existingResourceVersion.equals(resourceVersion)) { + LOGGER.info("Removing ServiceInstance with serviceInstanceId: {} and resourceVersion: {}", + existingServiceInstanceId, existingResourceVersion); + return true; + } + return false; + }); + + + return true; + } + + } + } + return false; + } + + private ServiceInstances getServiceInstances(final Optional<ServiceSubscription> optional) { + final ServiceSubscription serviceSubscription = optional.get(); + final ServiceInstances serviceInstances = serviceSubscription.getServiceInstances(); + if (serviceInstances == null) { + final ServiceInstances instances = new ServiceInstances(); + serviceSubscription.setServiceInstances(instances); + return instances; + } + return serviceInstances; + } + + @Override + public Optional<Relationship> getRelationship(final String globalCustomerId, final String serviceType, + final String serviceInstanceId, final String vnfName) { + final Optional<ServiceInstance> optional = getServiceInstance(globalCustomerId, serviceType, serviceInstanceId); + + if (optional.isPresent()) { + LOGGER.info("Found service instance ..."); + final ServiceInstance serviceInstance = optional.get(); + final RelationshipList relationshipList = serviceInstance.getRelationshipList(); + + if (relationshipList != null) { + final List<Relationship> relationship = relationshipList.getRelationship(); + return relationship.stream().filter( + relationShip -> relationShip.getRelatedToProperty().stream().filter(relatedToProperty -> { + final String propertyKey = relatedToProperty.getPropertyKey(); + final String propertyValue = relatedToProperty.getPropertyValue(); + return GENERIC_VNF_VNF_NAME.equals(propertyKey) && propertyValue != null + && propertyValue.equals(vnfName); + }).findFirst().isPresent()).findFirst(); + } + LOGGER.warn("Relationship list is nulll ..."); + } + LOGGER.error("Unable to RelationShip with property value: {}... ", vnfName); + + return Optional.empty(); + } + + @Override + public Optional<Relationship> addRelationShip(final String globalCustomerId, final String serviceType, + final String serviceInstanceId, final Relationship relationship, final String requestUri) { + final Optional<ServiceInstance> optional = getServiceInstance(globalCustomerId, serviceType, serviceInstanceId); + if (optional.isPresent()) { + final ServiceInstance serviceInstance = optional.get(); + RelationshipList relationshipList = serviceInstance.getRelationshipList(); + if (relationshipList == null) { + relationshipList = new RelationshipList(); + serviceInstance.setRelationshipList(relationshipList); + } + relationshipList.getRelationship().add(relationship); + + LOGGER.info("Successfully added relation to ServiceInstance"); + + final Relationship resultantRelationship = new Relationship(); + resultantRelationship.setRelatedTo(GENERIC_VNF); + resultantRelationship.setRelationshipLabel(relationship.getRelationshipLabel()); + resultantRelationship.setRelatedLink(getBiDirectionalRelationShipListRelatedLink(requestUri)); + + final List<RelationshipData> relationshipDataList = resultantRelationship.getRelationshipData(); + relationshipDataList.add(getRelationshipData(CUSTOMER_GLOBAL_CUSTOMER_ID, globalCustomerId)); + relationshipDataList.add(getRelationshipData(SERVICE_SUBSCRIPTION_SERVICE_TYPE, serviceType)); + relationshipDataList.add(getRelationshipData(SERVICE_INSTANCE_SERVICE_INSTANCE_ID, serviceInstanceId)); + + final List<RelatedToProperty> relatedToProperty = resultantRelationship.getRelatedToProperty(); + relatedToProperty.add(getRelatedToProperty(SERVICE_INSTANCE_SERVICE_INSTANCE_NAME, + serviceInstance.getServiceInstanceName())); + + return Optional.of(resultantRelationship); + + } + LOGGER.error("Unable to find ServiceInstance ..."); + return Optional.empty(); + } + + @Override + public void clearAll() { + clearCache(CUSTOMER_CACHE.getName()); + } + + private RelatedToProperty getRelatedToProperty(final String key, final String value) { + final RelatedToProperty relatedToProperty = new RelatedToProperty(); + relatedToProperty.setPropertyKey(key); + relatedToProperty.setPropertyValue(value); + return relatedToProperty; + } + + private RelationshipData getRelationshipData(final String key, final String value) { + final RelationshipData relationshipData = new RelationshipData(); + relationshipData.setRelationshipKey(key); + relationshipData.setRelationshipValue(value); + return relationshipData; + } + + + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/ExternalSystemCacheServiceProvider.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/ExternalSystemCacheServiceProvider.java new file mode 100755 index 000000000..108a8f287 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/ExternalSystemCacheServiceProvider.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.service.providers; + +import java.util.List; +import java.util.Optional; +import org.onap.aai.domain.yang.EsrSystemInfo; +import org.onap.aai.domain.yang.EsrSystemInfoList; +import org.onap.aai.domain.yang.EsrVnfm; +import org.onap.aai.domain.yang.Relationship; +import org.springframework.http.HttpHeaders; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +public interface ExternalSystemCacheServiceProvider extends Clearable { + + void putEsrVnfm(final String vnfmId, final EsrVnfm esrVnfm); + + Optional<EsrVnfm> getEsrVnfm(final String vnfmId); + + List<EsrVnfm> getAllEsrVnfm(); + + Optional<EsrSystemInfoList> getEsrSystemInfoList(final String vnfmId); + + boolean putEsrSystemInfo(final String vnfmId, final String esrSystemInfoId, final EsrSystemInfo esrSystemInfo); + + boolean addRelationShip(final HttpHeaders incomingHeader, final String targetBaseUrl, final String requestURI, + final String vnfmId, Relationship relationship); +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/ExternalSystemCacheServiceProviderImpl.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/ExternalSystemCacheServiceProviderImpl.java new file mode 100755 index 000000000..a274cc133 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/ExternalSystemCacheServiceProviderImpl.java @@ -0,0 +1,209 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.service.providers; + +import static org.onap.aaisimulator.utils.CacheName.ESR_VNFM_CACHE; +import static org.onap.aaisimulator.utils.Constants.DEPENDS_ON; +import static org.onap.aaisimulator.utils.Constants.ESR_VNFM; +import static org.onap.aaisimulator.utils.Constants.ESR_VNFM_VNFM_ID; +import static org.onap.aaisimulator.utils.HttpServiceUtils.getRelationShipListRelatedLink; +import static org.onap.aaisimulator.utils.HttpServiceUtils.getTargetUrl; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import org.onap.aai.domain.yang.EsrSystemInfo; +import org.onap.aai.domain.yang.EsrSystemInfoList; +import org.onap.aai.domain.yang.EsrVnfm; +import org.onap.aai.domain.yang.Relationship; +import org.onap.aai.domain.yang.RelationshipData; +import org.onap.aai.domain.yang.RelationshipList; +import org.onap.aaisimulator.cache.provider.AbstractCacheServiceProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.http.HttpHeaders; +import org.springframework.stereotype.Service; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +@Service +public class ExternalSystemCacheServiceProviderImpl extends AbstractCacheServiceProvider + implements ExternalSystemCacheServiceProvider { + + private static final Logger LOGGER = LoggerFactory.getLogger(ExternalSystemCacheServiceProviderImpl.class); + + private final HttpRestServiceProvider httpRestServiceProvider; + + @Autowired + public ExternalSystemCacheServiceProviderImpl(final CacheManager cacheManager, + final HttpRestServiceProvider httpRestServiceProvider) { + super(cacheManager); + this.httpRestServiceProvider = httpRestServiceProvider; + + } + + @Override + public void putEsrVnfm(final String vnfmId, final EsrVnfm esrVnfm) { + LOGGER.info("Adding esrVnfm: {} with name to cache", esrVnfm); + final Cache cache = getCache(ESR_VNFM_CACHE.getName()); + cache.put(vnfmId, esrVnfm); + } + + @Override + public Optional<EsrVnfm> getEsrVnfm(final String vnfmId) { + LOGGER.info("getting EsrVnfm from cache using key: {}", vnfmId); + final Cache cache = getCache(ESR_VNFM_CACHE.getName()); + final EsrVnfm value = cache.get(vnfmId, EsrVnfm.class); + if (value != null) { + return Optional.of(value); + } + LOGGER.error("Unable to find EsrVnfm in cache using vnfmId: {} ", vnfmId); + return Optional.empty(); + } + + @Override + public List<EsrVnfm> getAllEsrVnfm() { + final Cache cache = getCache(ESR_VNFM_CACHE.getName()); + if (cache != null) { + final Object nativeCache = cache.getNativeCache(); + if (nativeCache instanceof ConcurrentHashMap) { + @SuppressWarnings("unchecked") + final ConcurrentHashMap<Object, Object> concurrentHashMap = + (ConcurrentHashMap<Object, Object>) nativeCache; + final List<EsrVnfm> result = new ArrayList<>(); + concurrentHashMap.keySet().stream().forEach(key -> { + final Optional<EsrVnfm> optional = getEsrVnfm(key.toString()); + if (optional.isPresent()) { + result.add(optional.get()); + } + }); + return result; + } + } + LOGGER.error("Unable to get all esr vnfms ... "); + return Collections.emptyList(); + + } + + @Override + public Optional<EsrSystemInfoList> getEsrSystemInfoList(final String vnfmId) { + final Optional<EsrVnfm> optional = getEsrVnfm(vnfmId); + if (optional.isPresent()) { + final EsrVnfm esrVnfm = optional.get(); + if (esrVnfm.getEsrSystemInfoList() != null) { + return Optional.of(esrVnfm.getEsrSystemInfoList()); + } + LOGGER.error("EsrSystemInfoList is null for vnfmId: {} ", vnfmId); + } + LOGGER.error("Unable to find EsrVnfm in cache using vnfmId: {} ", vnfmId); + return Optional.empty(); + } + + @Override + public boolean putEsrSystemInfo(final String vnfmId, final String esrSystemInfoId, + final EsrSystemInfo esrSystemInfo) { + final Optional<EsrVnfm> optional = getEsrVnfm(vnfmId); + if (optional.isPresent()) { + final EsrVnfm esrVnfm = optional.get(); + final List<EsrSystemInfo> esrSystemInfoList = getEsrSystemInfoList(esrVnfm); + + final Optional<EsrSystemInfo> existingEsrSystemInfo = + esrSystemInfoList.stream().filter(existing -> existing.getEsrSystemInfoId() != null + && existing.getEsrSystemInfoId().equals(esrSystemInfoId)).findFirst(); + if (existingEsrSystemInfo.isPresent()) { + LOGGER.error("EsrSystemInfo already exists {}", existingEsrSystemInfo.get()); + return false; + } + + return esrSystemInfoList.add(esrSystemInfo); + } + LOGGER.error("Unable to add EsrSystemInfo in cache for vnfmId: {} ", vnfmId); + return false; + } + + @Override + public boolean addRelationShip(final HttpHeaders incomingHeader, final String targetBaseUrl, + final String requestUriString, final String vnfmId, final Relationship relationship) { + try { + final Optional<EsrVnfm> optional = getEsrVnfm(vnfmId); + if (optional.isPresent()) { + final EsrVnfm esrVnfm = optional.get(); + final String targetUrl = getTargetUrl(targetBaseUrl, relationship.getRelatedLink()); + final Relationship outGoingRelationShip = + getRelationship(getRelationShipListRelatedLink(requestUriString), esrVnfm); + final Optional<Relationship> optionalRelationship = httpRestServiceProvider.put(incomingHeader, + outGoingRelationShip, targetUrl, Relationship.class); + if (optionalRelationship.isPresent()) { + final Relationship resultantRelationship = optionalRelationship.get(); + + RelationshipList relationshipList = esrVnfm.getRelationshipList(); + if (relationshipList == null) { + relationshipList = new RelationshipList(); + esrVnfm.setRelationshipList(relationshipList); + } + if (relationshipList.getRelationship().add(resultantRelationship)) { + LOGGER.info("added relationship {} in cache successfully", resultantRelationship); + return true; + } + } + } + } catch (final Exception exception) { + LOGGER.error("Unable to add two-way relationship for vnfmId: {}", vnfmId, exception); + } + LOGGER.error("Unable to add relationship in cache for vnfmId: {}", vnfmId); + return false; + } + + private Relationship getRelationship(final String relatedLink, final EsrVnfm esrVnfm) { + final Relationship relationShip = new Relationship(); + relationShip.setRelatedTo(ESR_VNFM); + relationShip.setRelationshipLabel(DEPENDS_ON); + relationShip.setRelatedLink(relatedLink); + + final RelationshipData relationshipData = new RelationshipData(); + relationshipData.setRelationshipKey(ESR_VNFM_VNFM_ID); + relationshipData.setRelationshipValue(esrVnfm.getVnfmId()); + relationShip.getRelationshipData().add(relationshipData); + + return relationShip; + } + + private List<EsrSystemInfo> getEsrSystemInfoList(final EsrVnfm esrVnfm) { + EsrSystemInfoList esrSystemInfoList = esrVnfm.getEsrSystemInfoList(); + if (esrSystemInfoList == null) { + esrSystemInfoList = new EsrSystemInfoList(); + esrVnfm.setEsrSystemInfoList(esrSystemInfoList); + } + return esrSystemInfoList.getEsrSystemInfo(); + } + + @Override + public void clearAll() { + clearCache(ESR_VNFM_CACHE.getName()); + + } + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/GenericVnfCacheServiceProvider.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/GenericVnfCacheServiceProvider.java new file mode 100755 index 000000000..e2f05c699 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/GenericVnfCacheServiceProvider.java @@ -0,0 +1,53 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.service.providers; + +import java.util.List; +import java.util.Optional; +import org.onap.aai.domain.yang.GenericVnf; +import org.onap.aai.domain.yang.Relationship; +import org.springframework.http.HttpHeaders; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +public interface GenericVnfCacheServiceProvider extends Clearable { + + void putGenericVnf(final String vnfId, final GenericVnf genericVnf); + + Optional<GenericVnf> getGenericVnf(final String vnfId); + + Optional<Relationship> addRelationShip(final String vnfId, final Relationship relationship, + final String requestURI); + + boolean addRelationShip(final HttpHeaders incomingHeader, final String targetBaseUrl, final String requestUriString, + final String vnfId, final Relationship relationship); + + Optional<String> getGenericVnfId(final String vnfName); + + boolean patchGenericVnf(final String vnfId, final GenericVnf genericVnf); + + List<GenericVnf> getGenericVnfs(final String selflink); + + boolean deleteGenericVnf(final String vnfId, final String resourceVersion); + + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/GenericVnfCacheServiceProviderImpl.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/GenericVnfCacheServiceProviderImpl.java new file mode 100755 index 000000000..4fb6a0644 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/GenericVnfCacheServiceProviderImpl.java @@ -0,0 +1,258 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.service.providers; + +import static org.onap.aaisimulator.utils.CacheName.GENERIC_VNF_CACHE; +import static org.onap.aaisimulator.utils.Constants.COMPOSED_OF; +import static org.onap.aaisimulator.utils.Constants.GENERIC_VNF; +import static org.onap.aaisimulator.utils.Constants.GENERIC_VNF_VNF_ID; +import static org.onap.aaisimulator.utils.Constants.GENERIC_VNF_VNF_NAME; +import static org.onap.aaisimulator.utils.HttpServiceUtils.getBiDirectionalRelationShipListRelatedLink; +import static org.onap.aaisimulator.utils.HttpServiceUtils.getRelationShipListRelatedLink; +import static org.onap.aaisimulator.utils.HttpServiceUtils.getTargetUrl; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import org.onap.aai.domain.yang.GenericVnf; +import org.onap.aai.domain.yang.RelatedToProperty; +import org.onap.aai.domain.yang.Relationship; +import org.onap.aai.domain.yang.RelationshipData; +import org.onap.aai.domain.yang.RelationshipList; +import org.onap.aaisimulator.utils.ShallowBeanCopy; +import org.onap.aaisimulator.cache.provider.AbstractCacheServiceProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.http.HttpHeaders; +import org.springframework.stereotype.Service; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +@Service +public class GenericVnfCacheServiceProviderImpl extends AbstractCacheServiceProvider + implements GenericVnfCacheServiceProvider { + + private static final Logger LOGGER = LoggerFactory.getLogger(GenericVnfCacheServiceProviderImpl.class); + + private final HttpRestServiceProvider httpRestServiceProvider; + + @Autowired + public GenericVnfCacheServiceProviderImpl(final CacheManager cacheManager, + final HttpRestServiceProvider httpRestServiceProvider) { + super(cacheManager); + this.httpRestServiceProvider = httpRestServiceProvider; + } + + @Override + public void putGenericVnf(final String vnfId, final GenericVnf genericVnf) { + LOGGER.info("Adding customer: {} with key: {} in cache ...", genericVnf, vnfId); + final Cache cache = getCache(GENERIC_VNF_CACHE.getName()); + cache.put(vnfId, genericVnf); + } + + @Override + public Optional<GenericVnf> getGenericVnf(final String vnfId) { + LOGGER.info("getting GenericVnf from cache using key: {}", vnfId); + final Cache cache = getCache(GENERIC_VNF_CACHE.getName()); + final GenericVnf value = cache.get(vnfId, GenericVnf.class); + if (value != null) { + return Optional.of(value); + } + LOGGER.error("Unable to find GenericVnf ..."); + return Optional.empty(); + } + + @Override + public Optional<String> getGenericVnfId(final String vnfName) { + final Cache cache = getCache(GENERIC_VNF_CACHE.getName()); + if (cache != null) { + final Object nativeCache = cache.getNativeCache(); + if (nativeCache instanceof ConcurrentHashMap) { + @SuppressWarnings("unchecked") + final ConcurrentHashMap<Object, Object> concurrentHashMap = + (ConcurrentHashMap<Object, Object>) nativeCache; + for (final Object key : concurrentHashMap.keySet()) { + final Optional<GenericVnf> optional = getGenericVnf(key.toString()); + if (optional.isPresent()) { + final GenericVnf value = optional.get(); + final String genericVnfName = value.getVnfName(); + if (genericVnfName != null && genericVnfName.equals(vnfName)) { + final String genericVnfId = value.getVnfId(); + LOGGER.info("Found matching vnf for name: {}, vnf-id: {}", genericVnfName, genericVnfId); + return Optional.of(genericVnfId); + } + } + } + } + } + LOGGER.error("No match found for vnf name: {}", vnfName); + return Optional.empty(); + } + + @Override + public boolean addRelationShip(final HttpHeaders incomingHeader, final String targetBaseUrl, + final String requestUriString, final String vnfId, final Relationship relationship) { + try { + final Optional<GenericVnf> optional = getGenericVnf(vnfId); + if (optional.isPresent()) { + final GenericVnf genericVnf = optional.get(); + final String targetUrl = getTargetUrl(targetBaseUrl, relationship.getRelatedLink()); + final Relationship outGoingRelationShip = + getRelationship(getRelationShipListRelatedLink(requestUriString), genericVnf, COMPOSED_OF); + final Optional<Relationship> optionalRelationship = httpRestServiceProvider.put(incomingHeader, + outGoingRelationShip, targetUrl, Relationship.class); + if (optionalRelationship.isPresent()) { + final Relationship resultantRelationship = optionalRelationship.get(); + + RelationshipList relationshipList = genericVnf.getRelationshipList(); + if (relationshipList == null) { + relationshipList = new RelationshipList(); + genericVnf.setRelationshipList(relationshipList); + } + if (relationshipList.getRelationship().add(resultantRelationship)) { + LOGGER.info("added relationship {} in cache successfully", resultantRelationship); + return true; + } + } + } + } catch (final Exception exception) { + LOGGER.error("Unable to add two-way relationship for vnfId: {}", vnfId, exception); + } + LOGGER.error("Unable to add relationship in cache for vnfId: {}", vnfId); + return false; + } + + @Override + public Optional<Relationship> addRelationShip(final String vnfId, final Relationship relationship, + final String requestURI) { + final Optional<GenericVnf> optional = getGenericVnf(vnfId); + if (optional.isPresent()) { + final GenericVnf genericVnf = optional.get(); + RelationshipList relationshipList = genericVnf.getRelationshipList(); + if (relationshipList == null) { + relationshipList = new RelationshipList(); + genericVnf.setRelationshipList(relationshipList); + } + relationshipList.getRelationship().add(relationship); + LOGGER.info("Successfully added relation to GenericVnf for vnfId: {}", vnfId); + + final String relatedLink = getBiDirectionalRelationShipListRelatedLink(requestURI); + final Relationship resultantRelationship = + getRelationship(relatedLink, genericVnf, relationship.getRelationshipLabel()); + return Optional.of(resultantRelationship); + } + return Optional.empty(); + } + + @Override + public boolean patchGenericVnf(final String vnfId, final GenericVnf genericVnf) { + final Optional<GenericVnf> optional = getGenericVnf(vnfId); + if (optional.isPresent()) { + final GenericVnf cachedGenericVnf = optional.get(); + try { + ShallowBeanCopy.copy(genericVnf, cachedGenericVnf); + return true; + } catch (final Exception exception) { + LOGGER.error("Unable to update GenericVnf for vnfId: {}", vnfId, exception); + } + } + LOGGER.error("Unable to find GenericVnf ..."); + return false; + } + + @Override + public List<GenericVnf> getGenericVnfs(final String selflink) { + final Cache cache = getCache(GENERIC_VNF_CACHE.getName()); + if (cache != null) { + final Object nativeCache = cache.getNativeCache(); + if (nativeCache instanceof ConcurrentHashMap) { + @SuppressWarnings("unchecked") + final ConcurrentHashMap<Object, Object> concurrentHashMap = + (ConcurrentHashMap<Object, Object>) nativeCache; + final List<GenericVnf> result = new ArrayList<>(); + + concurrentHashMap.keySet().stream().forEach(key -> { + final Optional<GenericVnf> optional = getGenericVnf(key.toString()); + if (optional.isPresent()) { + final GenericVnf genericVnf = optional.get(); + final String genericVnfSelfLink = genericVnf.getSelflink(); + final String genericVnfId = genericVnf.getSelflink(); + + if (genericVnfSelfLink != null && genericVnfSelfLink.equals(selflink)) { + LOGGER.info("Found matching vnf for selflink: {}, vnf-id: {}", genericVnfSelfLink, + genericVnfId); + result.add(genericVnf); + } + } + }); + return result; + } + } + LOGGER.error("No match found for selflink: {}", selflink); + return Collections.emptyList(); + } + + @Override + public boolean deleteGenericVnf(final String vnfId, final String resourceVersion) { + final Optional<GenericVnf> optional = getGenericVnf(vnfId); + if (optional.isPresent()) { + final GenericVnf genericVnf = optional.get(); + if (genericVnf.getResourceVersion() != null && genericVnf.getResourceVersion().equals(resourceVersion)) { + final Cache cache = getCache(GENERIC_VNF_CACHE.getName()); + LOGGER.info("Will evict GenericVnf from cache with vnfId: {}", genericVnf.getVnfId()); + cache.evict(vnfId); + return true; + } + } + LOGGER.error("Unable to find GenericVnf for vnfId: {} and resourceVersion: {} ...", vnfId, resourceVersion); + return false; + } + + private Relationship getRelationship(final String relatedLink, final GenericVnf genericVnf, + final String relationshipLabel) { + final Relationship relationShip = new Relationship(); + relationShip.setRelatedTo(GENERIC_VNF); + relationShip.setRelationshipLabel(relationshipLabel); + relationShip.setRelatedLink(relatedLink); + + final RelationshipData relationshipData = new RelationshipData(); + relationshipData.setRelationshipKey(GENERIC_VNF_VNF_ID); + relationshipData.setRelationshipValue(genericVnf.getVnfId()); + relationShip.getRelationshipData().add(relationshipData); + + final RelatedToProperty relatedToProperty = new RelatedToProperty(); + relatedToProperty.setPropertyKey(GENERIC_VNF_VNF_NAME); + relatedToProperty.setPropertyValue(genericVnf.getVnfName()); + relationShip.getRelatedToProperty().add(relatedToProperty); + return relationShip; + } + + @Override + public void clearAll() { + clearCache(GENERIC_VNF_CACHE.getName()); + } + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/HttpRestServiceProvider.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/HttpRestServiceProvider.java new file mode 100755 index 000000000..2075fa0c2 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/HttpRestServiceProvider.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.service.providers; + +import java.util.Optional; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.ResponseEntity; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +public interface HttpRestServiceProvider { + + <T> ResponseEntity<T> invokeHttpPut(final HttpEntity<Object> httpEntity, final String url, final Class<T> clazz); + + <T> Optional<T> put(final HttpHeaders headers, final Object object, final String url, final Class<T> clazz); +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/HttpRestServiceProviderImpl.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/HttpRestServiceProviderImpl.java new file mode 100755 index 000000000..1989c643d --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/HttpRestServiceProviderImpl.java @@ -0,0 +1,98 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.service.providers; + +import java.util.Optional; +import org.onap.aaisimulator.exception.InvalidRestRequestException; +import org.onap.aaisimulator.exception.RestProcessingException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +@Service +public class HttpRestServiceProviderImpl implements HttpRestServiceProvider { + private static final Logger LOGGER = LoggerFactory.getLogger(HttpRestServiceProviderImpl.class); + + private final RestTemplate restTemplate; + + @Autowired + public HttpRestServiceProviderImpl(final RestTemplate restTemplate) { + this.restTemplate = restTemplate; + } + + @Override + public <T> ResponseEntity<T> invokeHttpPut(final HttpEntity<Object> httpEntity, final String url, + final Class<T> clazz) { + + final HttpMethod httpMethod = HttpMethod.PUT; + LOGGER.trace("Will invoke HTTP {} using URL: {}", httpMethod, url); + try { + return restTemplate.exchange(url, httpMethod, httpEntity, clazz); + + } catch (final HttpClientErrorException httpClientErrorException) { + final String message = "Unable to invoke HTTP " + httpMethod + " using url: " + url + ", Response: " + + httpClientErrorException.getRawStatusCode(); + LOGGER.error(message, httpClientErrorException); + final int rawStatusCode = httpClientErrorException.getRawStatusCode(); + if (rawStatusCode == HttpStatus.BAD_REQUEST.value() || rawStatusCode == HttpStatus.NOT_FOUND.value()) { + throw new InvalidRestRequestException("No result found for given url: " + url); + } + throw new RestProcessingException("Unable to invoke HTTP " + httpMethod + " using URL: " + url); + + } catch (final RestClientException restClientException) { + LOGGER.error("Unable to invoke HTTP POST using url: {}", url, restClientException); + throw new RestProcessingException("Unable to invoke HTTP " + httpMethod + " using URL: " + url, + restClientException); + } + } + + @Override + public <T> Optional<T> put(final HttpHeaders headers, final Object object, final String url, final Class<T> clazz) { + final HttpEntity<Object> httpEntity = new HttpEntity<Object>(object, headers); + final ResponseEntity<T> response = invokeHttpPut(httpEntity, url, clazz); + + if (!response.getStatusCode().equals(HttpStatus.OK) && !response.getStatusCode().equals(HttpStatus.CREATED) + && !response.getStatusCode().equals(HttpStatus.ACCEPTED)) { + final String message = "Unable to invoke HTTP " + HttpMethod.PUT + " using URL: " + url + + ", Response Code: " + response.getStatusCode(); + LOGGER.error(message); + return Optional.empty(); + } + + if (response.hasBody()) { + return Optional.of(response.getBody()); + } + LOGGER.error("Received response without body status code: {}", response.getStatusCode()); + return Optional.empty(); + } +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/LinesOfBusinessCacheServiceProvider.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/LinesOfBusinessCacheServiceProvider.java new file mode 100755 index 000000000..391238556 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/LinesOfBusinessCacheServiceProvider.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.service.providers; + +import java.util.Optional; +import org.onap.aai.domain.yang.LineOfBusiness; +import org.onap.aai.domain.yang.Relationship; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +public interface LinesOfBusinessCacheServiceProvider extends Clearable { + + void putLineOfBusiness(final String lineOfBusinessName, final LineOfBusiness lineOfBusiness); + + Optional<LineOfBusiness> getLineOfBusiness(final String lineOfBusinessName); + + Optional<Relationship> addRelationShip(final String lineOfBusinessName, final Relationship relationship, + final String requestURI); + + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/LinesOfBusinessCacheServiceProviderImpl.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/LinesOfBusinessCacheServiceProviderImpl.java new file mode 100755 index 000000000..9c0d4a22f --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/LinesOfBusinessCacheServiceProviderImpl.java @@ -0,0 +1,111 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.service.providers; + +import static org.onap.aaisimulator.utils.CacheName.LINES_OF_BUSINESS_CACHE; +import static org.onap.aaisimulator.utils.Constants.LINE_OF_BUSINESS; +import static org.onap.aaisimulator.utils.Constants.LINE_OF_BUSINESS_LINE_OF_BUSINESS_NAME; +import static org.onap.aaisimulator.utils.Constants.USES; +import static org.onap.aaisimulator.utils.HttpServiceUtils.getBiDirectionalRelationShipListRelatedLink; +import java.util.Optional; +import org.onap.aai.domain.yang.LineOfBusiness; +import org.onap.aai.domain.yang.Relationship; +import org.onap.aai.domain.yang.RelationshipData; +import org.onap.aai.domain.yang.RelationshipList; +import org.onap.aaisimulator.cache.provider.AbstractCacheServiceProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.stereotype.Service; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +@Service +public class LinesOfBusinessCacheServiceProviderImpl extends AbstractCacheServiceProvider + implements LinesOfBusinessCacheServiceProvider { + + private static final Logger LOGGER = LoggerFactory.getLogger(LinesOfBusinessCacheServiceProviderImpl.class); + + @Autowired + public LinesOfBusinessCacheServiceProviderImpl(final CacheManager cacheManager) { + super(cacheManager); + } + + @Override + public void putLineOfBusiness(final String lineOfBusinessName, final LineOfBusiness lineOfBusiness) { + LOGGER.info("Adding LineOfBusiness to cache with key: {} ...", lineOfBusinessName); + final Cache cache = getCache(LINES_OF_BUSINESS_CACHE.getName()); + cache.put(lineOfBusinessName, lineOfBusiness); + + } + + @Override + public Optional<LineOfBusiness> getLineOfBusiness(final String lineOfBusinessName) { + LOGGER.info("getting LineOfBusiness from cache using key: {}", lineOfBusinessName); + final Cache cache = getCache(LINES_OF_BUSINESS_CACHE.getName()); + final LineOfBusiness value = cache.get(lineOfBusinessName, LineOfBusiness.class); + if (value != null) { + return Optional.of(value); + } + LOGGER.error("Unable to find LineOfBusiness in cache using key:{} ", lineOfBusinessName); + return Optional.empty(); + } + + @Override + public Optional<Relationship> addRelationShip(final String lineOfBusinessName, final Relationship relationship, + final String requestUri) { + final Optional<LineOfBusiness> optional = getLineOfBusiness(lineOfBusinessName); + if (optional.isPresent()) { + final LineOfBusiness lineOfBusiness = optional.get(); + RelationshipList relationshipList = lineOfBusiness.getRelationshipList(); + if (relationshipList == null) { + relationshipList = new RelationshipList(); + lineOfBusiness.setRelationshipList(relationshipList); + } + relationshipList.getRelationship().add(relationship); + + LOGGER.info("Successfully added relation to LineOfBusiness with name: {}", lineOfBusinessName); + final Relationship resultantRelationship = new Relationship(); + resultantRelationship.setRelatedTo(LINE_OF_BUSINESS); + resultantRelationship.setRelationshipLabel(USES); + resultantRelationship.setRelatedLink(getBiDirectionalRelationShipListRelatedLink(requestUri)); + + final RelationshipData relationshipData = new RelationshipData(); + relationshipData.setRelationshipKey(LINE_OF_BUSINESS_LINE_OF_BUSINESS_NAME); + relationshipData.setRelationshipValue(lineOfBusiness.getLineOfBusinessName()); + resultantRelationship.getRelationshipData().add(relationshipData); + + return Optional.of(resultantRelationship); + + } + LOGGER.error("Unable to find LineOfBusiness using name: {} ...", lineOfBusinessName); + return Optional.empty(); + } + + @Override + public void clearAll() { + clearCache(LINES_OF_BUSINESS_CACHE.getName()); + } + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/NodesCacheServiceProvider.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/NodesCacheServiceProvider.java new file mode 100755 index 000000000..113a44f48 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/NodesCacheServiceProvider.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.service.providers; + +import java.util.Optional; +import org.onap.aai.domain.yang.GenericVnfs; +import org.onap.aai.domain.yang.ServiceInstance; +import org.onap.aaisimulator.models.NodeServiceInstance; + +/** + * @author waqas.ikram@ericsson.com + * + */ +public interface NodesCacheServiceProvider extends Clearable { + + void putNodeServiceInstance(final String serviceInstanceId, final NodeServiceInstance nodeServiceInstance); + + Optional<NodeServiceInstance> getNodeServiceInstance(final String serviceInstanceId); + + Optional<GenericVnfs> getGenericVnfs(final String vnfName); + + Optional<ServiceInstance> getServiceInstance(final NodeServiceInstance nodeServiceInstance); + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/NodesCacheServiceProviderImpl.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/NodesCacheServiceProviderImpl.java new file mode 100755 index 000000000..120236b15 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/NodesCacheServiceProviderImpl.java @@ -0,0 +1,104 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.service.providers; + +import static org.onap.aaisimulator.utils.CacheName.NODES_CACHE; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import org.onap.aai.domain.yang.GenericVnf; +import org.onap.aai.domain.yang.GenericVnfs; +import org.onap.aai.domain.yang.ServiceInstance; +import org.onap.aaisimulator.models.NodeServiceInstance; +import org.onap.aaisimulator.cache.provider.AbstractCacheServiceProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.stereotype.Service; + +/** + * @author waqas.ikram@ericsson.com + * + */ +@Service +public class NodesCacheServiceProviderImpl extends AbstractCacheServiceProvider implements NodesCacheServiceProvider { + private static final Logger LOGGER = LoggerFactory.getLogger(NodesCacheServiceProviderImpl.class); + private final GenericVnfCacheServiceProvider cacheServiceProvider; + private final CustomerCacheServiceProvider customerCacheServiceProvider; + + + @Autowired + public NodesCacheServiceProviderImpl(final CacheManager cacheManager, + final GenericVnfCacheServiceProvider cacheServiceProvider, + final CustomerCacheServiceProvider customerCacheServiceProvider) { + super(cacheManager); + this.cacheServiceProvider = cacheServiceProvider; + this.customerCacheServiceProvider = customerCacheServiceProvider; + } + + @Override + public void putNodeServiceInstance(final String serviceInstanceId, final NodeServiceInstance nodeServiceInstance) { + final Cache cache = getCache(NODES_CACHE.getName()); + LOGGER.info("Adding {} to cache with key: {}...", nodeServiceInstance, serviceInstanceId); + cache.put(serviceInstanceId, nodeServiceInstance); + } + + @Override + public Optional<NodeServiceInstance> getNodeServiceInstance(final String serviceInstanceId) { + final Cache cache = getCache(NODES_CACHE.getName()); + final NodeServiceInstance value = cache.get(serviceInstanceId, NodeServiceInstance.class); + if (value != null) { + return Optional.of(value); + } + LOGGER.error("Unable to find node service instance in cache using key:{} ", serviceInstanceId); + return Optional.empty(); + } + + @Override + public Optional<GenericVnfs> getGenericVnfs(final String vnfName) { + final Optional<String> genericVnfId = cacheServiceProvider.getGenericVnfId(vnfName); + if (genericVnfId.isPresent()) { + final Optional<GenericVnf> genericVnf = cacheServiceProvider.getGenericVnf(genericVnfId.get()); + if (genericVnf.isPresent()) { + final GenericVnfs genericVnfs = new GenericVnfs(); + genericVnfs.getGenericVnf().add(genericVnf.get()); + return Optional.of(genericVnfs); + } + } + LOGGER.error("Unable to find GenericVnf for name: {}", vnfName); + return Optional.empty(); + } + + @Override + public Optional<ServiceInstance> getServiceInstance(final NodeServiceInstance nodeServiceInstance) { + return customerCacheServiceProvider.getServiceInstance(nodeServiceInstance.getGlobalCustomerId(), + nodeServiceInstance.getServiceType(), nodeServiceInstance.getServiceInstanceId()); + } + + @Override + public void clearAll() { + final Cache cache = getCache(NODES_CACHE.getName()); + final ConcurrentHashMap<?, ?> nativeCache = (ConcurrentHashMap<?, ?>) cache.getNativeCache(); + LOGGER.info("Clear all entries from cahce: {}", cache.getName()); + nativeCache.clear(); + } + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/OwnEntityCacheServiceProvider.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/OwnEntityCacheServiceProvider.java new file mode 100755 index 000000000..d7aee99f7 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/OwnEntityCacheServiceProvider.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.service.providers; + +import java.util.Optional; +import org.onap.aai.domain.yang.OwningEntity; +import org.onap.aai.domain.yang.Relationship; +import org.springframework.http.HttpHeaders; + +/** + * @author waqas.ikram@ericsson.com + * + */ +public interface OwnEntityCacheServiceProvider extends Clearable { + + void putOwningEntity(final String owningEntityId, final OwningEntity owningEntity); + + Optional<OwningEntity> getOwningEntity(final String owningEntityId); + + boolean addRelationShip(final HttpHeaders incomingHeader, final String targetBaseUrl, final String requestUriString, + final String owningEntityId, final Relationship relationship); + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/OwnEntityCacheServiceProviderImpl.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/OwnEntityCacheServiceProviderImpl.java new file mode 100755 index 000000000..a592f9b3f --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/OwnEntityCacheServiceProviderImpl.java @@ -0,0 +1,138 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.service.providers; + +import static org.onap.aaisimulator.utils.CacheName.OWNING_ENTITY_CACHE; +import static org.onap.aaisimulator.utils.Constants.BELONGS_TO; +import static org.onap.aaisimulator.utils.Constants.OWNING_ENTITY; +import static org.onap.aaisimulator.utils.Constants.OWNING_ENTITY_OWNING_ENTITY_ID; +import static org.onap.aaisimulator.utils.HttpServiceUtils.getRelationShipListRelatedLink; +import static org.onap.aaisimulator.utils.HttpServiceUtils.getTargetUrl; +import java.util.List; +import java.util.Optional; +import org.onap.aai.domain.yang.OwningEntity; +import org.onap.aai.domain.yang.Relationship; +import org.onap.aai.domain.yang.RelationshipData; +import org.onap.aai.domain.yang.RelationshipList; +import org.onap.aaisimulator.cache.provider.AbstractCacheServiceProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.http.HttpHeaders; +import org.springframework.stereotype.Service; + +/** + * @author waqas.ikram@ericsson.com + * + */ +@Service +public class OwnEntityCacheServiceProviderImpl extends AbstractCacheServiceProvider + implements OwnEntityCacheServiceProvider { + + private static final Logger LOGGER = LoggerFactory.getLogger(OwnEntityCacheServiceProviderImpl.class); + + private final HttpRestServiceProvider httpRestServiceProvider; + + + @Autowired + public OwnEntityCacheServiceProviderImpl(final CacheManager cacheManager, + final HttpRestServiceProvider httpRestServiceProvider) { + super(cacheManager); + this.httpRestServiceProvider = httpRestServiceProvider; + } + + @Override + public void putOwningEntity(final String owningEntityId, final OwningEntity owningEntity) { + LOGGER.info("Adding OwningEntity: {} with name to cache", owningEntityId, owningEntity); + final Cache cache = getCache(OWNING_ENTITY_CACHE.getName()); + cache.put(owningEntityId, owningEntity); + } + + @Override + public Optional<OwningEntity> getOwningEntity(final String owningEntityId) { + LOGGER.info("getting OwningEntity from cache using key: {}", owningEntityId); + final Cache cache = getCache(OWNING_ENTITY_CACHE.getName()); + final OwningEntity value = cache.get(owningEntityId, OwningEntity.class); + if (value != null) { + return Optional.of(value); + } + return Optional.empty(); + } + + @Override + public boolean addRelationShip(final HttpHeaders incomingHeader, final String targetBaseUrl, + final String requestUriString, final String owningEntityId, final Relationship relationship) { + try { + final Optional<OwningEntity> optional = getOwningEntity(owningEntityId); + if (optional.isPresent()) { + final OwningEntity owningEntity = optional.get(); + final String targetUrl = getTargetUrl(targetBaseUrl, relationship.getRelatedLink()); + final Relationship outGoingRelationShip = getRelationship(requestUriString, owningEntity); + + final Optional<Relationship> optionalRelationship = httpRestServiceProvider.put(incomingHeader, + outGoingRelationShip, targetUrl, Relationship.class); + + if (optionalRelationship.isPresent()) { + final Relationship resultantRelationship = optionalRelationship.get(); + + RelationshipList relationshipList = owningEntity.getRelationshipList(); + if (relationshipList == null) { + relationshipList = new RelationshipList(); + owningEntity.setRelationshipList(relationshipList); + } + if (relationshipList.getRelationship().add(resultantRelationship)) { + LOGGER.info("added relationship {} in cache successfully", resultantRelationship); + return true; + } + } + } + + } catch (final Exception exception) { + LOGGER.error("Unable to add two-way relationship for owning entity id: {}", owningEntityId, exception); + } + LOGGER.error("Unable to add relationship in cache for owning entity id: {}", owningEntityId); + return false; + } + + @Override + public void clearAll() { + clearCache(OWNING_ENTITY_CACHE.getName()); + } + + private Relationship getRelationship(final String requestUriString, final OwningEntity owningEntity) { + final Relationship relationShip = new Relationship(); + relationShip.setRelatedTo(OWNING_ENTITY); + relationShip.setRelationshipLabel(BELONGS_TO); + relationShip.setRelatedLink(getRelationShipListRelatedLink(requestUriString)); + + final List<RelationshipData> relationshipDataList = relationShip.getRelationshipData(); + + final RelationshipData relationshipData = new RelationshipData(); + relationshipData.setRelationshipKey(OWNING_ENTITY_OWNING_ENTITY_ID); + relationshipData.setRelationshipValue(owningEntity.getOwningEntityId()); + + relationshipDataList.add(relationshipData); + + + return relationShip; + } +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/PlatformCacheServiceProvider.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/PlatformCacheServiceProvider.java new file mode 100755 index 000000000..0ede3feb2 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/PlatformCacheServiceProvider.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.service.providers; + +import java.util.Optional; +import org.onap.aai.domain.yang.Platform; +import org.onap.aai.domain.yang.Relationship; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +public interface PlatformCacheServiceProvider extends Clearable { + + void putPlatform(final String platformName, final Platform platform); + + Optional<Platform> getPlatform(final String platformName); + + Optional<Relationship> addRelationShip(final String platformName, final Relationship relationship, + final String requestUri); + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/PlatformCacheServiceProviderImpl.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/PlatformCacheServiceProviderImpl.java new file mode 100755 index 000000000..639b883d6 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/PlatformCacheServiceProviderImpl.java @@ -0,0 +1,110 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.service.providers; + +import static org.onap.aaisimulator.utils.CacheName.PLATFORM_CACHE; +import static org.onap.aaisimulator.utils.Constants.PLATFORM; +import static org.onap.aaisimulator.utils.Constants.PLATFORM_PLATFORM_NAME; +import static org.onap.aaisimulator.utils.Constants.USES; +import static org.onap.aaisimulator.utils.HttpServiceUtils.getBiDirectionalRelationShipListRelatedLink; +import java.util.Optional; +import org.onap.aai.domain.yang.Platform; +import org.onap.aai.domain.yang.Relationship; +import org.onap.aai.domain.yang.RelationshipData; +import org.onap.aai.domain.yang.RelationshipList; +import org.onap.aaisimulator.cache.provider.AbstractCacheServiceProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.stereotype.Service; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +@Service +public class PlatformCacheServiceProviderImpl extends AbstractCacheServiceProvider + implements PlatformCacheServiceProvider { + + private static final Logger LOGGER = LoggerFactory.getLogger(PlatformCacheServiceProviderImpl.class); + + @Autowired + public PlatformCacheServiceProviderImpl(final CacheManager cacheManager) { + super(cacheManager); + } + + @Override + public void putPlatform(final String platformName, final Platform platform) { + LOGGER.info("Adding Platform to cache with key: {} ...", platformName); + final Cache cache = getCache(PLATFORM_CACHE.getName()); + cache.put(platformName, platform); + } + + @Override + public Optional<Platform> getPlatform(final String platformName) { + LOGGER.info("getting Platform from cache using key: {}", platformName); + final Cache cache = getCache(PLATFORM_CACHE.getName()); + final Platform value = cache.get(platformName, Platform.class); + if (value != null) { + return Optional.of(value); + } + LOGGER.error("Unable to find Platform in cache using key:{} ", platformName); + return Optional.empty(); + } + + @Override + public Optional<Relationship> addRelationShip(final String platformName, final Relationship relationship, + final String requestUri) { + final Optional<Platform> optional = getPlatform(platformName); + if (optional.isPresent()) { + final Platform platform = optional.get(); + RelationshipList relationshipList = platform.getRelationshipList(); + if (relationshipList == null) { + relationshipList = new RelationshipList(); + platform.setRelationshipList(relationshipList); + } + relationshipList.getRelationship().add(relationship); + + LOGGER.info("Successfully add relation to Platform with name: {}", platformName); + + final Relationship resultantRelationship = new Relationship(); + resultantRelationship.setRelatedTo(PLATFORM); + resultantRelationship.setRelationshipLabel(USES); + resultantRelationship.setRelatedLink(getBiDirectionalRelationShipListRelatedLink(requestUri)); + + final RelationshipData relationshipData = new RelationshipData(); + relationshipData.setRelationshipKey(PLATFORM_PLATFORM_NAME); + relationshipData.setRelationshipValue(platform.getPlatformName()); + resultantRelationship.getRelationshipData().add(relationshipData); + + return Optional.of(resultantRelationship); + } + LOGGER.error("Unable to find Platform ..."); + return Optional.empty(); + } + + @Override + public void clearAll() { + clearCache(PLATFORM_CACHE.getName()); + } + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/PnfCacheServiceProvider.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/PnfCacheServiceProvider.java new file mode 100755 index 000000000..c27589e3c --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/PnfCacheServiceProvider.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.service.providers; + +import org.onap.aai.domain.yang.v15.Pnf; + +import java.util.List; +import java.util.Optional; + +/** + * @author Raj Gumma (raj.gumma@est.tech) + */ +public interface PnfCacheServiceProvider extends Clearable { + + void putPnf(final String pnfId, final Pnf pnf); + + Optional<Pnf> getPnf(final String pnfId); + + Optional<String> getPnfId(final String pnfName); + + boolean patchPnf(final String pnfId, final Pnf pnf); + + List<Pnf> getPnfs(final String selflink); + + boolean deletePnf(final String pnfId, final String resourceVersion); + + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/PnfCacheServiceProviderImpl.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/PnfCacheServiceProviderImpl.java new file mode 100755 index 000000000..3f33883b1 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/PnfCacheServiceProviderImpl.java @@ -0,0 +1,154 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.service.providers; + +import org.onap.aai.domain.yang.v15.Pnf; +import org.onap.aaisimulator.utils.ShallowBeanCopy; +import org.onap.aaisimulator.cache.provider.AbstractCacheServiceProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; + +import static org.onap.aaisimulator.utils.CacheName.PNF_CACHE; + +/** + * @author Raj Gumma (raj.gumma@est.tech) + */ +@Service +public class PnfCacheServiceProviderImpl extends AbstractCacheServiceProvider implements PnfCacheServiceProvider { + + + private static final Logger LOGGER = LoggerFactory.getLogger(PnfCacheServiceProvider.class); + + private final Cache cache; + + @Autowired + public PnfCacheServiceProviderImpl(final CacheManager cacheManager) { + super(cacheManager); + cache = getCache(PNF_CACHE.getName()); + } + + @Override + public void putPnf(final String pnfId, final Pnf pnf) { + LOGGER.info("Adding pnf: {} with key: {} in cache ...", pnf, pnfId); + cache.put(pnfId, pnf); + } + + @Override + public Optional<Pnf> getPnf(final String pnfId) { + LOGGER.info("getting Pnf from cache using key: {}", pnfId); + final Pnf value = cache.get(pnfId, Pnf.class); + return Optional.ofNullable(value); + } + + @Override + public Optional<String> getPnfId(final String pnfName) { + final Object nativeCache = cache.getNativeCache(); + if (nativeCache instanceof ConcurrentHashMap) { + @SuppressWarnings("unchecked") final ConcurrentHashMap<Object, Object> concurrentHashMap = + (ConcurrentHashMap<Object, Object>) nativeCache; + for (final Object key : concurrentHashMap.keySet()) { + final Optional<Pnf> optional = getPnf(key.toString()); + if (optional.isPresent()) { + final String cachedPnfName = optional.get().getPnfName(); + if (cachedPnfName != null && cachedPnfName.equals(cachedPnfName)) { + final String pnfId = optional.get().getPnfId(); + LOGGER.info("Found matching pnf for name: {}, pnf-id: {}", cachedPnfName, pnfId); + return Optional.of(pnfId); + } + } + } + } + return Optional.empty(); + } + + @Override + public boolean patchPnf(final String pnfId, final Pnf pnf) { + final Optional<Pnf> optional = getPnf(pnfId); + if (optional.isPresent()) { + final Pnf cachedPnf = optional.get(); + try { + ShallowBeanCopy.copy(pnf, cachedPnf); + return true; + } catch (final Exception exception) { + LOGGER.error("Unable to update Pnf for pnfId: {}", pnfId, exception); + } + } + LOGGER.error("Unable to find Pnf for pnfID : {}", pnfId); + return false; + } + + @Override + public List<Pnf> getPnfs(String selfLink) { + final Object nativeCache = cache.getNativeCache(); + if (nativeCache instanceof ConcurrentHashMap) { + @SuppressWarnings("unchecked") final ConcurrentHashMap<Object, Object> concurrentHashMap = + (ConcurrentHashMap<Object, Object>) nativeCache; + final List<Pnf> result = new ArrayList<>(); + + concurrentHashMap.keySet().stream().forEach(key -> { + final Optional<Pnf> optional = getPnf(key.toString()); + if (optional.isPresent()) { + final Pnf pnf = optional.get(); + final String pnfSelfLink = pnf.getSelflink(); + final String pnfId = pnf.getSelflink(); + + if (pnfSelfLink != null && pnfSelfLink.equals(selfLink)) { + LOGGER.info("Found matching pnf for selflink: {}, pnf-id: {}", pnfSelfLink, + pnfId); + result.add(pnf); + } + } + }); + return result; + } + LOGGER.error("No match found for selflink: {}", selfLink); + return Collections.emptyList(); + } + + @Override + public boolean deletePnf(String pnfId, String resourceVersion) { + final Optional<Pnf> optional = getPnf(pnfId); + if (optional.isPresent()) { + final Pnf pnf = optional.get(); + if (pnf.getResourceVersion() != null && pnf.getResourceVersion().equals(resourceVersion)) { + LOGGER.info("Will evict pnf from cache with pnfId: {}", pnf.getPnfId()); + cache.evict(pnfId); + return true; + } + } + LOGGER.error("Unable to find Pnf for pnfId: {} and resourceVersion: {} ...", pnfId, resourceVersion); + return false; + } + + @Override + public void clearAll() { + clearCache(cache.getName()); + } +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/ProjectCacheServiceProvider.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/ProjectCacheServiceProvider.java new file mode 100755 index 000000000..f766b1790 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/ProjectCacheServiceProvider.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.service.providers; + +import java.util.Optional; +import org.onap.aai.domain.yang.Project; +import org.onap.aai.domain.yang.Relationship; +import org.springframework.http.HttpHeaders; + +/** + * @author waqas.ikram@ericsson.com + * + */ +public interface ProjectCacheServiceProvider extends Clearable { + + void putProject(final String projectName, final Project project); + + Optional<Project> getProject(final String projectName); + + boolean addRelationShip(final HttpHeaders incomingHeader, final String targetBaseUrl, final String requestUri, + final String projectName, final Relationship relationship); + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/ProjectCacheServiceProviderImpl.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/ProjectCacheServiceProviderImpl.java new file mode 100755 index 000000000..6b690aa5c --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/service/providers/ProjectCacheServiceProviderImpl.java @@ -0,0 +1,140 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.service.providers; + +import static org.onap.aaisimulator.utils.CacheName.PROJECT_CACHE; +import static org.onap.aaisimulator.utils.Constants.PROJECT; +import static org.onap.aaisimulator.utils.Constants.PROJECT_PROJECT_NAME; +import static org.onap.aaisimulator.utils.Constants.USES; +import static org.onap.aaisimulator.utils.HttpServiceUtils.getRelationShipListRelatedLink; +import static org.onap.aaisimulator.utils.HttpServiceUtils.getTargetUrl; +import java.util.List; +import java.util.Optional; +import org.onap.aai.domain.yang.Project; +import org.onap.aai.domain.yang.Relationship; +import org.onap.aai.domain.yang.RelationshipData; +import org.onap.aai.domain.yang.RelationshipList; +import org.onap.aaisimulator.cache.provider.AbstractCacheServiceProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.http.HttpHeaders; +import org.springframework.stereotype.Service; + +/** + * @author waqas.ikram@ericsson.com + * + */ +@Service +public class ProjectCacheServiceProviderImpl extends AbstractCacheServiceProvider + implements ProjectCacheServiceProvider { + + private static final Logger LOGGER = LoggerFactory.getLogger(ProjectCacheServiceProviderImpl.class); + + private final HttpRestServiceProvider httpRestServiceProvider; + + @Autowired + public ProjectCacheServiceProviderImpl(final CacheManager cacheManager, + final HttpRestServiceProvider httpRestServiceProvider) { + super(cacheManager); + this.httpRestServiceProvider = httpRestServiceProvider; + } + + @Override + public void putProject(final String projectName, final Project project) { + LOGGER.info("Adding project: {} with name to cache", project, projectName); + final Cache cache = getCache(PROJECT_CACHE.getName()); + cache.put(projectName, project); + } + + + @Override + public Optional<Project> getProject(final String projectName) { + LOGGER.info("getting project from cache using key: {}", projectName); + final Cache cache = getCache(PROJECT_CACHE.getName()); + final Project value = cache.get(projectName, Project.class); + if (value != null) { + return Optional.of(value); + } + return Optional.empty(); + } + + @Override + public boolean addRelationShip(final HttpHeaders incomingHeader, final String targetBaseUrl, + final String requestUriString, final String projectName, final Relationship relationship) { + try { + final Optional<Project> optional = getProject(projectName); + + if (optional.isPresent()) { + final Project project = optional.get(); + final String targetUrl = getTargetUrl(targetBaseUrl, relationship.getRelatedLink()); + final Relationship outGoingRelationShip = getRelationship(requestUriString, project); + + final Optional<Relationship> optionalRelationship = httpRestServiceProvider.put(incomingHeader, + outGoingRelationShip, targetUrl, Relationship.class); + + if (optionalRelationship.isPresent()) { + final Relationship resultantRelationship = optionalRelationship.get(); + + RelationshipList relationshipList = project.getRelationshipList(); + if (relationshipList == null) { + relationshipList = new RelationshipList(); + project.setRelationshipList(relationshipList); + } + if (relationshipList.getRelationship().add(resultantRelationship)) { + LOGGER.info("added relationship {} in cache successfully", resultantRelationship); + return true; + } + } + } + } catch (final Exception exception) { + LOGGER.error("Unable to add two-way relationship for project name: {}", projectName, exception); + } + LOGGER.error("Unable to add relationship in cache for project name: {}", projectName); + return false; + } + + @Override + public void clearAll() { + clearCache(PROJECT_CACHE.getName()); + } + + private Relationship getRelationship(final String requestUriString, final Project project) { + + final Relationship relationShip = new Relationship(); + relationShip.setRelatedTo(PROJECT); + relationShip.setRelationshipLabel(USES); + relationShip.setRelatedLink(getRelationShipListRelatedLink(requestUriString)); + + final List<RelationshipData> relationshipDataList = relationShip.getRelationshipData(); + + final RelationshipData relationshipData = new RelationshipData(); + relationshipData.setRelationshipKey(PROJECT_PROJECT_NAME); + relationshipData.setRelationshipValue(project.getProjectName()); + + relationshipDataList.add(relationshipData); + + + return relationShip; + } + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/utils/CacheName.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/utils/CacheName.java new file mode 100755 index 000000000..63e7e2614 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/utils/CacheName.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.utils; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +public enum CacheName { + + CUSTOMER_CACHE("customer-cache"), + PROJECT_CACHE("project-cache"), + NODES_CACHE("nodes-cache"), + GENERIC_VNF_CACHE("generic-vnf-cache"), + PNF_CACHE("pnf-cache"), + OWNING_ENTITY_CACHE("owning-entity-cache"), + PLATFORM_CACHE("platform-cache"), + LINES_OF_BUSINESS_CACHE("lines-of-business-cache"), + CLOUD_REGION_CACHE("cloud-region-cache"), + ESR_VNFM_CACHE("esr-vnfm-cache"); + + private String name; + + private CacheName(final String name) { + this.name = name; + } + + public String getName() { + return name; + } +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/utils/Constants.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/utils/Constants.java new file mode 100755 index 000000000..24aaa0656 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/utils/Constants.java @@ -0,0 +1,153 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.utils; + +/** + * @author waqas.ikram@ericsson.com + * + */ +public class Constants { + + public static final String BASE_URL = "/aai/v{version:\\d+}"; + + public static final String NODES_URL = BASE_URL + "/nodes"; + + public static final String BUSINESS_URL = BASE_URL + "/business"; + + public static final String CLOUD_INFRASTRUCTURE_URL = BASE_URL + "/cloud-infrastructure"; + + public static final String CLOUD_REGIONS = CLOUD_INFRASTRUCTURE_URL + "/cloud-regions/cloud-region/"; + + public static final String CUSTOMER_URL = BUSINESS_URL + "/customers/customer/"; + + public static final String PROJECT_URL = BUSINESS_URL + "/projects/project/"; + + public static final String OWNING_ENTITY_URL = BUSINESS_URL + "/owning-entities/owning-entity/"; + + public static final String PLATFORMS_URL = BUSINESS_URL + "/platforms/platform/"; + + public static final String EXTERNAL_SYSTEM_ESR_VNFM_LIST_URL = BASE_URL + "/external-system/esr-vnfm-list"; + + public static final String NETWORK_URL = BASE_URL + "/network"; + + public static final String GENERIC_VNFS_URL = NETWORK_URL + "/generic-vnfs"; + + public static final String PNFS_URL = NETWORK_URL+ "/pnfs"; + + public static final String RELATIONSHIP_LIST_RELATIONSHIP_URL = "/relationship-list/relationship"; + + public static final String BI_DIRECTIONAL_RELATIONSHIP_LIST_URL = + RELATIONSHIP_LIST_RELATIONSHIP_URL + "/bi-directional"; + + public static final String LINES_OF_BUSINESS_URL = BUSINESS_URL + "/lines-of-business/line-of-business/"; + + public static final String SERVICE_DESIGN_AND_CREATION_URL = BASE_URL + "/service-design-and-creation"; + + public static final String HEALTHY = "healthy"; + + public static final String PROJECT = "project"; + + public static final String PROJECT_PROJECT_NAME = "project.project-name"; + + public static final String OWNING_ENTITY = "owning-entity"; + + public static final String OWNING_ENTITY_OWNING_ENTITY_ID = "owning-entity.owning-entity-id"; + + public static final String X_HTTP_METHOD_OVERRIDE = "X-HTTP-Method-Override"; + + public static final String APPLICATION_MERGE_PATCH_JSON = "application/merge-patch+json"; + + public static final String SERVICE_RESOURCE_TYPE = "service-instance"; + + public static final String RESOURCE_LINK = "resource-link"; + + public static final String RESOURCE_TYPE = "resource-type"; + + public static final String GENERIC_VNF_VNF_NAME = "generic-vnf.vnf-name"; + + public static final String GENERIC_VNF_VNF_ID = "generic-vnf.vnf-id"; + + public static final String SERVICE_INSTANCE_SERVICE_INSTANCE_ID = "service-instance.service-instance-id"; + + public static final String SERVICE_SUBSCRIPTION_SERVICE_TYPE = "service-subscription.service-type"; + + public static final String CUSTOMER_GLOBAL_CUSTOMER_ID = "customer.global-customer-id"; + + public static final String COMPOSED_OF = "org.onap.relationships.inventory.ComposedOf"; + + public static final String GENERIC_VNF = "generic-vnf"; + + public static final String PNF = "pnf"; + + public static final String PLATFORM = "platform"; + + public static final String USES = "org.onap.relationships.inventory.Uses"; + + public static final String PLATFORM_PLATFORM_NAME = "platform.platform-name"; + + public static final String LINE_OF_BUSINESS_LINE_OF_BUSINESS_NAME = "line-of-business.line-of-business-name"; + + public static final String LINE_OF_BUSINESS = "line-of-business"; + + public static final String SERVICE_SUBSCRIPTION = "service-subscription"; + + public static final String CUSTOMER_TYPE = "Customer"; + + public static final String SERVICE_INSTANCE_SERVICE_INSTANCE_NAME = "service-instance.service-instance-name"; + + public static final String CLOUD_REGION_OWNER_DEFINED_TYPE = "cloud-region.owner-defined-type"; + + public static final String CLOUD_REGION_CLOUD_REGION_ID = "cloud-region.cloud-region-id"; + + public static final String CLOUD_REGION_CLOUD_OWNER = "cloud-region.cloud-owner"; + + public static final String LOCATED_IN = "org.onap.relationships.inventory.LocatedIn"; + + public static final String CLOUD_REGION = "cloud-region"; + + public static final String TENANT_TENANT_NAME = "tenant.tenant-name"; + + public static final String TENANT_TENANT_ID = "tenant.tenant-id"; + + public static final String BELONGS_TO = "org.onap.relationships.inventory.BelongsTo"; + + public static final String TENANT = "tenant"; + + public static final String ESR_VNFM = "esr-vnfm"; + + public static final String ESR_SYSTEM_INFO = "esr-system-info"; + + public static final String ESR_SYSTEM_INFO_LIST = "esr-system-info-list"; + + public static final String ESR_VNFM_VNFM_ID = "esr-vnfm.vnfm-id"; + + public static final String DEPENDS_ON = "tosca.relationships.DependsOn"; + + public static final String VSERVER_VSERVER_NAME = "vserver.vserver-name"; + + public static final String VSERVER_VSERVER_ID = "vserver.vserver-id"; + + public static final String HOSTED_ON = "tosca.relationships.HostedOn"; + + public static final String VSERVER = "vserver"; + + private Constants() {} + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/utils/HttpServiceUtils.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/utils/HttpServiceUtils.java new file mode 100755 index 000000000..0d83a50f9 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/utils/HttpServiceUtils.java @@ -0,0 +1,107 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.utils; + +import static org.onap.aaisimulator.utils.Constants.BI_DIRECTIONAL_RELATIONSHIP_LIST_URL; +import static org.onap.aaisimulator.utils.Constants.RELATIONSHIP_LIST_RELATIONSHIP_URL; +import static org.springframework.http.MediaType.APPLICATION_XML; +import java.net.URI; +import java.util.Arrays; +import java.util.Enumeration; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.servlet.http.HttpServletRequest; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.web.util.UriComponentsBuilder; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +public class HttpServiceUtils { + + private static final String START_WITH_FORWARD_SLASH = "(^/.*?)"; + private static final String ALPHANUMERIC = "((?:v+[a-z0-9]*)/)"; + private static final String REGEX = START_WITH_FORWARD_SLASH + ALPHANUMERIC; + private static final Pattern PATTERN = Pattern.compile(REGEX, Pattern.CASE_INSENSITIVE | Pattern.DOTALL); + + private HttpServiceUtils() {} + + public static URI getBaseUrl(final HttpServletRequest request) { + final StringBuffer url = request.getRequestURL(); + final String uri = request.getRequestURI(); + return UriComponentsBuilder.fromHttpUrl(url.substring(0, url.indexOf(uri))).path(getBaseUrl(uri)).build() + .toUri(); + } + + private static String getBaseUrl(final String uri) { + final Matcher matcher = PATTERN.matcher(uri); + if (matcher.find()) { + final StringBuilder builder = new StringBuilder(); + for (int index = 0; index < matcher.groupCount() - 1; index++) { + builder.append(matcher.group(index)); + } + return builder.toString(); + } + return uri; + } + + public static URI getBaseUrl(final StringBuffer requestUrl, final String requestUri) { + return UriComponentsBuilder.fromHttpUrl(requestUrl.substring(0, requestUrl.indexOf(requestUri))).build() + .toUri(); + } + + public static String getBaseServiceInstanceUrl(final HttpServletRequest request, final String relatedLink) { + return UriComponentsBuilder.fromUri(getBaseUrl(request)).path(relatedLink).toUriString(); + } + + public static HttpHeaders getHeaders(final HttpServletRequest request) { + return getHeaders(request, APPLICATION_XML); + } + + public static HttpHeaders getHeaders(final HttpServletRequest request, final MediaType mediaType) { + final HttpHeaders headers = new HttpHeaders(); + for (final Enumeration<String> enumeration = request.getHeaderNames(); enumeration.hasMoreElements();) { + final String headerName = enumeration.nextElement(); + headers.add(headerName, request.getHeader(headerName)); + } + headers.setContentType(mediaType); + headers.setAccept(Arrays.asList(MediaType.APPLICATION_XML)); + return headers; + } + + public static String getTargetUrl(final String targetBaseUrl, final String relatedLink) { + return UriComponentsBuilder.fromUriString(targetBaseUrl).path(relatedLink) + .path(BI_DIRECTIONAL_RELATIONSHIP_LIST_URL).toUriString(); + } + + public static String getRelationShipListRelatedLink(final String requestUriString) { + return requestUriString != null ? requestUriString.replaceFirst(RELATIONSHIP_LIST_RELATIONSHIP_URL, "") + : requestUriString; + } + + public static String getBiDirectionalRelationShipListRelatedLink(final String requestUriString) { + return requestUriString != null ? requestUriString.replaceFirst(BI_DIRECTIONAL_RELATIONSHIP_LIST_URL, "") + : requestUriString; + } + + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/utils/RequestError.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/utils/RequestError.java new file mode 100755 index 000000000..191e9afb3 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/utils/RequestError.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.utils; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +/** + * @author waqas.ikram@ericsson.com + * + */ +@XmlRootElement(name = "requestError") +@XmlAccessorType(XmlAccessType.FIELD) +public class RequestError { + + @XmlElement(name = "serviceException") + private ServiceException serviceException; + + /** + * @return the serviceException + */ + public ServiceException getServiceException() { + return serviceException; + } + + /** + * @param serviceException the serviceException to set + */ + public void setServiceException(final ServiceException serviceException) { + this.serviceException = serviceException; + } + + @Override + public String toString() { + return "RequestError [serviceException=" + serviceException + "]"; + } + + + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/utils/RequestErrorBuilder.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/utils/RequestErrorBuilder.java new file mode 100755 index 000000000..a67cd9d92 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/utils/RequestErrorBuilder.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.utils; + +import java.util.Arrays; +import java.util.List; + +/** + * @author waqas.ikram@ericsson.com + * + */ +public class RequestErrorBuilder { + + private final ServiceException serviceException = new ServiceException(); + + public RequestErrorBuilder messageId(final String messageId) { + this.serviceException.setMessageId(messageId); + return this; + } + + public RequestErrorBuilder text(final String text) { + this.serviceException.setText(text); + return this; + } + + public RequestErrorBuilder variables(final List<String> variables) { + this.serviceException.setVariables(variables); + return this; + } + + public RequestErrorBuilder variables(final String... variables) { + this.serviceException.setVariables(Arrays.asList(variables)); + return this; + } + + public RequestError build() { + final RequestError requestError = new RequestError(); + requestError.setServiceException(serviceException); + return requestError; + } + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/utils/RequestErrorResponseUtils.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/utils/RequestErrorResponseUtils.java new file mode 100755 index 000000000..bc302405c --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/utils/RequestErrorResponseUtils.java @@ -0,0 +1,57 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.utils; + +import javax.servlet.http.HttpServletRequest; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +/** + * @author waqas.ikram@ericsson.com + * + */ +public class RequestErrorResponseUtils { + + public static final String ERROR_MESSAGE_ID = "SVC3001"; + + public static final String ERROR_MESSAGE = "Resource not found for %1 using id %2 (msg=%3) (ec=%4)"; + + private static final String EMPTY_STRING = ""; + + public static final String getResourceVersion() { + return System.currentTimeMillis() + EMPTY_STRING; + } + + public static ResponseEntity<?> getRequestErrorResponseEntity(final HttpServletRequest request, + final String nodeType) { + return new ResponseEntity<>(new RequestErrorBuilder().messageId(ERROR_MESSAGE_ID).text(ERROR_MESSAGE) + .variables(request.getMethod(), request.getRequestURI(), + "Node Not Found:No Node of " + nodeType + " found at: " + request.getRequestURI(), + "ERR.5.4.6114") + .build(), HttpStatus.NOT_FOUND); + } + + public static ResponseEntity<?> getRequestErrorResponseEntity(final HttpServletRequest request) { + return getRequestErrorResponseEntity(request, Constants.SERVICE_RESOURCE_TYPE); + } + + private RequestErrorResponseUtils() {} + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/utils/ServiceException.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/utils/ServiceException.java new file mode 100755 index 000000000..c349b8e4a --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/utils/ServiceException.java @@ -0,0 +1,88 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.utils; + +import java.util.List; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlRootElement; + +/** + * @author waqas.ikram@ericsson.com + * + */ +@XmlRootElement(name = "serviceException") +@XmlAccessorType(XmlAccessType.FIELD) +public class ServiceException { + + private String messageId; + + private String text; + + private List<String> variables; + + /** + * @return the messageId + */ + public String getMessageId() { + return messageId; + } + + /** + * @param messageId the messageId to set + */ + public void setMessageId(final String messageId) { + this.messageId = messageId; + } + + /** + * @return the text + */ + public String getText() { + return text; + } + + /** + * @param text the text to set + */ + public void setText(final String text) { + this.text = text; + } + + /** + * @return the variables + */ + public List<String> getVariables() { + return variables; + } + + /** + * @param variables the variables to set + */ + public void setVariables(final List<String> variables) { + this.variables = variables; + } + + @Override + public String toString() { + return "ServiceException [messageId=" + messageId + ", text=" + text + ", variables=" + variables + "]"; + } + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/utils/ShallowBeanCopy.java b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/utils/ShallowBeanCopy.java new file mode 100755 index 000000000..64c6efc5e --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/java/org/onap/aaisimulator/utils/ShallowBeanCopy.java @@ -0,0 +1,89 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.aaisimulator.utils; + +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +public class ShallowBeanCopy { + private static final Logger LOGGER = LoggerFactory.getLogger(ShallowBeanCopy.class); + + private ShallowBeanCopy() {} + + public static void copy(final Object from, final Object to) throws Exception { + final Map<String, Method> fromMethods = getMethods(from); + final Map<String, Method> toMethods = getMethods(to); + + for (final Entry<String, Method> entry : fromMethods.entrySet()) { + final String methodName = entry.getKey(); + final Method fromMethod = entry.getValue(); + + final Optional<Method> optional = getSetMethod(to, fromMethod); + if (optional.isPresent()) { + final Method toGetMethod = toMethods.get(methodName); + final Method toMethod = optional.get(); + final Object toValue = fromMethod.invoke(from); + + final Object fromValue = toGetMethod.invoke(to); + if (toValue != null && !toValue.equals(fromValue)) { + LOGGER.info("Changing {} value from: {} to: {}", methodName, fromValue, toValue); + toMethod.invoke(to, toValue); + } + } + } + } + + + private static Optional<Method> getSetMethod(final Object to, final Method fromMethod) { + final String name = fromMethod.getName().replaceFirst("get|is", "set"); + final Class<?> returnType = fromMethod.getReturnType(); + try { + return Optional.of(to.getClass().getMethod(name, returnType)); + } catch (final NoSuchMethodException noSuchMethodException) { + } + return Optional.empty(); + } + + private static Map<String, Method> getMethods(final Object object) { + final Map<String, Method> methodsFound = new HashMap<>(); + final Method[] methods = object.getClass().getMethods(); + + for (final Method method : methods) { + if (method.getName().startsWith("get") || method.getName().startsWith("is")) { + final String name = method.getName().replaceFirst("get|is", ""); + + methodsFound.put(name, method); + } + } + + return methodsFound; + + } + +} diff --git a/test/mocks/aai-simulator/aai-sim/src/main/resources/application.yaml b/test/mocks/aai-simulator/aai-sim/src/main/resources/application.yaml new file mode 100755 index 000000000..a59f3ccde --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/resources/application.yaml @@ -0,0 +1,25 @@ +server: + port: 9993 + tomcat: + max-threads: 4 + ssl: + key-store: classpath:keystore/keystore.p12 + key-store-password: mYHC98!qX}7h?W}jRv}MIXTJ + keyStoreType: PKCS12 +ssl-enable: true +spring: + security: + users: + - username: aai + #password: aai.onap.org:demo123456! + password: $2a$04$crRntT01fAF4kb48mxlvgu68/silcLg.czC1LxQsKTdWuDBPpO3YO + role: VID + - username: aai@aai.onap.org + #password: demo123456! + password: $2a$04$06VCpDvW5ztE7WOvhhvAtOx7JHLghECyZIzOShIbXLWpnshMva8T6 + role: VID +http: + client: + ssl: + trust-store: classpath:truststore/truststore.jks + trust-store-password: '*TQH?Lnszprs4LmlAj38yds(' diff --git a/test/mocks/aai-simulator/aai-sim/src/main/resources/keystore/keystore.p12 b/test/mocks/aai-simulator/aai-sim/src/main/resources/keystore/keystore.p12 Binary files differnew file mode 100644 index 000000000..6b4340d41 --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/resources/keystore/keystore.p12 diff --git a/test/mocks/aai-simulator/aai-sim/src/main/resources/truststore/truststore.jks b/test/mocks/aai-simulator/aai-sim/src/main/resources/truststore/truststore.jks Binary files differnew file mode 100644 index 000000000..d219aaf5a --- /dev/null +++ b/test/mocks/aai-simulator/aai-sim/src/main/resources/truststore/truststore.jks |