diff options
63 files changed, 2150 insertions, 489 deletions
diff --git a/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V7.2__Add_PNF_Column_Infra_Requests_archive_tables.sql b/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V7.2__Add_PNF_Column_Infra_Requests_archive_tables.sql index dbdc925dae..8c042dcbaf 100644 --- a/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V7.2__Add_PNF_Column_Infra_Requests_archive_tables.sql +++ b/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V7.2__Add_PNF_Column_Infra_Requests_archive_tables.sql @@ -1,4 +1,4 @@ use requestdb; -ALTER TABLE infra_active_requests ADD COLUMN IF NOT EXISTS PNF_ID varchar(45); -ALTER TABLE archived_infra_requests ADD COLUMN IF NOT EXISTS PNF_ID varchar(45);
\ No newline at end of file +ALTER TABLE infra_active_requests ADD COLUMN IF NOT EXISTS PNF_NAME varchar(45); +ALTER TABLE archived_infra_requests ADD COLUMN IF NOT EXISTS PNF_NAME varchar(45); diff --git a/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V8.1__Add_Orchestration_Task_Table.sql b/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V8.1__Add_Orchestration_Task_Table.sql new file mode 100644 index 0000000000..0d7cb7a62b --- /dev/null +++ b/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V8.1__Add_Orchestration_Task_Table.sql @@ -0,0 +1,12 @@ +USE `requestdb`; + +CREATE TABLE `orchestration_task` ( + `TASK_ID` varchar(200) NOT NULL, + `REQUEST_ID` varchar(200) NOT NULL, + `NAME` varchar(200) NOT NULL, + `CREATED_TIME` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `STATUS` varchar(200) NOT NULL, + `IS_MANUAL` varchar(20) NOT NULL, + `PARAMS` varchar(20000) DEFAULT NULL, + PRIMARY KEY (`TASK_ID`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1; diff --git a/adapters/mso-ve-vnfm-adapter/pom.xml b/adapters/mso-ve-vnfm-adapter/pom.xml index 4472956eb7..d58f183ab0 100644 --- a/adapters/mso-ve-vnfm-adapter/pom.xml +++ b/adapters/mso-ve-vnfm-adapter/pom.xml @@ -30,6 +30,10 @@ <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> + <groupId>org.springframework.retry</groupId> + <artifactId>spring-retry</artifactId> + </dependency> + <dependency> <groupId>org.onap.so.adapters</groupId> <artifactId>mso-vnfm-adapter-ext-clients</artifactId> <version>${project.version}</version> @@ -52,6 +56,10 @@ <artifactId>jersey-hk2</artifactId> </dependency> <dependency> + <groupId>org.projectlombok</groupId> + <artifactId>lombok</artifactId> + </dependency> + <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> diff --git a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/aai/AaiConnection.java b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/aai/AaiConnection.java index 188b6718f2..a2bd603ae6 100644 --- a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/aai/AaiConnection.java +++ b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/aai/AaiConnection.java @@ -22,11 +22,14 @@ package org.onap.so.adapters.vevnfm.aai; import java.util.List; import java.util.Optional; +import org.apache.logging.log4j.util.Strings; import org.onap.aai.domain.yang.EsrSystemInfo; import org.onap.aai.domain.yang.EsrVnfm; import org.onap.aai.domain.yang.EsrVnfmList; +import org.onap.so.adapters.vevnfm.exception.VeVnfmException; import org.onap.so.client.aai.AAIObjectType; import org.onap.so.client.aai.AAIResourcesClient; +import org.onap.so.client.aai.entities.uri.AAIResourceUri; import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.client.graphinventory.entities.uri.Depth; import org.slf4j.Logger; @@ -40,10 +43,30 @@ public class AaiConnection { private static final int FIRST_INDEX = 0; - public EsrSystemInfo receiveVnfm() { + private static void isValid(final EsrSystemInfo info) throws VeVnfmException { + if (info == null || Strings.isBlank(info.getServiceUrl())) { + throw new VeVnfmException("No 'url' field in VNFM info"); + } + } + + public EsrSystemInfo receiveVnfm() throws VeVnfmException { + EsrSystemInfo info; + + try { + info = receiveVnfmInternal(); + } catch (Exception e) { + throw new VeVnfmException(e); + } + + isValid(info); + + return info; + } + + private EsrSystemInfo receiveVnfmInternal() { final AAIResourcesClient resourcesClient = new AAIResourcesClient(); - final Optional<EsrVnfmList> response = - resourcesClient.get(EsrVnfmList.class, AAIUriFactory.createResourceUri(AAIObjectType.VNFM_LIST)); + final AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VNFM_LIST); + final Optional<EsrVnfmList> response = resourcesClient.get(EsrVnfmList.class, resourceUri); if (response.isPresent()) { final EsrVnfmList esrVnfmList = response.get(); diff --git a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/configuration/StartupConfiguration.java b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/configuration/StartupConfiguration.java index f7b7283c59..ae330f7ed6 100644 --- a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/configuration/StartupConfiguration.java +++ b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/configuration/StartupConfiguration.java @@ -20,7 +20,9 @@ package org.onap.so.adapters.vevnfm.configuration; +import org.onap.aai.domain.yang.EsrSystemInfo; import org.onap.so.adapters.vevnfm.service.StartupService; +import org.onap.so.adapters.vevnfm.service.SubscriptionScheduler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.annotation.Configuration; @@ -39,10 +41,14 @@ public class StartupConfiguration { @Autowired private StartupService startupService; + @Autowired + private SubscriptionScheduler subscriptionScheduler; + @EventListener(ApplicationReadyEvent.class) public void onApplicationReadyEvent() throws Exception { if (!environment.acceptsProfiles(Profiles.of(TEST_PROFILE))) { - startupService.run(); + final EsrSystemInfo info = startupService.receiveVnfm(); + subscriptionScheduler.setInfo(info); } } } diff --git a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/controller/NotificationController.java b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/controller/NotificationController.java index 1882b4e183..cb324c32a9 100644 --- a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/controller/NotificationController.java +++ b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/controller/NotificationController.java @@ -38,7 +38,7 @@ public class NotificationController { @Autowired private DmaapService dmaapService; - @PostMapping("${notification.url}") + @PostMapping("${vnfm.notification}") public ResponseEntity receiveNotification(@RequestBody final VnfLcmOperationOccurrenceNotification notification) { logger.info("Notification received {}", notification); dmaapService.send(notification); diff --git a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/exception/VeVnfmException.java b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/exception/VeVnfmException.java index abd9ff9d33..a0c1c1e9db 100644 --- a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/exception/VeVnfmException.java +++ b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/exception/VeVnfmException.java @@ -25,4 +25,8 @@ public class VeVnfmException extends Exception { public VeVnfmException(final String message) { super(message); } + + public VeVnfmException(final Throwable cause) { + super(cause); + } } diff --git a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/provider/AuthorizationHeadersProvider.java b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/provider/AuthorizationHeadersProvider.java index 251e0c426b..838a67d115 100644 --- a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/provider/AuthorizationHeadersProvider.java +++ b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/provider/AuthorizationHeadersProvider.java @@ -20,11 +20,16 @@ package org.onap.so.adapters.vevnfm.provider; +import org.apache.logging.log4j.util.Strings; import org.onap.so.configuration.rest.BasicHttpHeadersProvider; public class AuthorizationHeadersProvider extends BasicHttpHeadersProvider { public void addAuthorization(final String authorization) { + if (Strings.isBlank(authorization)) { + return; + } + getHttpHeaders().set(AUTHORIZATION_HEADER, authorization); } diff --git a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/service/StartupService.java b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/service/StartupService.java index dfbafa223c..3d215148f2 100644 --- a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/service/StartupService.java +++ b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/service/StartupService.java @@ -20,35 +20,43 @@ package org.onap.so.adapters.vevnfm.service; -import org.apache.logging.log4j.util.Strings; import org.onap.aai.domain.yang.EsrSystemInfo; import org.onap.so.adapters.vevnfm.aai.AaiConnection; import org.onap.so.adapters.vevnfm.exception.VeVnfmException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.retry.annotation.Backoff; +import org.springframework.retry.annotation.EnableRetry; +import org.springframework.retry.annotation.Recover; +import org.springframework.retry.annotation.Retryable; import org.springframework.stereotype.Service; @Service +@EnableRetry public class StartupService { - @Autowired - private AaiConnection aaiConnection; + private static final Logger logger = LoggerFactory.getLogger(StartupService.class); + + @Value("${vnfm.default-endpoint}") + private String vnfmDefaultEndpoint; @Autowired - private SubscriberService subscriberService; + private AaiConnection aaiConnection; - private static void isValid(final EsrSystemInfo info) throws VeVnfmException { - if (Strings.isBlank(info.getServiceUrl())) { - throw new VeVnfmException("No 'url' field in VNFM info"); - } + @Retryable(value = {VeVnfmException.class}, maxAttempts = 5, backoff = @Backoff(delay = 5000, multiplier = 10)) + public EsrSystemInfo receiveVnfm() throws VeVnfmException { + return aaiConnection.receiveVnfm(); } - public void run() throws Exception { - final EsrSystemInfo info = aaiConnection.receiveVnfm(); - isValid(info); - final boolean done = subscriberService.subscribe(info); + @Recover + public EsrSystemInfo recoverReceiveVnfm(final Throwable e) { + logger.warn("Connection to AAI failed"); + final EsrSystemInfo info = new EsrSystemInfo(); + info.setServiceUrl(vnfmDefaultEndpoint); + logger.warn("This EsrSystemInfo is used by default: {}", info); - if (!done) { - throw new VeVnfmException("Could not subscribe to VNFM"); - } + return info; } } diff --git a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/subscription/SubscribeSender.java b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/service/SubscribeSender.java index 8fdfb41d26..d01c3c8f66 100644 --- a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/subscription/SubscribeSender.java +++ b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/service/SubscribeSender.java @@ -18,9 +18,11 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.adapters.vevnfm.subscription; +package org.onap.so.adapters.vevnfm.service; +import com.fasterxml.jackson.annotation.JsonProperty; import org.onap.aai.domain.yang.EsrSystemInfo; +import org.onap.so.adapters.vevnfm.exception.VeVnfmException; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.LccnSubscriptionRequest; import org.onap.so.rest.service.HttpRestServiceProvider; import org.slf4j.Logger; @@ -29,11 +31,14 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Component; +import org.springframework.stereotype.Service; +import lombok.ToString; -@Component +@Service public class SubscribeSender { + public static final String SLASH = "/"; + private static final Logger logger = LoggerFactory.getLogger(SubscribeSender.class); @Value("${vnfm.subscription}") @@ -42,18 +47,37 @@ public class SubscribeSender { @Autowired private HttpRestServiceProvider restProvider; - public boolean send(final EsrSystemInfo info, final LccnSubscriptionRequest request) { - final ResponseEntity<String> response = restProvider.postHttpRequest(request, getUrl(info), String.class); + public String send(final EsrSystemInfo info, final LccnSubscriptionRequest request) throws VeVnfmException { + final ResponseEntity<SubscribeToManoResponse> response = + restProvider.postHttpRequest(request, getUrl(info), SubscribeToManoResponse.class); final HttpStatus statusCode = response.getStatusCode(); - final String body = response.getBody(); + final SubscribeToManoResponse body = response.getBody(); logger.info("The VNFM replied with the code {} and the body {}", statusCode, body); - return HttpStatus.CREATED == statusCode; + if (HttpStatus.CREATED != statusCode) { + throw new VeVnfmException("The status code was different than " + HttpStatus.CREATED); + } + + return body.id; + } + + public boolean check(final EsrSystemInfo info, final String id) { + final ResponseEntity<SubscribeToManoResponse> response = + restProvider.getHttpResponse(getUrl(info) + SLASH + id, SubscribeToManoResponse.class); + return response.getBody() != null && response.getBody().id.equals(id); } private String getUrl(final EsrSystemInfo info) { return info.getServiceUrl() + vnfmSubscription; } + + @ToString + static class SubscribeToManoResponse { + @JsonProperty("id") + String id; + @JsonProperty("callbackUri") + String callbackUri; + } } diff --git a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/service/SubscriberService.java b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/service/SubscriberService.java index eefd9ba93b..9760584d7a 100644 --- a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/service/SubscriberService.java +++ b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/service/SubscriberService.java @@ -22,9 +22,10 @@ package org.onap.so.adapters.vevnfm.service; import com.squareup.okhttp.Credentials; import java.util.Collections; +import org.apache.logging.log4j.util.Strings; import org.onap.aai.domain.yang.EsrSystemInfo; +import org.onap.so.adapters.vevnfm.exception.VeVnfmException; import org.onap.so.adapters.vevnfm.provider.AuthorizationHeadersProvider; -import org.onap.so.adapters.vevnfm.subscription.SubscribeSender; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.LccnSubscriptionRequest; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.SubscriptionsAuthentication; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.SubscriptionsAuthenticationParamsBasic; @@ -35,16 +36,11 @@ import org.springframework.stereotype.Service; @Service public class SubscriberService { - private static final char COLON = ':'; + @Value("${vevnfmadapter.endpoint}") + private String endpoint; - @Value("${system.url}") - private String systemUrl; - - @Value("${server.port}") - private String serverPort; - - @Value("${notification.url}") - private String notificationUrl; + @Value("${vnfm.notification}") + private String notification; @Value("${spring.security.usercredentials[0].username}") private String username; @@ -59,19 +55,40 @@ public class SubscriberService { private SubscribeSender sender; private static String getAuthorization(final EsrSystemInfo info) { - return Credentials.basic(info.getUserName(), info.getPassword()); + if (info == null) { + return null; + } + + final String userName = info.getUserName(); + + if (Strings.isBlank(userName)) { + return null; + } + + final String password = info.getPassword(); + return Credentials.basic(userName, password); } - public boolean subscribe(final EsrSystemInfo info) { + public String subscribe(final EsrSystemInfo info) throws VeVnfmException { try { headersProvider.addAuthorization(getAuthorization(info)); final LccnSubscriptionRequest request = createRequest(); return sender.send(info, request); + } catch (Exception e) { + throw new VeVnfmException(e); } finally { headersProvider.removeAuthorization(); } } + public boolean checkSubscription(final EsrSystemInfo info, final String id) throws VeVnfmException { + try { + return sender.check(info, id); + } catch (Exception e) { + throw new VeVnfmException(e); + } + } + private LccnSubscriptionRequest createRequest() { final LccnSubscriptionRequest request = new LccnSubscriptionRequest(); request.callbackUri(getCallbackUri()); @@ -87,6 +104,6 @@ public class SubscriberService { } private String getCallbackUri() { - return systemUrl + COLON + serverPort + notificationUrl; + return endpoint + notification; } } diff --git a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/service/SubscriptionScheduler.java b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/service/SubscriptionScheduler.java new file mode 100644 index 0000000000..16427437fc --- /dev/null +++ b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/service/SubscriptionScheduler.java @@ -0,0 +1,71 @@ +/*- + * ============LICENSE_START======================================================= + * SO + * ================================================================================ + * Copyright (C) 2020 Samsung. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.vevnfm.service; + +import org.onap.aai.domain.yang.EsrSystemInfo; +import org.onap.so.adapters.vevnfm.exception.VeVnfmException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +@Service +@EnableScheduling +public class SubscriptionScheduler { + + private static final Logger logger = LoggerFactory.getLogger(SubscriptionScheduler.class); + + @Autowired + private SubscriberService subscriberService; + + private String subscribedId; + + private EsrSystemInfo info; + + public void setInfo(final EsrSystemInfo info) { + this.info = info; + } + + @Scheduled(fixedRate = 5000, initialDelay = 2000) + void subscribeTask() throws VeVnfmException { + if (info != null) { + if (subscribedId == null) { + logger.info("Starting subscribe task"); + subscribedId = subscriberService.subscribe(info); + } + } + } + + @Scheduled(fixedRate = 20000) + void checkSubscribeTask() throws VeVnfmException { + if (info != null) { + if (subscribedId != null) { + logger.info("Checking subscription: {}", subscribedId); + if (!subscriberService.checkSubscription(info, subscribedId)) { + logger.info("Subscription {} not available", subscribedId); + subscribedId = null; + } + } + } + } +} diff --git a/adapters/mso-ve-vnfm-adapter/src/main/resources/application.yaml b/adapters/mso-ve-vnfm-adapter/src/main/resources/application.yaml index 35871c51ac..72198b83c1 100644 --- a/adapters/mso-ve-vnfm-adapter/src/main/resources/application.yaml +++ b/adapters/mso-ve-vnfm-adapter/src/main/resources/application.yaml @@ -15,13 +15,10 @@ # limitations under the License. server: - port: 8080 + port: 9098 -system: - url: http://localhost - -notification: - url: /lcm/v1/vnf/instances/notifications +vevnfmadapter: + endpoint: http://so-ve-vnfm-adapter.onap:9098 mso: key: 07a7159d3bf51a0e53be7a8f89699be7 @@ -31,10 +28,12 @@ aai: auth: 75C4483F9C05E2C33A8602635FA532397EC44AB667A2B64DED4FEE08DD932F2E3C1FEE vnfm: + default-endpoint: https://so-vnfm-simulator.onap:9093 subscription: /vnflcm/v1/subscriptions + notification: /lcm/v1/vnf/instances/notifications dmaap: - endpoint: http://message-router:30227 + endpoint: http://message-router.onap:30227 topic: /events/unauthenticated.DCAE_CL_OUTPUT spring: diff --git a/adapters/mso-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/controller/NotificationControllerTest.java b/adapters/mso-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/controller/NotificationControllerTest.java index 57638a165a..974e6ec544 100644 --- a/adapters/mso-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/controller/NotificationControllerTest.java +++ b/adapters/mso-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/controller/NotificationControllerTest.java @@ -53,8 +53,8 @@ public class NotificationControllerTest { private static final String MINIMAL_JSON_CONTENT = "{}"; private static final int ZERO = 0; - @Value("${notification.url}") - private String notificationUrl; + @Value("${vnfm.notification}") + private String notification; @Autowired private WebApplicationContext webApplicationContext; @@ -74,7 +74,7 @@ public class NotificationControllerTest { @Test public void testReceiveNotification() throws Exception { // given - final MockHttpServletRequestBuilder request = MockMvcRequestBuilders.post(notificationUrl) + final MockHttpServletRequestBuilder request = MockMvcRequestBuilders.post(notification) .contentType(MediaType.APPLICATION_JSON).content(MINIMAL_JSON_CONTENT); mockRestServer.expect(once(), anything()).andRespond(withSuccess()); diff --git a/adapters/mso-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/provider/AuthorizationHeadersProviderTest.java b/adapters/mso-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/provider/AuthorizationHeadersProviderTest.java index 64503ddfc2..f9ae427086 100644 --- a/adapters/mso-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/provider/AuthorizationHeadersProviderTest.java +++ b/adapters/mso-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/provider/AuthorizationHeadersProviderTest.java @@ -28,6 +28,8 @@ import org.springframework.http.HttpHeaders; public class AuthorizationHeadersProviderTest { private static final String AUTHORIZATION_EXAMPLE = "authorization"; + private static final String BLANK_EXAMPLE = "\t\n"; + private static final String EMPTY = ""; private final AuthorizationHeadersProvider provider = new AuthorizationHeadersProvider(); @@ -44,4 +46,41 @@ public class AuthorizationHeadersProviderTest { assertEquals(size, headers.size()); assertFalse(headers.containsKey(AUTHORIZATION_HEADER)); } + + @Test + public void testBlankAuthorization() { + final HttpHeaders headers = provider.getHttpHeaders(); + final int size = headers.size(); + + provider.addAuthorization(BLANK_EXAMPLE); + assertEquals(size, headers.size()); + } + + @Test + public void testEmptyAuthorization() { + final HttpHeaders headers = provider.getHttpHeaders(); + final int size = headers.size(); + + provider.addAuthorization(EMPTY); + assertEquals(size, headers.size()); + } + + @Test + public void testNullAuthorization() { + final HttpHeaders headers = provider.getHttpHeaders(); + final int size = headers.size(); + + provider.addAuthorization(null); + assertEquals(size, headers.size()); + } + + @Test + public void testRemoveAuthorization() { + final HttpHeaders headers = provider.getHttpHeaders(); + final int size = headers.size(); + + provider.removeAuthorization(); + provider.removeAuthorization(); + assertEquals(size, headers.size()); + } } diff --git a/adapters/mso-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/service/StartupServiceTest.java b/adapters/mso-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/service/StartupServiceTest.java index 0f9c23e261..d1d34a706f 100644 --- a/adapters/mso-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/service/StartupServiceTest.java +++ b/adapters/mso-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/service/StartupServiceTest.java @@ -20,7 +20,9 @@ package org.onap.so.adapters.vevnfm.service; -import static org.mockito.Mockito.*; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -30,62 +32,34 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.onap.aai.domain.yang.EsrSystemInfo; import org.onap.so.adapters.vevnfm.aai.AaiConnection; -import org.onap.so.adapters.vevnfm.exception.VeVnfmException; @RunWith(MockitoJUnitRunner.class) public class StartupServiceTest { - @Mock - private AaiConnection aaiConnection; + private static final String URL = "rt"; + + @Rule + public ExpectedException thrown = ExpectedException.none(); @Mock - private SubscriberService subscriberService; + private AaiConnection aaiConnection; @InjectMocks private StartupService startupService; - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void testSuccess() throws Exception { // given final EsrSystemInfo info = new EsrSystemInfo(); - info.setServiceUrl("lh"); - when(aaiConnection.receiveVnfm()).thenReturn(info); - when(subscriberService.subscribe(info)).thenReturn(true); - - // when - startupService.run(); - - // then - verify(aaiConnection, times(1)).receiveVnfm(); - verify(subscriberService, times(1)).subscribe(info); - } + info.setServiceUrl(URL); - @Test - public void testFailureAai() throws Exception { - // given - final EsrSystemInfo info = new EsrSystemInfo(); when(aaiConnection.receiveVnfm()).thenReturn(info); - thrown.expect(VeVnfmException.class); - // when - startupService.run(); - } - - @Test - public void testFailureSubscriber() throws Exception { - // given - final EsrSystemInfo info = new EsrSystemInfo(); - info.setServiceUrl("lh"); - when(aaiConnection.receiveVnfm()).thenReturn(info); - when(subscriberService.subscribe(info)).thenReturn(false); + final EsrSystemInfo systemInfo = startupService.receiveVnfm(); - thrown.expect(VeVnfmException.class); - - // when - startupService.run(); + // then + verify(aaiConnection).receiveVnfm(); + assertEquals(info, systemInfo); } } diff --git a/adapters/mso-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/subscription/SubscribeSenderTest.java b/adapters/mso-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/service/SubscribeSenderTest.java index d1fda0eee6..b7f1f982a2 100644 --- a/adapters/mso-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/subscription/SubscribeSenderTest.java +++ b/adapters/mso-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/service/SubscribeSenderTest.java @@ -18,9 +18,10 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.adapters.vevnfm.subscription; +package org.onap.so.adapters.vevnfm.service; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertEquals; +import static org.onap.so.adapters.vevnfm.service.SubscribeSender.SLASH; import static org.springframework.http.HttpHeaders.CONTENT_TYPE; import static org.springframework.test.web.client.ExpectedCount.once; import static org.springframework.test.web.client.match.MockRestRequestMatchers.*; @@ -33,6 +34,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.onap.aai.domain.yang.EsrSystemInfo; import org.onap.so.adapters.vevnfm.configuration.StartupConfiguration; +import org.onap.so.adapters.vevnfm.exception.VeVnfmException; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.LccnSubscriptionRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -50,8 +52,9 @@ import org.springframework.web.client.RestTemplate; @ActiveProfiles(StartupConfiguration.TEST_PROFILE) public class SubscribeSenderTest { - private static final String SLASH = "/"; - private static final String MINIMAL_JSON_CONTENT = "{}"; + private static final String URL = "lh"; + private static final String ID = "1a2s3d4f"; + private static final String JSON = "{\"id\":\"" + ID + "\"}"; private static final Gson GSON; @@ -78,22 +81,22 @@ public class SubscribeSenderTest { } @Test - public void testSuccess() { + public void testSuccess() throws VeVnfmException { // given final EsrSystemInfo info = new EsrSystemInfo(); - info.setServiceUrl("lh"); + info.setServiceUrl(URL); final LccnSubscriptionRequest request = new LccnSubscriptionRequest(); mockRestServer.expect(once(), requestTo(SLASH + info.getServiceUrl() + vnfmSubscription)) .andExpect(header(CONTENT_TYPE, CoreMatchers.containsString(MediaType.APPLICATION_JSON_VALUE))) .andExpect(method(HttpMethod.POST)).andExpect(content().json(GSON.toJson(request))) - .andRespond(withStatus(HttpStatus.CREATED).body(MINIMAL_JSON_CONTENT)); + .andRespond(withStatus(HttpStatus.CREATED).body(JSON).contentType(MediaType.APPLICATION_JSON)); // when - final boolean done = sender.send(info, request); + final String id = sender.send(info, request); // then - assertTrue(done); mockRestServer.verify(); + assertEquals(ID, id); } } diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/activity/ActivitySpecsActions.java b/asdc-controller/src/main/java/org/onap/so/asdc/activity/ActivitySpecsActions.java index 06887f1253..a48e1770f0 100644 --- a/asdc-controller/src/main/java/org/onap/so/asdc/activity/ActivitySpecsActions.java +++ b/asdc-controller/src/main/java/org/onap/so/asdc/activity/ActivitySpecsActions.java @@ -4,12 +4,15 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (c) 2020 Nokia + * ================================================================================ + * * 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. @@ -29,7 +32,6 @@ import org.onap.so.asdc.activity.beans.ActivitySpec; import org.onap.so.asdc.activity.beans.ActivitySpecCreateResponse; import org.onap.so.client.HttpClient; import org.onap.so.client.HttpClientFactory; -import org.onap.so.logger.LoggingAnchor; import org.onap.logging.filter.base.ONAPComponents; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -53,8 +55,6 @@ public class ActivitySpecsActions { return null; } - String activitySpecId = null; - try { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL); @@ -71,30 +71,34 @@ public class ActivitySpecsActions { int statusCode = response.getStatus(); if (statusCode == HttpStatus.SC_UNPROCESSABLE_ENTITY) { logger.warn(LoggingAnchor.THREE, "ActivitySpec", activitySpec.getName(), "already exists in SDC"); - } else if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED) { + return null; + } + if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED) { logger.warn(LoggingAnchor.THREE, "Error creating activity spec", activitySpec.getName(), statusCode); - } else { - if (response.getEntity() != null) { - ActivitySpecCreateResponse activitySpecCreateResponse = - response.readEntity(ActivitySpecCreateResponse.class); - if (activitySpecCreateResponse != null) { - activitySpecId = activitySpecCreateResponse.getId(); - } else { - logger.warn(LoggingAnchor.TWO, "Unable to read activity spec", activitySpec.getName()); - } - } else { - logger.warn(LoggingAnchor.TWO, "No activity spec response returned", activitySpec.getName()); - } + return null; + } + + if (response.getEntity() == null) { + logger.warn(LoggingAnchor.TWO, "No activity spec response returned", activitySpec.getName()); + return null; } + ActivitySpecCreateResponse activitySpecCreateResponse = + response.readEntity(ActivitySpecCreateResponse.class); + if (activitySpecCreateResponse == null) { + logger.warn(LoggingAnchor.TWO, "Unable to read activity spec", activitySpec.getName()); + return null; + } + return activitySpecCreateResponse.getId(); + + } catch (Exception e) { logger.warn(LoggingAnchor.TWO, "Exception creating activitySpec", e); } - return activitySpecId; + return null; } public boolean certifyActivitySpec(String hostname, String activitySpecId) { - boolean certificationResult = false; if (activitySpecId == null) { return false; } @@ -114,16 +118,19 @@ public class ActivitySpecsActions { if (statusCode == HttpStatus.SC_UNPROCESSABLE_ENTITY) { logger.warn(LoggingAnchor.THREE, "ActivitySpec with id", activitySpecId, "is already certified in SDC"); - } else if (statusCode != HttpStatus.SC_OK) { + return false; + } + if (statusCode != HttpStatus.SC_OK) { logger.warn(LoggingAnchor.THREE, "Error certifying activity", activitySpecId, statusCode); - } else { - certificationResult = true; + return false; } + return true; + } catch (Exception e) { logger.warn(LoggingAnchor.TWO, "Exception certifying activitySpec", e); + return false; } - return certificationResult; } } diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/activity/DeployActivitySpecs.java b/asdc-controller/src/main/java/org/onap/so/asdc/activity/DeployActivitySpecs.java index e53b792a74..df8e828a16 100644 --- a/asdc-controller/src/main/java/org/onap/so/asdc/activity/DeployActivitySpecs.java +++ b/asdc-controller/src/main/java/org/onap/so/asdc/activity/DeployActivitySpecs.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (c) 2020 Nokia + * ================================================================================ * 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. @@ -74,17 +76,19 @@ public class DeployActivitySpecs { logger.debug("{} {}", "Attempting to create activity ", activitySpecFromCatalog.getName()); ActivitySpec activitySpec = mapActivitySpecFromCatalogToSdc(activitySpecFromCatalog); String activitySpecId = activitySpecsActions.createActivitySpec(hostname, activitySpec); - if (activitySpecId != null) { - logger.info(LoggingAnchor.TWO, "Successfully created activitySpec", activitySpec.getName()); - boolean certificationResult = activitySpecsActions.certifyActivitySpec(hostname, activitySpecId); - if (certificationResult) { - logger.info(LoggingAnchor.TWO, "Successfully certified activitySpec", activitySpec.getName()); - } else { - logger.info(LoggingAnchor.TWO, "Failed to certify activitySpec", activitySpec.getName()); - } - } else { + if (activitySpecId == null) { logger.info(LoggingAnchor.TWO, "Failed to create activitySpec", activitySpec.getName()); + continue; + } + + logger.info(LoggingAnchor.TWO, "Successfully created activitySpec", activitySpec.getName()); + boolean certificationResult = activitySpecsActions.certifyActivitySpec(hostname, activitySpecId); + if (!certificationResult) { + logger.info(LoggingAnchor.TWO, "Failed to certify activitySpec", activitySpec.getName()); + continue; } + + logger.info(LoggingAnchor.TWO, "Successfully certified activitySpec", activitySpec.getName()); } } @@ -120,46 +124,41 @@ public class DeployActivitySpecs { List<Input> inputs = new ArrayList<>(); List<Output> outputs = new ArrayList<>(); for (ActivitySpecActivitySpecParameters activitySpecParam : activitySpecActivitySpecParameters) { - if (activitySpecParam != null) { - if (activitySpecParam.getActivitySpecParameters() != null) { - ActivitySpecParameters activitySpecParameters = activitySpecParam.getActivitySpecParameters(); - if (activitySpecParameters != null) { - if (activitySpecParameters.getDirection().equals(DIRECTION_INPUT)) { - Input input = new Input(); - input.setName(activitySpecParameters.getName()); - input.setType(activitySpecParameters.getType()); - inputs.add(input); - } else if (activitySpecParameters.getDirection().equals(DIRECTION_OUTPUT)) { - Output output = new Output(); - output.setName(activitySpecParameters.getName()); - output.setType(activitySpecParameters.getType()); - outputs.add(output); - } - } - } + if (activitySpecParam == null || activitySpecParam.getActivitySpecParameters() == null) { + continue; + } + ActivitySpecParameters activitySpecParameters = activitySpecParam.getActivitySpecParameters(); + + if (activitySpecParameters.getDirection().equals(DIRECTION_INPUT)) { + Input input = new Input(); + input.setName(activitySpecParameters.getName()); + input.setType(activitySpecParameters.getType()); + inputs.add(input); + continue; + } + if (activitySpecParameters.getDirection().equals(DIRECTION_OUTPUT)) { + Output output = new Output(); + output.setName(activitySpecParameters.getName()); + output.setType(activitySpecParameters.getType()); + outputs.add(output); } } activitySpec.setInputs(inputs); activitySpec.setOutputs(outputs); - return; } public boolean checkHttpServerUp(String host) { - URL url = null; - boolean isUp = false; - - int responseCode = 0; try { - url = new URL(host); + URL url = new URL(host); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(5000); - responseCode = connection.getResponseCode(); + int responseCode = connection.getResponseCode(); + if (responseCode == HttpStatus.SC_OK || responseCode == HttpStatus.SC_NOT_FOUND) { + return true; + } } catch (Exception e) { logger.warn("Exception on connecting to SDC WFD endpoint: ", e); } - if (responseCode == HttpStatus.SC_OK || responseCode == HttpStatus.SC_NOT_FOUND) { - isUp = true; - } - return isUp; + return false; } } diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCController.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCController.java index f64adfd760..c9d4f4d92f 100644 --- a/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCController.java +++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCController.java @@ -7,6 +7,8 @@ * ================================================================================ * Modifications Copyright (c) 2019 Samsung * ================================================================================ + * Modifications Copyright (c) 2020 Nokia + * ================================================================================ * 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 @@ -33,6 +35,7 @@ import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; import java.nio.file.Paths; import java.util.List; import java.util.Optional; @@ -162,12 +165,7 @@ public class ASDCController { break; case IDLE: - if (this.nbOfNotificationsOngoing > 1) { - --this.nbOfNotificationsOngoing; - } else { - this.nbOfNotificationsOngoing = 0; - this.controllerStatus = newControllerStatus; - } + changeOnStatusIDLE(newControllerStatus); break; default: @@ -177,6 +175,15 @@ public class ASDCController { } } + private void changeOnStatusIDLE(ASDCControllerStatus newControllerStatus) { + if (this.nbOfNotificationsOngoing > 1) { + --this.nbOfNotificationsOngoing; + } else { + this.nbOfNotificationsOngoing = 0; + this.controllerStatus = newControllerStatus; + } + } + public ASDCControllerStatus getControllerStatus() { return this.controllerStatus; } @@ -296,13 +303,12 @@ public class ASDCController { protected void notifyErrorToAsdc(INotificationData iNotif, ToscaResourceStructure toscaResourceStructure, DistributionStatusEnum deployStatus, VfResourceStructure resourceStructure, String errorMessage) { // do csar lever first - this.sendCsarDeployNotification(iNotif, resourceStructure, toscaResourceStructure, deployStatus, errorMessage); + this.sendCsarDeployNotification(resourceStructure, toscaResourceStructure, deployStatus, errorMessage); // at resource level for (IResourceInstance resource : iNotif.getResources()) { resourceStructure = new VfResourceStructure(iNotif, resource); errorMessage = String.format("Resource with UUID: %s already exists", resource.getResourceUUID()); - this.sendCsarDeployNotification(iNotif, resourceStructure, toscaResourceStructure, deployStatus, - errorMessage); + this.sendCsarDeployNotification(resourceStructure, toscaResourceStructure, deployStatus, errorMessage); } } @@ -363,8 +369,7 @@ public class ASDCController { if (DistributionActionResultEnum.SUCCESS.equals(downloadResult.getDistributionActionResult())) { logger.info(LoggingAnchor.FOUR, MessageEnum.ASDC_ARTIFACT_DOWNLOAD_SUC.toString(), - artifact.getArtifactURL(), artifact.getArtifactUUID(), - String.valueOf(downloadResult.getArtifactPayload().length)); + artifact.getArtifactURL(), artifact.getArtifactUUID(), downloadResult.getArtifactPayload().length); } else { logger.error(LoggingAnchor.SEVEN, MessageEnum.ASDC_ARTIFACT_DOWNLOAD_FAIL.toString(), @@ -447,7 +452,7 @@ public class ASDCController { } } - protected void sendCsarDeployNotification(INotificationData iNotif, ResourceStructure resourceStructure, + protected void sendCsarDeployNotification(ResourceStructure resourceStructure, ToscaResourceStructure toscaResourceStructure, DistributionStatusEnum statusEnum, String errorReason) { IArtifactInfo csarArtifact = toscaResourceStructure.getToscaArtifact(); @@ -471,8 +476,8 @@ public class ASDCController { } catch (ArtifactInstallerException e) { logger.info(LoggingAnchor.SIX, MessageEnum.ASDC_ARTIFACT_DOWNLOAD_FAIL.toString(), resourceStructure.getResourceInstance().getResourceName(), - resourceStructure.getResourceInstance().getResourceUUID(), - String.valueOf(resourceStructure.getNumberOfResources()), "ASDC", "deployResourceStructure"); + resourceStructure.getResourceInstance().getResourceUUID(), resourceStructure.getNumberOfResources(), + "ASDC", "deployResourceStructure"); sendDeployNotificationsForResource(resourceStructure, DistributionStatusEnum.DEPLOY_ERROR, e.getMessage()); throw e; } @@ -480,8 +485,8 @@ public class ASDCController { if (resourceStructure.isDeployedSuccessfully() || toscaResourceStructure.isDeployedSuccessfully()) { logger.info(LoggingAnchor.SIX, MessageEnum.ASDC_ARTIFACT_DEPLOY_SUC.toString(), resourceStructure.getResourceInstance().getResourceName(), - resourceStructure.getResourceInstance().getResourceUUID(), - String.valueOf(resourceStructure.getNumberOfResources()), "ASDC", "deployResourceStructure"); + resourceStructure.getResourceInstance().getResourceUUID(), resourceStructure.getNumberOfResources(), + "ASDC", "deployResourceStructure"); sendDeployNotificationsForResource(resourceStructure, DistributionStatusEnum.DEPLOY_OK, null); } @@ -509,26 +514,10 @@ public class ASDCController { try { IDistributionStatusMessage message = new DistributionStatusMessage(artifactURL, consumerID, distributionID, status, timestamp); - - switch (notificationType) { - case DOWNLOAD: - if (errorReason != null) { - this.distributionClient.sendDownloadStatus(message, errorReason); - } else { - this.distributionClient.sendDownloadStatus(message); - } - - break; - case DEPLOY: - if (errorReason != null) { - this.distributionClient.sendDeploymentStatus(message, errorReason); - } else { - this.distributionClient.sendDeploymentStatus(message); - } - - break; - default: - break; + if (errorReason != null) { + sendNotificationWithMessageAndErrorReason(notificationType, errorReason, message); + } else { + sendNotificationWithMessage(notificationType, message); } } catch (RuntimeException e) { logger.warn(LoggingAnchor.FIVE, MessageEnum.ASDC_SEND_NOTIF_ASDC_EXEC.toString(), "ASDC", @@ -537,6 +526,33 @@ public class ASDCController { } } + private void sendNotificationWithMessage(NotificationType notificationType, IDistributionStatusMessage message) { + switch (notificationType) { + case DOWNLOAD: + this.distributionClient.sendDownloadStatus(message); + break; + case DEPLOY: + this.distributionClient.sendDeploymentStatus(message); + break; + default: + break; + } + } + + private void sendNotificationWithMessageAndErrorReason(NotificationType notificationType, String errorReason, + IDistributionStatusMessage message) { + switch (notificationType) { + case DOWNLOAD: + this.distributionClient.sendDownloadStatus(message, errorReason); + break; + case DEPLOY: + this.distributionClient.sendDeploymentStatus(message, errorReason); + break; + default: + break; + } + } + protected void sendFinalDistributionStatus(String distributionID, DistributionStatusEnum status, String errorReason) { @@ -587,8 +603,8 @@ public class ASDCController { for (IResourceInstance resource : iNotif.getResources()) { noOfArtifacts += resource.getArtifacts().size(); } - logger.info(LoggingAnchor.FOUR, MessageEnum.ASDC_RECEIVE_CALLBACK_NOTIF.toString(), - String.valueOf(noOfArtifacts), iNotif.getServiceUUID(), "ASDC"); + logger.info(LoggingAnchor.FOUR, MessageEnum.ASDC_RECEIVE_CALLBACK_NOTIF.toString(), noOfArtifacts, + iNotif.getServiceUUID(), "ASDC"); try { if (iNotif.getDistributionID() != null && !iNotif.getDistributionID().isEmpty()) { @@ -721,7 +737,6 @@ public class ASDCController { protected void processResourceNotification(INotificationData iNotif) { // For each artifact, create a structure describing the VFModule in a ordered flat level - ResourceStructure resourceStructure = null; String msoConfigPath = getMsoConfigPath(); ToscaResourceStructure toscaResourceStructure = new ToscaResourceStructure(msoConfigPath); DistributionStatusEnum deployStatus = DistributionStatusEnum.DEPLOY_OK; @@ -734,6 +749,7 @@ public class ASDCController { return; } + ResourceStructure resourceStructure = null; for (IResourceInstance resource : iNotif.getResources()) { String resourceType = resource.getResourceType(); @@ -741,21 +757,11 @@ public class ASDCController { logger.info("Processing Resource Type: {}, Model UUID: {}", resourceType, resource.getResourceUUID()); - if ("VF".equals(resourceType)) { - resourceStructure = new VfResourceStructure(iNotif, resource); - } else if ("PNF".equals(resourceType)) { - resourceStructure = new PnfResourceStructure(iNotif, resource); - } else { - // There are cases where the Service has no VF resources, those are handled here - logger.info("No resources found for Service: {}", iNotif.getServiceUUID()); - resourceStructure = new VfResourceStructure(iNotif, new ResourceInstance()); - resourceStructure.setResourceType(ResourceType.OTHER); - } + resourceStructure = getResourceStructure(iNotif, resource, resourceType); try { if (!this.checkResourceAlreadyDeployed(resourceStructure, serviceDeployed)) { - logger.debug("Processing Resource Type: " + resourceType + " and Model UUID: " + resourceStructure.getResourceInstance().getResourceUUID()); @@ -765,25 +771,27 @@ public class ASDCController { for (IArtifactInfo artifact : resource.getArtifacts()) { IDistributionClientDownloadResult resultArtifact = this.downloadTheArtifact(artifact, iNotif.getDistributionID()); - if (resultArtifact != null) { - - if (ASDCConfiguration.VF_MODULES_METADATA.equals(artifact.getArtifactType())) { - logger.debug("VF_MODULE_ARTIFACT: " - + new String(resultArtifact.getArtifactPayload(), "UTF-8")); - logger.debug(ASDCNotificationLogging - .dumpVfModuleMetaDataList(((VfResourceStructure) resourceStructure) - .decodeVfModuleArtifact(resultArtifact.getArtifactPayload()))); - } - if (!ASDCConfiguration.WORKFLOW.equals(artifact.getArtifactType())) { - resourceStructure.addArtifactToStructure(distributionClient, artifact, - resultArtifact); - } else { - writeArtifactToFile(artifact, resultArtifact); - logger.debug( - "Adding workflow artifact to structure: " + artifact.getArtifactName()); - resourceStructure.addWorkflowArtifactToStructure(artifact, resultArtifact); - } + if (resultArtifact == null) { + continue; } + + if (ASDCConfiguration.VF_MODULES_METADATA.equals(artifact.getArtifactType())) { + logger.debug("VF_MODULE_ARTIFACT: " + + new String(resultArtifact.getArtifactPayload(), StandardCharsets.UTF_8)); + logger.debug(ASDCNotificationLogging + .dumpVfModuleMetaDataList(((VfResourceStructure) resourceStructure) + .decodeVfModuleArtifact(resultArtifact.getArtifactPayload()))); + } + if (!ASDCConfiguration.WORKFLOW.equals(artifact.getArtifactType())) { + resourceStructure.addArtifactToStructure(distributionClient, artifact, + resultArtifact); + } else { + writeArtifactToFile(artifact, resultArtifact); + logger.debug( + "Adding workflow artifact to structure: " + artifact.getArtifactName()); + resourceStructure.addWorkflowArtifactToStructure(artifact, resultArtifact); + } + } // Deploy VF resource and artifacts @@ -817,8 +825,7 @@ public class ASDCController { } } - this.sendCsarDeployNotification(iNotif, resourceStructure, toscaResourceStructure, deployStatus, - errorMessage); + this.sendCsarDeployNotification(resourceStructure, toscaResourceStructure, deployStatus, errorMessage); } catch (ASDCDownloadException | UnsupportedEncodingException e) { logger.error(LoggingAnchor.SIX, MessageEnum.ASDC_GENERAL_EXCEPTION_ARG.toString(), @@ -827,6 +834,20 @@ public class ASDCController { } } + private ResourceStructure getResourceStructure(INotificationData iNotif, IResourceInstance resource, + String resourceType) { + if ("VF".equals(resourceType)) { + return new VfResourceStructure(iNotif, resource); + } + if ("PNF".equals(resourceType)) { + return new PnfResourceStructure(iNotif, resource); + } + logger.info("No resources found for Service: {}", iNotif.getServiceUUID()); + ResourceStructure resourceStructure = new VfResourceStructure(iNotif, new ResourceInstance()); + resourceStructure.setResourceType(ResourceType.OTHER); + return resourceStructure; + } + private String getMsoConfigPath() { String msoConfigPath = System.getProperty("mso.config.path"); if (msoConfigPath == null) { @@ -900,7 +921,6 @@ public class ASDCController { } - /** * @return the address of the ASDC we are connected to. */ diff --git a/asdc-controller/src/main/resources/resource-examples/resource_Extvl.csar b/asdc-controller/src/main/resources/resource-examples/resource_Extvl.csar Binary files differindex bd35b0ab60..20ce62b8de 100644 --- a/asdc-controller/src/main/resources/resource-examples/resource_Extvl.csar +++ b/asdc-controller/src/main/resources/resource-examples/resource_Extvl.csar diff --git a/asdc-controller/src/main/resources/resource-examples/service-ServiceFdnt-csar-0904-2.csar b/asdc-controller/src/main/resources/resource-examples/service-ServiceFdnt-csar-0904-2.csar Binary files differindex 29d30f8023..dd0115b716 100644 --- a/asdc-controller/src/main/resources/resource-examples/service-ServiceFdnt-csar-0904-2.csar +++ b/asdc-controller/src/main/resources/resource-examples/service-ServiceFdnt-csar-0904-2.csar diff --git a/asdc-controller/src/test/resources/resource-examples/WorkflowBpmn/service-VfZrdm5bpxmc02092017Service-csar.csar b/asdc-controller/src/test/resources/resource-examples/WorkflowBpmn/service-VfZrdm5bpxmc02092017Service-csar.csar Binary files differindex 4c906aba38..817b83135d 100644 --- a/asdc-controller/src/test/resources/resource-examples/WorkflowBpmn/service-VfZrdm5bpxmc02092017Service-csar.csar +++ b/asdc-controller/src/test/resources/resource-examples/WorkflowBpmn/service-VfZrdm5bpxmc02092017Service-csar.csar diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/GeneratePayloadForCds.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/GeneratePayloadForCds.java index 0766dae8e1..fb79880572 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/GeneratePayloadForCds.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/GeneratePayloadForCds.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2019 Bell Canada * ================================================================================ + * Modifications Copyright (c) 2020 Nordix + * ================================================================================ * 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 @@ -20,6 +22,7 @@ package org.onap.so.client.cds; +import org.camunda.bpm.engine.delegate.DelegateExecution; import org.onap.so.bpmn.common.BuildingBlockExecution; import org.onap.so.bpmn.servicedecomposition.entities.BuildingBlock; import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock; @@ -34,8 +37,9 @@ import java.util.UUID; public class GeneratePayloadForCds { private static final String ORIGINATOR_ID = "SO"; - private static final String MODE = "sync"; private static final String BUILDING_BLOCK = "buildingBlock"; + private static final String DEFAULT_SYNC_MODE = "sync"; + private static final String MSO_REQUEST_ID = "msoRequestId"; @Autowired private VnfCDSRequestProvider vnfCDSRequestProvider; @@ -49,8 +53,12 @@ public class GeneratePayloadForCds { @Autowired private ExtractPojosForBB extractPojosForBB; + @Autowired + private PnfCDSRequestProvider pnfCDSRequestProvider; + /** - * Build properties like (blueprint name, version, action etc..) along with the request payload. + * Build properties like (blueprint name, version, action etc..) along with the request payload for vnf, vf-module + * and service. * * @param execution - A building block execution object. * @return AbstractCDSPropertiesBean - A POJO which contains CDS related information. @@ -61,8 +69,9 @@ public class GeneratePayloadForCds { ExecuteBuildingBlock executeBuildingBlock = execution.getVariable(BUILDING_BLOCK); BuildingBlock buildingBlock = executeBuildingBlock.getBuildingBlock(); - String scope = buildingBlock.getBpmnScope(); - String action = buildingBlock.getBpmnAction(); + final String requestId = execution.getGeneralBuildingBlock().getRequestContext().getMsoRequestId(); + final String scope = buildingBlock.getBpmnScope(); + final String action = buildingBlock.getBpmnAction(); CDSRequestProvider requestProvider = getRequestProviderByScope(scope); @@ -71,7 +80,35 @@ public class GeneratePayloadForCds { final String requestPayload = requestProvider.buildRequestPayload(action) .orElseThrow(() -> new PayloadGenerationException("Failed to build payload for CDS")); - final String requestId = execution.getGeneralBuildingBlock().getRequestContext().getMsoRequestId(); + return prepareAndSetCdsPropertyBean(requestProvider, requestPayload, requestId, action, DEFAULT_SYNC_MODE); + } + + /** + * Build properties like (blueprint name, version, action etc..) along with the request payload for pnf. + * + * @param execution - A building block execution object. + * @return AbstractCDSPropertiesBean - A POJO which contains CDS related information. + * @throws PayloadGenerationException - Throw an exception if it fails to build payload for CDS. + */ + public AbstractCDSPropertiesBean buildCdsPropertiesBean(DelegateExecution execution) + throws PayloadGenerationException { + + final String scope = String.valueOf(execution.getVariable(PayloadConstants.SCOPE)); + final String action = String.valueOf(execution.getVariable(PayloadConstants.ACTION)); + final String requestId = String.valueOf(execution.getVariable(MSO_REQUEST_ID)); + final String mode = extractAndSetMode(execution); + + CDSRequestProvider requestProvider = getRequestProviderByScope(scope); + requestProvider.setExecutionObject(execution); + + final String requestPayload = requestProvider.buildRequestPayload(action) + .orElseThrow(() -> new PayloadGenerationException("Failed to build payload for CDS")); + + return prepareAndSetCdsPropertyBean(requestProvider, requestPayload, requestId, action, mode); + } + + private AbstractCDSPropertiesBean prepareAndSetCdsPropertyBean(CDSRequestProvider requestProvider, + String requestPayload, String requestId, String action, String mode) { final AbstractCDSPropertiesBean cdsPropertiesBean = new AbstractCDSPropertiesBean(); cdsPropertiesBean.setRequestObject(requestPayload); cdsPropertiesBean.setBlueprintName(requestProvider.getBlueprintName()); @@ -80,23 +117,34 @@ public class GeneratePayloadForCds { cdsPropertiesBean.setOriginatorId(ORIGINATOR_ID); cdsPropertiesBean.setSubRequestId(UUID.randomUUID().toString()); cdsPropertiesBean.setActionName(action); - cdsPropertiesBean.setMode(MODE); - + cdsPropertiesBean.setMode(mode); return cdsPropertiesBean; } + private String extractAndSetMode(DelegateExecution execution) { + String mode = DEFAULT_SYNC_MODE; + Object obj = execution.getVariable(PayloadConstants.MODE); + if (obj != null && !String.valueOf(obj).isEmpty()) { + mode = String.valueOf(obj); + } + return mode; + } + private CDSRequestProvider getRequestProviderByScope(String scope) throws PayloadGenerationException { CDSRequestProvider requestProvider; switch (scope) { - case "vnf": + case PayloadConstants.VNF_SCOPE: requestProvider = vnfCDSRequestProvider; break; - case "vfModule": + case PayloadConstants.VF_MODULE_SCOPE: requestProvider = vfModuleCDSRequestProvider; break; - case "service": + case PayloadConstants.SERVICE_SCOPE: requestProvider = serviceCDSRequestProvider; break; + case PayloadConstants.PNF_SCOPE: + requestProvider = pnfCDSRequestProvider; + break; default: throw new PayloadGenerationException("No scope defined with " + scope); } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/PayloadConstants.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/PayloadConstants.java index e758f548f7..808d427d65 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/PayloadConstants.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/PayloadConstants.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2019 Bell Canada * ================================================================================ + * Modifications Copyright (C) 2020 Nordix + * ================================================================================ * 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 @@ -30,5 +32,22 @@ public final class PayloadConstants { public static final String PROPERTIES = "properties"; public static final String SCOPE = "scope"; public static final String ACTION = "action"; + public static final String MODE = "mode"; public static final String SEPARATOR = "-"; + public static final String PNF_SCOPE = "pnf"; + public static final String VNF_SCOPE = "vnf"; + public static final String VF_MODULE_SCOPE = "vfModule"; + public static final String SERVICE_SCOPE = "service"; + public static final String RESOLUTION_KEY = "resolution-key"; + public static final String CDS_ACTOR = "cds"; + + public static final String PRC_BLUEPRINT_NAME = "PRC_blueprintName"; + public static final String PRC_BLUEPRINT_VERSION = "PRC_blueprintVersion"; + public static final String PRC_CUSTOMIZATION_UUID = "PRC_customizationUuid"; + public static final String PRC_TARGET_SOFTWARE_VERSION = "targetSoftwareVersion"; + + public final static String PNF_CORRELATION_ID = "pnfCorrelationId"; + public final static String PNF_UUID = "pnfUuid"; + public final static String SERVICE_INSTANCE_ID = "serviceInstanceId"; + public final static String MODEL_UUID = "modelUuid"; } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/PnfCDSRequestProvider.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/PnfCDSRequestProvider.java new file mode 100644 index 0000000000..86bca755ed --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/PnfCDSRequestProvider.java @@ -0,0 +1,78 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix + * ================================================================================ + * 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.so.client.cds; + +import com.google.gson.JsonObject; +import org.camunda.bpm.engine.delegate.DelegateExecution; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; +import java.util.Optional; +import static org.onap.so.client.cds.PayloadConstants.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class PnfCDSRequestProvider implements CDSRequestProvider { + private String blueprintName; + private String blueprintVersion; + private DelegateExecution execution; + + @Override + public String getBlueprintName() { + return blueprintName; + } + + @Override + public String getBlueprintVersion() { + return blueprintVersion; + } + + @Override + public <T> void setExecutionObject(T executionObject) { + execution = (DelegateExecution) executionObject; + } + + @Override + public Optional<String> buildRequestPayload(String action) { + + final JsonObject pnfObject = new JsonObject(); + final String resolutionKey = String.valueOf(execution.getVariable(PNF_CORRELATION_ID)); + blueprintName = String.valueOf(execution.getVariable(PRC_BLUEPRINT_NAME)); + blueprintVersion = String.valueOf(execution.getVariable(PRC_BLUEPRINT_VERSION)); + + extractAndSetExecutionVariable("service-instance-id", SERVICE_INSTANCE_ID, pnfObject); + extractAndSetExecutionVariable("service-model-uuid", MODEL_UUID, pnfObject); + extractAndSetExecutionVariable("pnf-id", PNF_UUID, pnfObject); + extractAndSetExecutionVariable("pnf-name", PNF_CORRELATION_ID, pnfObject); + extractAndSetExecutionVariable("pnf-customization-uuid", PRC_CUSTOMIZATION_UUID, pnfObject); + extractAndSetExecutionVariable("target-software-version", PRC_TARGET_SOFTWARE_VERSION, pnfObject); + + final JsonObject cdsPropertyObject = new JsonObject(); + cdsPropertyObject.addProperty(RESOLUTION_KEY, resolutionKey); + cdsPropertyObject.add(action + SEPARATOR + PROPERTIES, pnfObject); + + return Optional.of(buildRequestJsonObject(cdsPropertyObject, action)); + } + + private void extractAndSetExecutionVariable(String jsonProperty, String executionProperty, JsonObject pnfObject) { + if (execution.getVariable(executionProperty) != null) { + pnfObject.addProperty(jsonProperty, String.valueOf(execution.getVariable(executionProperty))); + } + } +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/GeneratePayloadForCdsTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/GeneratePayloadForCdsTest.java index 471bdb74fc..24962a0c14 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/GeneratePayloadForCdsTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/GeneratePayloadForCdsTest.java @@ -19,9 +19,6 @@ */ package org.onap.so.client.cds; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.gson.JsonParser; import org.camunda.bpm.engine.delegate.DelegateExecution; import org.camunda.bpm.extension.mockito.delegate.DelegateExecutionFake; import org.junit.Before; @@ -30,7 +27,6 @@ import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; -import org.omg.Messaging.SYNC_WITH_TRANSPORT; import org.onap.so.bpmn.common.BuildingBlockExecution; import org.onap.so.bpmn.common.DelegateExecutionImpl; import org.onap.so.bpmn.servicedecomposition.entities.BuildingBlock; @@ -38,28 +34,19 @@ import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock; import org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock; import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestContext; import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestParameters; -import org.onap.so.bpmn.servicedecomposition.tasks.ExtractPojosForBB; import org.onap.so.client.cds.beans.AbstractCDSPropertiesBean; -import org.onap.so.client.exception.BBObjectNotFoundException; import org.onap.so.client.exception.PayloadGenerationException; import org.onap.so.serviceinstancebeans.*; import java.util.*; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.ThrowableAssert.catchThrowable; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; @RunWith(MockitoJUnitRunner.Silent.class) public class GeneratePayloadForCdsTest { - private static final String GENERIC_VNF_ID = "vnfId_configVnfTest1"; - private static final String VF_MODULE_ID = "vf-module-id-1"; - private static final String VF_MODULE_NAME = "vf-module-name-1"; private static final String VF_MODULE_CUSTOMIZATION_UUID = "23ce9ac4-e5dd-11e9-81b4-2a2ae2dbcce1"; - private static final String GENERIC_VNF_NAME = "vnf-name-1"; - private static final String SERVICE_INSTANCE_ID = "serviceInst_configTest"; - private static final String SERVICE_MODEL_UUID = "b45b5780-e5dd-11e9-81b4-2a2ae2dbcce4"; - private static final String SERVICE_INSTANCE_NAME = "test-service-instance"; private static final String VNF_MODEL_CUSTOMIZATION_UUID = "23ce9ac4-e5dd-11e9-81b4-2a2ae2dbcce4"; private static final String GENERAL_BLOCK_EXECUTION_MAP_KEY = "gBBInput"; private static final String VNF_SCOPE = "vnf"; @@ -68,10 +55,34 @@ public class GeneratePayloadForCdsTest { private static final String VF_SCOPE = "vfModule"; private static final String ASSIGN_ACTION = "configAssign"; private static final String DEPLOY_ACTION = "configDeploy"; + private static final String DOWNLOAD_ACTION = "downloadNeSw"; private static final String MSO_REQUEST_ID = "1234"; private static final String BUILDING_BLOCK = "buildingBlock"; private static final String PUBLIC_NET_ID = "public-net-id"; private static final String CLOUD_REGION = "acl-cloud-region"; + private static final String TEST_MODEL_UUID = "6bc0b04d-1873-4721-b53d-6615225b2a28"; + private static final String TEST_SERVICE_INSTANCE_ID = "test_service_id"; + private static final String TEST_PROCESS_KEY = "processKey1"; + private static final String TEST_PNF_RESOURCE_INSTANCE_NAME = "PNF_demo_resource"; + private static final String TEST_PNF_CORRELATION_ID = "PNFDemo"; + private static final String TEST_PNF_RESOURCE_CUSTOMIZATION_UUID = "9acb3a83-8a52-412c-9a45-901764938144"; + private static final String TEST_MSO_REQUEST_ID = "ff874603-4222-11e7-9252-005056850d2e"; + private static final String TEST_PNF_UUID = "5df8b6de-2083-11e7-93ae-92361f002671"; + private static final String TEST_SOFTWARE_VERSION = "demo-sw-ver2.0.0"; + private static final String PNF_CORRELATION_ID = "pnfCorrelationId"; + private static final String PNF_UUID = "pnfUuid"; + private static final String SERVICE_INSTANCE_ID = "serviceInstanceId"; + private static final String MODEL_UUID = "modelUuid"; + private static final String PRC_CUSTOMIZATION_UUID = "PRC_customizationUuid"; + private static final String PRC_INSTANCE_NAME = "PRC_instanceName"; + private static final String PRC_TARGET_SOFTWARE_VERSION = "targetSoftwareVersion"; + private static final String SCOPE = "scope"; + private static final String ACTION = "action"; + private static final String PROCESS_KEY = "testProcessKey"; + private static final String PRC_BLUEPRINT_NAME = "PRC_blueprintName"; + private static final String PRC_BLUEPRINT_VERSION = "PRC_blueprintVersion"; + private static final String TEST_PNF_RESOURCE_BLUEPRINT_NAME = "blueprintOnap"; + private static final String TEST_PNF_RESOURCE_BLUEPRINT_VERSION = "1.0.1"; private BuildingBlockExecution buildingBlockExecution; private ExecuteBuildingBlock executeBuildingBlock; @@ -88,6 +99,9 @@ public class GeneratePayloadForCdsTest { @Mock private ServiceCDSRequestProvider serviceCDSRequestProvider; + @Mock + private PnfCDSRequestProvider pnfCDSRequestProvider; + @Before public void setup() { @@ -100,9 +114,7 @@ public class GeneratePayloadForCdsTest { // given final String assignPayload = "{\"configAssign-request\":{\"resolution-key\":\"vnf-name-1\",\"configAssign-properties\":{\"service-instance-id\":\"serviceInst_configTest\",\"service-model-uuid\":\"b45b5780-e5dd-11e9-81b4-2a2ae2dbcce4\",\"vnf-id\":\"vnfId_configVnfTest1\",\"vnf-name\":\"vnf-name-1\",\"vnf-customization-uuid\":\"23ce9ac4-e5dd-11e9-81b4-2a2ae2dbcce4\",\"acl-cloud-region\":\"acl-cloud-region\",\"public_net_id\":\"public-net-id\"}}}"; - setScopeAndAction(VNF_SCOPE, ASSIGN_ACTION); - doReturn(Optional.of(assignPayload)).when(vnfCDSRequestProvider).buildRequestPayload(ASSIGN_ACTION); // when @@ -125,7 +137,6 @@ public class GeneratePayloadForCdsTest { final String deployPayload = "{\"configDeploy-request\":{\"resolution-key\":\"vnf-name-1\",\"configDeploy-properties\":{\"service-instance-id\":\"serviceInst_configTest\",\"service-model-uuid\":\"b45b5780-e5dd-11e9-81b4-2a2ae2dbcce4\",\"vnf-id\":\"vnfId_configVnfTest1\",\"vnf-name\":\"vnf-name-1\",\"vnf-customization-uuid\":\"23ce9ac4-e5dd-11e9-81b4-2a2ae2dbcce4\",\"acl-cloud-region\":\"acl-cloud-region\",\"public_net_id\":\"public-net-id\"}}}"; setScopeAndAction(VNF_SCOPE, DEPLOY_ACTION); - doReturn(Optional.of(deployPayload)).when(vnfCDSRequestProvider).buildRequestPayload(DEPLOY_ACTION); // when @@ -188,10 +199,35 @@ public class GeneratePayloadForCdsTest { } @Test + public void testBuildCdsPropertiesBeanDownloadPnf() throws Exception { + // given + final String downloadPayload = + "{\"downloadNeSw-request\":{\"resolution-key\":\"PNFDemo\",\"downloadNeSw-properties\":{\"service-instance-id\":\"test_service_id\",\"service-model-uuid\":\"6bc0b04d-1873-4721-b53d-6615225b2a28\",\"pnf-id\":\"5df8b6de-2083-11e7-93ae-92361f002671\",\"pnf-name\":\"PNFDemo\",\"pnf-customization-uuid\":\"9acb3a83-8a52-412c-9a45-901764938144\",\"target-software-version\":\"demo-sw-ver2.0.0\"}}}"; + DelegateExecution execution = prepareDelegateExecutionObj(PayloadConstants.PNF_SCOPE, DOWNLOAD_ACTION); + doReturn(Optional.of(downloadPayload)).when(pnfCDSRequestProvider).buildRequestPayload(DOWNLOAD_ACTION); + doReturn(TEST_PNF_RESOURCE_BLUEPRINT_NAME).when(pnfCDSRequestProvider).getBlueprintName(); + doReturn(TEST_PNF_RESOURCE_BLUEPRINT_VERSION).when(pnfCDSRequestProvider).getBlueprintVersion(); + + // when + AbstractCDSPropertiesBean propertyBean = configurePayloadForCds.buildCdsPropertiesBean(execution); + + // verify + assertNotNull(propertyBean); + String payload = propertyBean.getRequestObject(); + assertThat(downloadPayload.equals(payload)); + assertThat(propertyBean.getRequestId().equals(MSO_REQUEST_ID)); + assertThat(propertyBean.getOriginatorId().equals("SO")); + assertNotNull(propertyBean.getSubRequestId()); + assertThat(propertyBean.getActionName().equals(DOWNLOAD_ACTION)); + assertThat(propertyBean.getMode().equalsIgnoreCase("async")); + assertThat(propertyBean.getBlueprintName().equalsIgnoreCase(TEST_PNF_RESOURCE_BLUEPRINT_NAME)); + assertThat(propertyBean.getBlueprintVersion().equalsIgnoreCase(TEST_PNF_RESOURCE_BLUEPRINT_VERSION)); + } + + @Test public void testFailureWhenServiceInstanceIsNotPresent() throws Exception { // given setScopeAndAction(VNF_SCOPE, ASSIGN_ACTION); - doThrow(PayloadGenerationException.class).when(serviceCDSRequestProvider).buildRequestPayload(ASSIGN_ACTION); // when @@ -284,4 +320,23 @@ public class GeneratePayloadForCdsTest { executeBuildingBlock.setBuildingBlock(buildingBlock); buildingBlockExecution.setVariable(BUILDING_BLOCK, executeBuildingBlock); } + + private DelegateExecution prepareDelegateExecutionObj(String scope, String action) { + DelegateExecution execution = new DelegateExecutionFake(); + execution.setVariable(PROCESS_KEY, TEST_PROCESS_KEY); + execution.setVariable(PNF_CORRELATION_ID, TEST_PNF_CORRELATION_ID); + execution.setVariable(MODEL_UUID, TEST_MODEL_UUID); + execution.setVariable(SERVICE_INSTANCE_ID, TEST_SERVICE_INSTANCE_ID); + execution.setVariable(MSO_REQUEST_ID, TEST_MSO_REQUEST_ID); + execution.setVariable(PNF_UUID, TEST_PNF_UUID); + execution.setVariable(PRC_INSTANCE_NAME, TEST_PNF_RESOURCE_INSTANCE_NAME); + execution.setVariable(PRC_CUSTOMIZATION_UUID, TEST_PNF_RESOURCE_CUSTOMIZATION_UUID); + execution.setVariable(PRC_TARGET_SOFTWARE_VERSION, TEST_SOFTWARE_VERSION); + execution.setVariable(PRC_BLUEPRINT_NAME, TEST_PNF_RESOURCE_BLUEPRINT_NAME); + execution.setVariable(PRC_BLUEPRINT_VERSION, TEST_PNF_RESOURCE_BLUEPRINT_VERSION); + execution.setVariable(SCOPE, scope); + execution.setVariable(ACTION, action); + execution.setVariable("mode", "async"); + return execution; + } } diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/PnfCDSRequestProviderTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/PnfCDSRequestProviderTest.java new file mode 100644 index 0000000000..e5cbc9a369 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/PnfCDSRequestProviderTest.java @@ -0,0 +1,139 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix + * ================================================================================ + * 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.so.client.cds; + + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.JsonParser; +import org.camunda.bpm.engine.delegate.DelegateExecution; +import org.camunda.bpm.extension.mockito.delegate.DelegateExecutionFake; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.junit.MockitoJUnitRunner; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +@RunWith(MockitoJUnitRunner.Silent.class) +public class PnfCDSRequestProviderTest { + + @InjectMocks + private PnfCDSRequestProvider pnfCDSRequestProvider; + + private static final String DOWNLOAD_ACTION = "downloadNeSw"; + private static final String ACTIVATE_ACTION = "activateNeSw"; + private static final String TEST_MODEL_UUID = "6bc0b04d-1873-4721-b53d-6615225b2a28"; + private static final String TEST_SERVICE_INSTANCE_ID = "test_service_id"; + private static final String TEST_PROCESS_KEY = "processKey1"; + private static final String TEST_PNF_RESOURCE_INSTANCE_NAME = "PNF_demo_resource"; + private static final String TEST_PNF_CORRELATION_ID = "PNFDemo"; + private static final String TEST_PNF_RESOURCE_CUSTOMIZATION_UUID = "9acb3a83-8a52-412c-9a45-901764938144"; + private static final String TEST_MSO_REQUEST_ID = "ff874603-4222-11e7-9252-005056850d2e"; + private static final String TEST_PNF_UUID = "5df8b6de-2083-11e7-93ae-92361f002671"; + private static final String TEST_SOFTWARE_VERSION = "demo-sw-ver2.0.0"; + private static final String PNF_CORRELATION_ID = "pnfCorrelationId"; + private static final String PNF_UUID = "pnfUuid"; + private static final String SERVICE_INSTANCE_ID = "serviceInstanceId"; + private static final String MSO_REQUEST_ID = "msoRequestId"; + private static final String MODEL_UUID = "modelUuid"; + private static final String PRC_CUSTOMIZATION_UUID = "PRC_customizationUuid"; + private static final String PRC_INSTANCE_NAME = "PRC_instanceName"; + private static final String PRC_TARGET_SOFTWARE_VERSION = "targetSoftwareVersion"; + private static final String SCOPE = "scope"; + private static final String ACTION = "action"; + private static final String PROCESS_KEY = "testProcessKey"; + private static final String PRC_BLUEPRINT_NAME = "PRC_blueprintName"; + private static final String PRC_BLUEPRINT_VERSION = "PRC_blueprintVersion"; + private static final String TEST_PNF_RESOURCE_BLUEPRINT_NAME = "blueprintOnap"; + private static final String TEST_PNF_RESOURCE_BLUEPRINT_VERSION = "1.0.1"; + + @Test + public void testBuildRequestPayloadDownloadActionPnf() { + try { + runTest(DOWNLOAD_ACTION); + } catch (Exception e) { + Assert.fail(e.getMessage()); + } + } + + @Test + public void testBuildRequestPayloadActivateActionPnf() { + try { + runTest(ACTIVATE_ACTION); + } catch (Exception e) { + Assert.fail(e.getMessage()); + } + } + + private void runTest(String action) throws Exception { + // given + DelegateExecution execution = prepareDelegateExecutionObj(PayloadConstants.PNF_SCOPE, action); + + // when + pnfCDSRequestProvider.setExecutionObject(execution); + String payload = pnfCDSRequestProvider.buildRequestPayload(action).get(); + System.out.println(payload); + + // verify + ObjectMapper mapper = new ObjectMapper(); + JsonNode payloadJson = mapper.readTree(payload); + JsonNode requestNode = payloadJson.findValue(action + "-request"); + JsonNode propertiesNode = payloadJson.findValue(action + "-properties"); + + assertNotNull(payload); + assertTrue(verfiyJsonFromString(payload)); + assertThat(requestNode.get("resolution-key").asText()).isEqualTo(TEST_PNF_CORRELATION_ID); + assertThat(propertiesNode.get("service-instance-id").asText()).isEqualTo(TEST_SERVICE_INSTANCE_ID); + assertThat(propertiesNode.get("service-model-uuid").asText()).isEqualTo(TEST_MODEL_UUID); + assertThat(propertiesNode.get("pnf-id").asText()).isEqualTo(TEST_PNF_UUID); + assertThat(propertiesNode.get("pnf-customization-uuid").asText()) + .isEqualTo(TEST_PNF_RESOURCE_CUSTOMIZATION_UUID); + assertThat(propertiesNode.get("target-software-version").asText()).isEqualTo(TEST_SOFTWARE_VERSION); + assertThat(pnfCDSRequestProvider.getBlueprintName().equals(TEST_PNF_RESOURCE_BLUEPRINT_NAME)); + assertThat(pnfCDSRequestProvider.getBlueprintVersion().equals(TEST_PNF_RESOURCE_BLUEPRINT_VERSION)); + } + + private DelegateExecution prepareDelegateExecutionObj(String scope, String action) { + DelegateExecution execution = new DelegateExecutionFake(); + execution.setVariable(PROCESS_KEY, TEST_PROCESS_KEY); + execution.setVariable(PNF_CORRELATION_ID, TEST_PNF_CORRELATION_ID); + execution.setVariable(MODEL_UUID, TEST_MODEL_UUID); + execution.setVariable(SERVICE_INSTANCE_ID, TEST_SERVICE_INSTANCE_ID); + execution.setVariable(MSO_REQUEST_ID, TEST_MSO_REQUEST_ID); + execution.setVariable(PNF_UUID, TEST_PNF_UUID); + execution.setVariable(PRC_INSTANCE_NAME, TEST_PNF_RESOURCE_INSTANCE_NAME); + execution.setVariable(PRC_CUSTOMIZATION_UUID, TEST_PNF_RESOURCE_CUSTOMIZATION_UUID); + execution.setVariable(PRC_TARGET_SOFTWARE_VERSION, TEST_SOFTWARE_VERSION); + execution.setVariable(SCOPE, scope); + execution.setVariable(ACTION, action); + execution.setVariable(PRC_BLUEPRINT_NAME, TEST_PNF_RESOURCE_BLUEPRINT_NAME); + execution.setVariable(PRC_BLUEPRINT_VERSION, TEST_PNF_RESOURCE_BLUEPRINT_VERSION); + return execution; + } + + private boolean verfiyJsonFromString(String payload) { + JsonParser parser = new JsonParser(); + return parser.parse(payload).isJsonObject(); + } + +} diff --git a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/process/ConfigurePnfResource.bpmn b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/process/ConfigurePnfResource.bpmn index 6d5b2a2f28..693dd922e2 100644 --- a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/process/ConfigurePnfResource.bpmn +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/process/ConfigurePnfResource.bpmn @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8"?> -<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" id="Definitions_13i2vsn" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="2.2.4"> +<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" id="Definitions_13i2vsn" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="3.3.5"> <bpmn:process id="ConfigurePnfResource" name="ConfigurePnfResource" isExecutable="true"> <bpmn:startEvent id="ConfigurePnfResource_StartEvent"> <bpmn:outgoing>SequenceFlow_069mxkg</bpmn:outgoing> @@ -57,6 +57,7 @@ <camunda:inputOutput> <camunda:inputParameter name="action">config-assign</camunda:inputParameter> <camunda:inputParameter name="scope">pnf</camunda:inputParameter> + <camunda:inputParameter name="mode">sync</camunda:inputParameter> </camunda:inputOutput> </bpmn:extensionElements> <bpmn:incoming>SequenceFlow_0j3pm2g</bpmn:incoming> @@ -68,6 +69,7 @@ <camunda:inputOutput> <camunda:inputParameter name="action">config-deploy</camunda:inputParameter> <camunda:inputParameter name="scope">pnf</camunda:inputParameter> + <camunda:inputParameter name="mode">async</camunda:inputParameter> </camunda:inputOutput> </bpmn:extensionElements> <bpmn:incoming>SequenceFlow_1owbpsy</bpmn:incoming> diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/decisionpoint/impl/camunda/controller/cds/CdsControllerDE.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/decisionpoint/impl/camunda/controller/cds/PnfConfigCdsControllerDE.java index 0f65b4b3d4..ffd49e6b84 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/decisionpoint/impl/camunda/controller/cds/CdsControllerDE.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/decisionpoint/impl/camunda/controller/cds/PnfConfigCdsControllerDE.java @@ -24,6 +24,7 @@ import org.onap.so.bpmn.infrastructure.decisionpoint.api.ControllerContext; import org.onap.so.bpmn.infrastructure.decisionpoint.api.ControllerRunnable; import org.onap.so.bpmn.infrastructure.decisionpoint.api.controller.ControllerPreparable; import org.onap.so.client.cds.AbstractCDSProcessingBBUtils; +import org.onap.so.client.cds.PayloadConstants; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -31,17 +32,23 @@ import org.springframework.stereotype.Component; * This implementation of {@ref ControllerRunnable} is used for Self service, i.e, blueprint based Controller. */ @Component -public class CdsControllerDE implements ControllerRunnable<DelegateExecution> { +public class PnfConfigCdsControllerDE implements ControllerRunnable<DelegateExecution> { + + private static final String ASSIGN_ACTION = "config-assign"; + private static final String DEPLOY_ACTION = "config-deploy"; @Autowired(required = false) private List<ControllerPreparable<DelegateExecution>> prepareList; @Autowired - private AbstractCDSProcessingBBUtils abstractCDSProcessingBBUtils; + private AbstractCDSProcessingBBUtils cdsDispatcher; @Override public Boolean understand(ControllerContext<DelegateExecution> context) { - return context.getControllerActor().equalsIgnoreCase("cds"); + return PayloadConstants.CDS_ACTOR.equalsIgnoreCase(context.getControllerActor()) + && PayloadConstants.PNF_SCOPE.equalsIgnoreCase(context.getControllerScope()) + && (ASSIGN_ACTION.equalsIgnoreCase(context.getControllerAction()) + || DEPLOY_ACTION.equalsIgnoreCase(context.getControllerAction())); // legacy behavior } @Override @@ -58,7 +65,7 @@ public class CdsControllerDE implements ControllerRunnable<DelegateExecution> { @Override public void run(ControllerContext<DelegateExecution> context) { DelegateExecution execution = context.getExecution(); - abstractCDSProcessingBBUtils.constructExecutionServiceInputObject(execution); - abstractCDSProcessingBBUtils.sendRequestToCDSClient(execution); + cdsDispatcher.constructExecutionServiceInputObject(execution); + cdsDispatcher.sendRequestToCDSClient(execution); } } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/GenericPnfCDSProcessingDE.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/GenericPnfCDSProcessingDE.java new file mode 100644 index 0000000000..d5423b2ff7 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/GenericPnfCDSProcessingDE.java @@ -0,0 +1,92 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix + * ================================================================================ + * 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.so.bpmn.infrastructure.flowspecific.tasks; + +import org.camunda.bpm.engine.delegate.DelegateExecution; +import org.onap.so.bpmn.infrastructure.decisionpoint.api.ControllerContext; +import org.onap.so.bpmn.infrastructure.decisionpoint.api.ControllerRunnable; +import org.onap.so.bpmn.servicedecomposition.tasks.ExtractPojosForBB; +import org.onap.so.client.cds.AbstractCDSProcessingBBUtils; +import org.onap.so.client.cds.GeneratePayloadForCds; +import org.onap.so.client.cds.PayloadConstants; +import org.onap.so.client.cds.beans.AbstractCDSPropertiesBean; +import org.onap.so.client.exception.ExceptionBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +/** + * For pnf, DelegateExecution is being used. + * + * @param - DelegateExecution + */ +@Component +public class GenericPnfCDSProcessingDE implements ControllerRunnable<DelegateExecution> { + private static final Logger logger = LoggerFactory.getLogger(GenericPnfCDSProcessingDE.class); + private static final String EXECUTION_OBJECT = "executionObject"; + private static final String ASSIGN_ACTION = "config-assign"; + private static final String DEPLOY_ACTION = "config-deploy"; + + @Autowired + private ExceptionBuilder exceptionBuilder; + + @Autowired + private AbstractCDSProcessingBBUtils cdsDispather; + + @Autowired + private GeneratePayloadForCds generatePayloadForCds; + + @Override + public Boolean understand(ControllerContext<DelegateExecution> context) { + final String scope = context.getControllerScope(); + return PayloadConstants.CDS_ACTOR.equalsIgnoreCase(context.getControllerActor()) + && PayloadConstants.PNF_SCOPE.equalsIgnoreCase(scope) + && !(ASSIGN_ACTION.equalsIgnoreCase(context.getControllerAction()) + || DEPLOY_ACTION.equalsIgnoreCase(context.getControllerAction())); + } + + @Override + public Boolean ready(ControllerContext<DelegateExecution> context) { + return true; + } + + @Override + public void prepare(ControllerContext<DelegateExecution> context) { + DelegateExecution delegateExecution = context.getExecution(); + try { + AbstractCDSPropertiesBean abstractCDSPropertiesBean = + generatePayloadForCds.buildCdsPropertiesBean(delegateExecution); + + delegateExecution.setVariable(EXECUTION_OBJECT, abstractCDSPropertiesBean); + + } catch (Exception ex) { + logger.error("An exception occurred when creating payload for CDS request", ex); + exceptionBuilder.buildAndThrowWorkflowException(delegateExecution, 7000, ex); + } + } + + @Override + public void run(ControllerContext<DelegateExecution> context) { + DelegateExecution obj = context.getExecution(); + cdsDispather.constructExecutionServiceInputObject(obj); + cdsDispather.sendRequestToCDSClient(obj); + } +} diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/listeners/SkipCDSBuildingBlockListener.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/listeners/SkipCDSBuildingBlockListener.java new file mode 100644 index 0000000000..682a0471ee --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/listeners/SkipCDSBuildingBlockListener.java @@ -0,0 +1,116 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2020 Tech Mahindra + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.workflow.tasks.listeners; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import org.apache.logging.log4j.util.Strings; +import org.onap.so.bpmn.common.BBConstants; +import org.onap.so.bpmn.common.BuildingBlockExecution; +import org.onap.so.bpmn.common.listener.flowmanipulator.FlowManipulator; +import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock; +import org.onap.so.db.catalog.beans.VfModuleCustomization; +import org.onap.so.db.catalog.beans.VnfResourceCustomization; +import org.onap.so.db.catalog.client.CatalogDbClient; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.CollectionUtils; + +@Component +public class SkipCDSBuildingBlockListener implements FlowManipulator { + + @Autowired + private CatalogDbClient catalogDbClient; + + private Set<String> vnfActions = + new HashSet<String>(Arrays.asList("config-assign", "config-deploy", "VnfConfigAssign", "VnfConfigDeploy")); + + private Set<String> vFModuleAction = + new HashSet<String>(Arrays.asList("VfModuleConfigAssign", "VfModuleConfigDeploy")); + + @Override + public boolean shouldRunFor(String currentBBName, boolean isFirst, BuildingBlockExecution execution) { + + return "ControllerExecutionBB".equals(currentBBName); + } + + /** + * Skip the CDS Building block according to the Skip Flag. + * + * @param flowsToExecute - List of ExecuteBuildingBlock object. + * @param execution - BuildingBlockExecution object + * @param currentBB - ExecuteBuildingBlock object + * + */ + @Override + public void run(List<ExecuteBuildingBlock> flowsToExecute, ExecuteBuildingBlock currentBB, + BuildingBlockExecution execution) { + String customizationUUID = currentBB.getBuildingBlock().getKey(); + + if (Strings.isEmpty(customizationUUID)) { + return; + } + + if (currentBB.getBuildingBlock().getBpmnScope().equalsIgnoreCase("VNF") + && containsIgnoreCaseAction(currentBB, vnfActions)) { + List<VnfResourceCustomization> vnfResourceCustomizations = + catalogDbClient.getVnfResourceCustomizationByModelUuid( + currentBB.getRequestDetails().getModelInfo().getModelUuid()); + if (!CollectionUtils.isEmpty(vnfResourceCustomizations)) { + VnfResourceCustomization vrc = catalogDbClient.findVnfResourceCustomizationInList(customizationUUID, + vnfResourceCustomizations); + if (null != vrc) { + boolean skipConfigVNF = vrc.isSkipPostInstConf(); + currentSequenceSkipCheck(execution, skipConfigVNF); + } + + } + } else if (currentBB.getBuildingBlock().getBpmnScope().equalsIgnoreCase("VFModule") + && containsIgnoreCaseAction(currentBB, vFModuleAction)) { + + VfModuleCustomization vfc = + catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID(customizationUUID); + + if (null != vfc) { + boolean skipVfModule = vfc.isSkipPostInstConf(); + currentSequenceSkipCheck(execution, skipVfModule); + } + } + + + } + + private boolean containsIgnoreCaseAction(ExecuteBuildingBlock currentBB, Set<String> actions) { + return actions.stream().filter(action -> action.equalsIgnoreCase(currentBB.getBuildingBlock().getBpmnAction())) + .findFirst().isPresent(); + } + + + private void currentSequenceSkipCheck(BuildingBlockExecution execution, boolean skipModule) { + if (skipModule) { + int currentSequence = execution.getVariable(BBConstants.G_CURRENT_SEQUENCE); + execution.setVariable(BBConstants.G_CURRENT_SEQUENCE, currentSequence + 1); + } + } + +} diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/decisionpoint/impl/camunda/ControllerExecutionDETestIT.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/decisionpoint/impl/camunda/ControllerExecutionDETestIT.java index 860780a2fc..275cd18f0b 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/decisionpoint/impl/camunda/ControllerExecutionDETestIT.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/decisionpoint/impl/camunda/ControllerExecutionDETestIT.java @@ -19,50 +19,63 @@ package org.onap.so.bpmn.infrastructure.decisionpoint.impl.camunda; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.fail; -import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.MODEL_UUID; -import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.MSO_REQUEST_ID; -import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PNF_CORRELATION_ID; -import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PNF_UUID; -import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PRC_BLUEPRINT_NAME; -import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PRC_BLUEPRINT_VERSION; -import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PRC_CUSTOMIZATION_UUID; -import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PRC_INSTANCE_NAME; -import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.SERVICE_INSTANCE_ID; import com.google.protobuf.Struct; -import java.util.List; import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Rule; import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers; import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader; import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput; import org.onap.so.BaseIntegrationTest; import org.onap.so.GrpcNettyServer; -import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf; +import org.onap.so.client.aai.AAIVersion; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.junit4.rules.SpringClassRule; +import org.springframework.test.context.junit4.rules.SpringMethodRule; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import static com.github.tomakehurst.wiremock.client.WireMock.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.fail; +import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.*; +@RunWith(Parameterized.class) public class ControllerExecutionDETestIT extends BaseIntegrationTest { private Logger logger = LoggerFactory.getLogger(this.getClass()); + @ClassRule + public static final SpringClassRule springClassRule = new SpringClassRule(); + + @Rule + public final SpringMethodRule smr = new SpringMethodRule(); + + private static final String DOWNLOAD_ACTION = "downloadNeSw"; + private static final String ACTIVATE_ACTION = "activateNeSw"; + private static final String PRECHECK_ACTION = "precheck"; + private static final String POSTCHECK_ACTION = "postcheck"; + private static final String ASSIGN_ACTION = "config-assign"; + private static final String DEPLOY_ACTION = "config-deploy"; + private static final String CDS_ACTOR = "cds"; + @Autowired private ControllerExecutionDE controllerExecutionDE; @Autowired private GrpcNettyServer grpcNettyServer; - private GenericVnf genericVnf; - private static String TEST_MODEL_UUID = "6bc0b04d-1873-4721-b53d-6615225b2a28"; private static String TEST_SERVICE_INSTANCE_ID = "test_service_id"; private static String TEST_PROCESS_KEY = "processKey1"; private static String TEST_MSO_REQUEST_ID = "ff874603-4222-11e7-9252-005056850d2e"; - private static String TEST_CDS_ACTION = "config-assign"; - private static String TEST_APPC_ACTION = "HealthCheck"; + private static final AAIVersion VERSION = AAIVersion.LATEST; private static String TEST_PNF_RESOURCE_INSTANCE_NAME = "PNF_demo_resource"; private static String TEST_PNF_CORRELATION_ID = "PNFDemo"; @@ -70,75 +83,112 @@ public class ControllerExecutionDETestIT extends BaseIntegrationTest { private static String TEST_PNF_RESOURCE_BLUEPRINT_VERSION = "1.0.1"; private static String TEST_PNF_RESOURCE_CUSTOMIZATION_UUID = "9acb3a83-8a52-412c-9a45-901764938144"; private static String TEST_PNF_UUID = "5df8b6de-2083-11e7-93ae-92361f002671"; + private static String TEST_SOFTWARE_VERSION = "demo-sw-ver2.0.0"; + + private String description; + private String action; + private String scope; + + public ControllerExecutionDETestIT(String desc, String action, String scope) { + this.description = desc; + this.action = action; + this.scope = scope; + + } + + @Parameterized.Parameters(name = "index {0}") + public static Collection<String[]> data() { + return Arrays.asList( + new String[][] {{"Test JSON for action:" + ACTIVATE_ACTION + " scope:pnf", ACTIVATE_ACTION, "pnf"}, + {"Test JSON for action:" + DOWNLOAD_ACTION + " scope:pnf", DOWNLOAD_ACTION, "pnf"}, + {"Test JSON for action:" + ASSIGN_ACTION + " scope:pnf", ASSIGN_ACTION, "pnf"}, + {"Test JSON for action:" + DEPLOY_ACTION + " scope:pnf", DEPLOY_ACTION, "pnf"}, + {"Test JSON for action:" + PRECHECK_ACTION + " scope:pnf", PRECHECK_ACTION, "pnf"}, + {"Test JSON for action:" + POSTCHECK_ACTION + " scope:pnf", POSTCHECK_ACTION, "pnf"}}); + } @Before public void setUp() { + delegateExecution.setVariable("testProcessKey", TEST_PROCESS_KEY); + delegateExecution.setVariable(PNF_CORRELATION_ID, TEST_PNF_CORRELATION_ID); delegateExecution.setVariable(MODEL_UUID, TEST_MODEL_UUID); delegateExecution.setVariable(SERVICE_INSTANCE_ID, TEST_SERVICE_INSTANCE_ID); delegateExecution.setVariable(MSO_REQUEST_ID, TEST_MSO_REQUEST_ID); - delegateExecution.setVariable("testProcessKey", TEST_PROCESS_KEY); + delegateExecution.setVariable(PNF_UUID, TEST_PNF_UUID); + delegateExecution.setVariable(PRC_INSTANCE_NAME, TEST_PNF_RESOURCE_INSTANCE_NAME); + delegateExecution.setVariable(PRC_CUSTOMIZATION_UUID, TEST_PNF_RESOURCE_CUSTOMIZATION_UUID); + delegateExecution.setVariable(PRC_BLUEPRINT_NAME, TEST_PNF_RESOURCE_BLUEPRINT_NAME); + delegateExecution.setVariable(PRC_BLUEPRINT_VERSION, TEST_PNF_RESOURCE_BLUEPRINT_VERSION); + delegateExecution.setVariable("targetSoftwareVersion", TEST_SOFTWARE_VERSION); + + delegateExecution.setVariable("actor", CDS_ACTOR); + delegateExecution.setVariable("action", this.action); + delegateExecution.setVariable("scope", this.scope); + + + /** + * Get the PNF entry from AAI. + */ + if (action.equalsIgnoreCase(DEPLOY_ACTION)) { + final String aaiPnfEntry = "{ \n" + " \"pnf-name\":\"PNFDemo\",\n" + " \"pnf-id\":\"testtest\",\n" + + " \"in-maint\":true,\n" + " \"resource-version\":\"1541720264047\",\n" + + " \"ipaddress-v4-oam\":\"1.1.1.1\",\n" + " \"ipaddress-v6-oam\":\"::/128\"\n" + "}"; + wireMockServer.stubFor( + get(urlEqualTo("/aai/" + VERSION + "/network/pnfs/pnf/PNFDemo")).willReturn(okJson(aaiPnfEntry))); + } grpcNettyServer.cleanMessage(); } @Test - public void testExecution_cdsConfigAssign_actionExecuted() { - - configureCdsConfigAssign(); + public void testExecution_cds_actions() { controllerExecutionDE.execute(delegateExecution); List<ExecutionServiceInput> detailedMessages = grpcNettyServer.getDetailedMessages(); assertThat(detailedMessages).hasSize(1); try { - checkConfigAssign(detailedMessages.get(0)); + verifyRequestContentForAction(detailedMessages.get(0)); } catch (Exception e) { e.printStackTrace(); - fail("ConfigAssign request exception", e); + fail(this.action + " request exception", e); } } - private void configureCdsConfigAssign() { - delegateExecution.setVariable("actor", "cds"); - delegateExecution.setVariable("action", TEST_CDS_ACTION); - delegateExecution.setVariable("scope", "pnf"); + private void verifyRequestContentForAction(ExecutionServiceInput executionServiceInput) { - delegateExecution.setVariable(PNF_CORRELATION_ID, TEST_PNF_CORRELATION_ID); - delegateExecution.setVariable(PNF_UUID, TEST_PNF_UUID); - delegateExecution.setVariable(PRC_INSTANCE_NAME, TEST_PNF_RESOURCE_INSTANCE_NAME); - delegateExecution.setVariable(PRC_CUSTOMIZATION_UUID, TEST_PNF_RESOURCE_CUSTOMIZATION_UUID); - delegateExecution.setVariable(PRC_BLUEPRINT_NAME, TEST_PNF_RESOURCE_BLUEPRINT_NAME); - delegateExecution.setVariable(PRC_BLUEPRINT_VERSION, TEST_PNF_RESOURCE_BLUEPRINT_VERSION); - } - - private void checkConfigAssign(ExecutionServiceInput executionServiceInput) { - - logger.info("Checking the configAssign request"); + logger.info("Checking the " + this.action + " request"); ActionIdentifiers actionIdentifiers = executionServiceInput.getActionIdentifiers(); - /** - * the fields of actionIdentifiers should match the one in the - * response/createVcpeResCustServiceSimplifiedTest_catalogdb.json. - */ assertThat(actionIdentifiers.getBlueprintName()).isEqualTo(TEST_PNF_RESOURCE_BLUEPRINT_NAME); assertThat(actionIdentifiers.getBlueprintVersion()).isEqualTo(TEST_PNF_RESOURCE_BLUEPRINT_VERSION); - assertThat(actionIdentifiers.getActionName()).isEqualTo(TEST_CDS_ACTION); - assertThat(actionIdentifiers.getMode()).isEqualTo("sync"); + assertThat(actionIdentifiers.getActionName()).isEqualTo(this.action); CommonHeader commonHeader = executionServiceInput.getCommonHeader(); assertThat(commonHeader.getOriginatorId()).isEqualTo("SO"); assertThat(commonHeader.getRequestId()).isEqualTo(TEST_MSO_REQUEST_ID); Struct payload = executionServiceInput.getPayload(); - Struct requeststruct = payload.getFieldsOrThrow("config-assign-request").getStructValue(); + Struct requeststruct = payload.getFieldsOrThrow(this.action + "-request").getStructValue(); assertThat(requeststruct.getFieldsOrThrow("resolution-key").getStringValue()) .isEqualTo(TEST_PNF_CORRELATION_ID); - Struct propertiesStruct = requeststruct.getFieldsOrThrow("config-assign-properties").getStructValue(); + Struct propertiesStruct = requeststruct.getFieldsOrThrow(this.action + "-properties").getStructValue(); assertThat(propertiesStruct.getFieldsOrThrow("pnf-name").getStringValue()).isEqualTo(TEST_PNF_CORRELATION_ID); assertThat(propertiesStruct.getFieldsOrThrow("service-model-uuid").getStringValue()).isEqualTo(TEST_MODEL_UUID); assertThat(propertiesStruct.getFieldsOrThrow("pnf-customization-uuid").getStringValue()) .isEqualTo(TEST_PNF_RESOURCE_CUSTOMIZATION_UUID); + if (action.equalsIgnoreCase(DEPLOY_ACTION)) { + assertThat(actionIdentifiers.getMode()).isEqualTo("async"); + assertThat(propertiesStruct.getFieldsOrThrow("pnf-ipv4-address").getStringValue()).isEqualTo("1.1.1.1"); + assertThat(propertiesStruct.getFieldsOrThrow("pnf-ipv6-address").getStringValue()).isEqualTo("::/128"); + } else if (!action.equalsIgnoreCase(ASSIGN_ACTION)) { + assertThat(actionIdentifiers.getMode()).isEqualTo("sync"); + assertThat(propertiesStruct.getFieldsOrThrow("target-software-version").getStringValue()) + .isEqualTo(TEST_SOFTWARE_VERSION); + } else { + assertThat(actionIdentifiers.getMode()).isEqualTo("sync"); + } } } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/decisionpoint/impl/camunda/controller/cds/CdsControllerDETest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/decisionpoint/impl/camunda/controller/cds/PnfConfigCdsControllerDETest.java index 142cb53ed8..d8f607f6d9 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/decisionpoint/impl/camunda/controller/cds/CdsControllerDETest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/decisionpoint/impl/camunda/controller/cds/PnfConfigCdsControllerDETest.java @@ -37,11 +37,12 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {CdsControllerDE.class, ExceptionBuilder.class, AbstractCDSProcessingBBUtils.class}) -public class CdsControllerDETest { +@ContextConfiguration( + classes = {PnfConfigCdsControllerDE.class, ExceptionBuilder.class, AbstractCDSProcessingBBUtils.class}) +public class PnfConfigCdsControllerDETest { @Autowired - private CdsControllerDE cdsControllerDE; + private PnfConfigCdsControllerDE pnfConfigCdsControllerDE; @MockBean private ControllerContext controllerContext; @@ -52,20 +53,46 @@ public class CdsControllerDETest { @Mock private AbstractCDSProcessingBBUtils abstractCDSProcessingBBUtils; - @Before - public void setUp() { + @Test + public void testUnderstand_action_assign_TrueReturned() { + // when + when(controllerContext.getControllerActor()).thenReturn("cds"); + when(controllerContext.getControllerScope()).thenReturn("pnf"); + when(controllerContext.getControllerAction()).thenReturn("config-assign"); + + // verify + assertTrue(pnfConfigCdsControllerDE.understand(controllerContext)); + } + + @Test + public void testUnderstand_action_deploy_TrueReturned() { + // when when(controllerContext.getControllerActor()).thenReturn("cds"); + when(controllerContext.getControllerScope()).thenReturn("pnf"); + when(controllerContext.getControllerAction()).thenReturn("config-deploy"); + + // verify + assertTrue(pnfConfigCdsControllerDE.understand(controllerContext)); } @Test - public void testUnderstand_validContext_TrueReturned() { - assertTrue(cdsControllerDE.understand(controllerContext)); + public void testUnderstand_action_any_FalseReturned() { + // when + when(controllerContext.getControllerActor()).thenReturn("cds"); + when(controllerContext.getControllerScope()).thenReturn("pnf"); + when(controllerContext.getControllerAction()).thenReturn("any-action"); + + // verify + assertFalse(pnfConfigCdsControllerDE.understand(controllerContext)); } @Test public void testUnderstand_invalidContext_FalseReturned() { + // when when(controllerContext.getControllerActor()).thenReturn("appc"); - assertFalse(cdsControllerDE.understand(controllerContext)); + + // verify + assertFalse(pnfConfigCdsControllerDE.understand(controllerContext)); } } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/GenericPnfCDSProcessingDETest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/GenericPnfCDSProcessingDETest.java new file mode 100644 index 0000000000..c69adeec50 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/GenericPnfCDSProcessingDETest.java @@ -0,0 +1,143 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix + * ================================================================================ + * 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.so.bpmn.infrastructure.flowspecific.tasks; + +import org.camunda.bpm.engine.delegate.DelegateExecution; +import org.camunda.bpm.extension.mockito.delegate.DelegateExecutionFake; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.onap.so.bpmn.BaseTaskTest; +import org.onap.so.bpmn.infrastructure.decisionpoint.api.ControllerContext; +import org.onap.so.client.cds.AbstractCDSProcessingBBUtils; +import org.onap.so.client.cds.GeneratePayloadForCds; +import org.onap.so.client.cds.beans.AbstractCDSPropertiesBean; +import org.onap.so.client.exception.ExceptionBuilder; +import org.skyscreamer.jsonassert.JSONAssert; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.rules.SpringClassRule; +import org.springframework.test.context.junit4.rules.SpringMethodRule; +import java.util.Arrays; +import java.util.Collection; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.*; + +@RunWith(Parameterized.class) +public class GenericPnfCDSProcessingDETest extends BaseTaskTest { + + @ClassRule + public static final SpringClassRule springClassRule = new SpringClassRule(); + + @Rule + public final SpringMethodRule smr = new SpringMethodRule(); + + @InjectMocks + private GenericPnfCDSProcessingDE controllerRunnable; + + @Mock + private GeneratePayloadForCds generatePayloadForCds; + + @Mock + private AbstractCDSProcessingBBUtils cdsDispather; + + private static final String PRECHECK_ACTION = "precheck"; + private static final String DOWNLOAD_ACTION = "downloadNeSw"; + private static final String ACTIVATE_ACTION = "activateNeSw"; + private static final String POSTCHECK_ACTION = "postcheck"; + + private String description; + private String action; + private String scope; + private String expectedJson; + + public GenericPnfCDSProcessingDETest(String desc, String action, String scope, String expectedJson) { + this.description = desc; + this.action = action; + this.scope = scope; + this.expectedJson = expectedJson; + + } + + @Parameterized.Parameters(name = "index {0}") + public static Collection<String[]> data() { + return Arrays.asList(new String[][] { + {"Test JSON for action:" + PRECHECK_ACTION + " scope:pnf", PRECHECK_ACTION, "pnf", + buildExpectedJson(PRECHECK_ACTION, "pnf")}, + {"Test JSON for action:" + DOWNLOAD_ACTION + " scope:pnf", DOWNLOAD_ACTION, "pnf", + buildExpectedJson(DOWNLOAD_ACTION, "pnf")}, + {"Test JSON for action:" + ACTIVATE_ACTION + " scope:pnf", ACTIVATE_ACTION, "pnf", + buildExpectedJson(ACTIVATE_ACTION, "pnf")}, + {"Test JSON for action:" + POSTCHECK_ACTION + " scope:pnf", POSTCHECK_ACTION, "pnf", + buildExpectedJson(POSTCHECK_ACTION, "pnf")},}); + } + + private static String buildExpectedJson(String action, String scope) { + return "{\"" + action + "-request\":" + "{\"" + action + "-" + "properties\":" + + "{\"service-instance-id\":\"test_service_id\"," + + "\"pnf-customization-uuid\":\"9acb3a83-8a52-412c-9a45-901764938144\"," + + "\"pnf-id\":\"5df8b6de-2083-11e7-93ae-92361f002671\"," + + "\"target-software-version\":\"demo-sw-ver2.0.0\"," + "\"pnf-name\":\"PNFDemo\"," + + "\"service-model-uuid\":\"6bc0b04d-1873-4721-b53d-6615225b2a28\"}," + "\"resolution-key\":\"PNFDemo\"" + + "}" + "}"; + } + + private DelegateExecution execution = new DelegateExecutionFake(); + + @Test + public void testExecution_validPnf_action_executionObjectCreated() { + try { + + // given + ControllerContext controllerContext = new ControllerContext(); + controllerContext.setExecution(execution); + controllerContext.setControllerActor("cds"); + controllerContext.setControllerAction(this.action); + controllerContext.setControllerScope(this.scope); + AbstractCDSPropertiesBean bean = new AbstractCDSPropertiesBean(); + doNothing().when(cdsDispather).constructExecutionServiceInputObject(execution); + doNothing().when(cdsDispather).sendRequestToCDSClient(execution); + doReturn(bean).when(generatePayloadForCds).buildCdsPropertiesBean(execution); + + // when + Boolean isUnderstandable = controllerRunnable.understand(controllerContext); + Boolean isReady = controllerRunnable.ready(controllerContext); + controllerRunnable.prepare(controllerContext); + controllerRunnable.run(controllerContext); + + // verify + assertEquals(isUnderstandable, true); + assertEquals(isReady, true); + Object executionObject = execution.getVariable(EXECUTION_OBJECT); + assertThat(executionObject).isNotNull(); + assertThat(executionObject).isInstanceOf(AbstractCDSPropertiesBean.class); + } catch (Exception e) { + e.printStackTrace(); + fail("Exception thrown" + e.getMessage()); + } + } +} diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/listeners/SkipCDSBuildingBlockListenerTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/listeners/SkipCDSBuildingBlockListenerTest.java new file mode 100644 index 0000000000..fb162f857b --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/listeners/SkipCDSBuildingBlockListenerTest.java @@ -0,0 +1,202 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2020 Tech Mahindra + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.workflow.tasks.listeners; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; +import java.util.ArrayList; +import java.util.List; +import org.camunda.bpm.extension.mockito.delegate.DelegateExecutionFake; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.bpmn.common.BBConstants; +import org.onap.so.bpmn.common.BuildingBlockExecution; +import org.onap.so.bpmn.common.DelegateExecutionImpl; +import org.onap.so.bpmn.servicedecomposition.entities.BuildingBlock; +import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock; +import org.onap.so.db.catalog.beans.VfModuleCustomization; +import org.onap.so.db.catalog.beans.VnfResourceCustomization; +import org.onap.so.db.catalog.client.CatalogDbClient; +import org.onap.so.serviceinstancebeans.ModelInfo; +import org.onap.so.serviceinstancebeans.RequestDetails; + +@RunWith(MockitoJUnitRunner.Silent.class) +public class SkipCDSBuildingBlockListenerTest { + + private static final String VNF_SCOPE = "VNF"; + private static final String VF_SCOPE = "VFModule"; + private static final String TEST_MODELUUID = "123456789"; + private static final String VNF_TEST_ACTION = "VnfConfigAssign"; + private static final String VFModule_TEST_ACTION = "VfModuleConfigAssign"; + private static final String MODELCUSTOMIZATIONUUID = "123456789"; + private static final String BBNAME = "ControllerExecutionBB"; + private static final boolean ISFIRST = true; + + private int actual; + private List<ExecuteBuildingBlock> flowsToExecute = new ArrayList<>(); + private List<VnfResourceCustomization> vnfResourceCustomization; + private List<VfModuleCustomization> vfModuleCustomization; + private ExecuteBuildingBlock executeBuildingBlock = new ExecuteBuildingBlock(); + private RequestDetails reqDetail = new RequestDetails(); + private BuildingBlockExecution buildingBlockExecution = new DelegateExecutionImpl(new DelegateExecutionFake()); + private VnfResourceCustomization vnfCust = new VnfResourceCustomization(); + private VfModuleCustomization vfCust = new VfModuleCustomization(); + private BuildingBlock buildingBlock = new BuildingBlock(); + + @InjectMocks + private SkipCDSBuildingBlockListener skipCDSBuildingBlockListener; + @Mock + private CatalogDbClient catalogDbClient; + + @Before + public void before() { + ModelInfo model = new ModelInfo(); + model.setModelUuid(TEST_MODELUUID); + reqDetail.setModelInfo(model); + executeBuildingBlock.setRequestDetails(reqDetail); + } + + @Test + public void testTrigger() { + BuildingBlockExecution execution = new DelegateExecutionImpl(new DelegateExecutionFake()); + skipCDSBuildingBlockListener.shouldRunFor(BBNAME, ISFIRST, execution); + assertEquals("ControllerExecutionBB", BBNAME); + } + + @Test + public void testProcessForVNFToSkipCDSBB() { + // given + setBuildingBlockAndCurrentSequence(VNF_SCOPE, VNF_TEST_ACTION, 0); + vnfResourceCustomization = getVnfResourceCustomizationList(true); + + when(catalogDbClient.getVnfResourceCustomizationByModelUuid( + executeBuildingBlock.getRequestDetails().getModelInfo().getModelUuid())) + .thenReturn(vnfResourceCustomization); + when(catalogDbClient.findVnfResourceCustomizationInList(executeBuildingBlock.getBuildingBlock().getKey(), + vnfResourceCustomization)).thenReturn(vnfCust); + + // when + skipCDSBuildingBlockListener.run(flowsToExecute, executeBuildingBlock, buildingBlockExecution); + + // then + actual = buildingBlockExecution.getVariable(BBConstants.G_CURRENT_SEQUENCE); + assertEquals(1, actual); + + } + + @Test + public void testProcessForVNFNotToSkipCDSBB() { + // given + setBuildingBlockAndCurrentSequence(VNF_SCOPE, VNF_TEST_ACTION, 0); + vnfResourceCustomization = getVnfResourceCustomizationList(false); + + when(catalogDbClient.getVnfResourceCustomizationByModelUuid( + executeBuildingBlock.getRequestDetails().getModelInfo().getModelUuid())) + .thenReturn(vnfResourceCustomization); + when(catalogDbClient.findVnfResourceCustomizationInList(executeBuildingBlock.getBuildingBlock().getKey(), + vnfResourceCustomization)).thenReturn(vnfCust); + + // when + skipCDSBuildingBlockListener.run(flowsToExecute, executeBuildingBlock, buildingBlockExecution); + + // then + actual = buildingBlockExecution.getVariable(BBConstants.G_CURRENT_SEQUENCE); + assertEquals(0, actual); + + } + + + @Test + public void testProcessForVFToSkipCDSBB() { + // given + setBuildingBlockAndCurrentSequence(VF_SCOPE, VFModule_TEST_ACTION, 0); + vfModuleCustomization = getVfModuleCustomizationList(true); + + when(catalogDbClient + .getVfModuleCustomizationByModelCuztomizationUUID(executeBuildingBlock.getBuildingBlock().getKey())) + .thenReturn(vfCust); + + // when + skipCDSBuildingBlockListener.run(flowsToExecute, executeBuildingBlock, buildingBlockExecution); + + // then + actual = buildingBlockExecution.getVariable(BBConstants.G_CURRENT_SEQUENCE); + assertEquals(1, actual); + + } + + @Test + public void testProcessForVFNotToSkipCDSBB() { + // given + setBuildingBlockAndCurrentSequence(VF_SCOPE, VFModule_TEST_ACTION, 0); + vfModuleCustomization = getVfModuleCustomizationList(false); + + when(catalogDbClient + .getVfModuleCustomizationByModelCuztomizationUUID(executeBuildingBlock.getBuildingBlock().getKey())) + .thenReturn(vfCust); + + // when + skipCDSBuildingBlockListener.run(flowsToExecute, executeBuildingBlock, buildingBlockExecution); + + // then + actual = buildingBlockExecution.getVariable(BBConstants.G_CURRENT_SEQUENCE); + assertEquals(0, actual); + + } + + /** + * setting scope action in buildingBlock and BB current sequence in BuildingBlockExecution + * + * @param scope + * @param action + * @param squence + */ + private void setBuildingBlockAndCurrentSequence(String scope, String action, int sequence) { + buildingBlock.setBpmnScope(scope); + buildingBlock.setBpmnAction(action); + buildingBlock.setBpmnFlowName("ControllerExecutionBB"); + buildingBlock.setKey(MODELCUSTOMIZATIONUUID); + executeBuildingBlock.setBuildingBlock(buildingBlock); + buildingBlockExecution.setVariable(BBConstants.G_CURRENT_SEQUENCE, sequence); + + } + + private List<VnfResourceCustomization> getVnfResourceCustomizationList(boolean setSkippost) { + List<VnfResourceCustomization> vnfResourceCustomizations = new ArrayList<>(); + vnfCust.setModelCustomizationUUID(MODELCUSTOMIZATIONUUID); + vnfCust.setSkipPostInstConf(setSkippost); + vnfResourceCustomizations.add(vnfCust); + return vnfResourceCustomizations; + } + + private List<VfModuleCustomization> getVfModuleCustomizationList(boolean setSkippost) { + List<VfModuleCustomization> vfModuleCustomizations = new ArrayList<>(); + vfCust.setModelCustomizationUUID(MODELCUSTOMIZATIONUUID); + vfCust.setSkipPostInstConf(setSkippost); + vfModuleCustomizations.add(vfCust); + return vfModuleCustomizations; + } + +} diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/ServiceInstancesRequest.java b/common/src/main/java/org/onap/so/serviceinstancebeans/ServiceInstancesRequest.java index 5bcdcb181b..05e69b7b19 100644 --- a/common/src/main/java/org/onap/so/serviceinstancebeans/ServiceInstancesRequest.java +++ b/common/src/main/java/org/onap/so/serviceinstancebeans/ServiceInstancesRequest.java @@ -32,8 +32,8 @@ public class ServiceInstancesRequest implements Serializable { private String serviceInstanceId; @JsonProperty("vnfInstanceId") private String vnfInstanceId; - @JsonProperty("pnfId") - private String pnfId; + @JsonProperty("pnfName") + private String pnfName; @JsonProperty("networkInstanceId") private String networkInstanceId; @JsonProperty("volumeGroupInstanceId") @@ -69,12 +69,12 @@ public class ServiceInstancesRequest implements Serializable { this.vnfInstanceId = vnfInstanceId; } - public String getPnfId() { - return pnfId; + public String getPnfName() { + return pnfName; } - public void setPnfId(String pnfId) { - this.pnfId = pnfId; + public void setPnfName(String pnfName) { + this.pnfName = pnfName; } public String getNetworkInstanceId() { @@ -123,7 +123,7 @@ public class ServiceInstancesRequest implements Serializable { sb.append("requestDetails=").append(requestDetails); sb.append(", serviceInstanceId='").append(serviceInstanceId).append('\''); sb.append(", vnfInstanceId='").append(vnfInstanceId).append('\''); - sb.append(", pnfId='").append(pnfId).append('\''); + sb.append(", pnfName='").append(pnfName).append('\''); sb.append(", networkInstanceId='").append(networkInstanceId).append('\''); sb.append(", volumeGroupInstanceId='").append(volumeGroupInstanceId).append('\''); sb.append(", vfModuleInstanceId='").append(vfModuleInstanceId).append('\''); diff --git a/mso-api-handlers/mso-api-handler-infra/pom.xml b/mso-api-handlers/mso-api-handler-infra/pom.xml index 84a80e6617..9944984d33 100644 --- a/mso-api-handlers/mso-api-handler-infra/pom.xml +++ b/mso-api-handlers/mso-api-handler-infra/pom.xml @@ -98,6 +98,10 @@ <artifactId>spring-retry</artifactId> </dependency> <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-webflux</artifactId> + </dependency> + <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java index 17377d881a..f30b66c6b5 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java @@ -9,9 +9,11 @@ import javax.ws.rs.core.UriBuilder; import javax.xml.bind.DatatypeConverter; import org.camunda.bpm.engine.impl.persistence.entity.HistoricActivityInstanceEntity; import org.camunda.bpm.engine.impl.persistence.entity.HistoricProcessInstanceEntity; +import org.json.JSONObject; import org.onap.logging.filter.spring.SpringClientPayloadFilter; import org.onap.so.logging.jaxrs.filter.SOSpringClientFilter; import org.onap.so.utils.CryptoUtils; +import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -29,6 +31,9 @@ import org.springframework.stereotype.Component; import org.springframework.web.client.ResourceAccessException; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; +import org.springframework.web.reactive.function.BodyInserters; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Flux; @Component public class CamundaRequestHandler { @@ -202,6 +207,20 @@ public class CamundaRequestHandler { return retryTemplate; } + protected void sendCamundaMessages(JSONObject msgJson) { + String url = env.getProperty("mso.camundaURL") + "/sobpmnengine/message"; + HttpHeaders headers = + setCamundaHeaders(env.getRequiredProperty("mso.camundaAuth"), env.getRequiredProperty("mso.msoKey")); + headers.setContentType(org.springframework.http.MediaType.APPLICATION_JSON); + // Workflow may take a long time so use non-blocking request + Flux<String> flux = WebClient.create().post().uri(url).headers(httpHeaders -> { + httpHeaders.set(httpHeaders.AUTHORIZATION, headers.get(httpHeaders.AUTHORIZATION).get(0)); + httpHeaders.set(httpHeaders.ACCEPT, headers.get(httpHeaders.ACCEPT).get(0)); + httpHeaders.set(httpHeaders.CONTENT_TYPE, headers.get(httpHeaders.CONTENT_TYPE).get(0)); + }).body(BodyInserters.fromObject(msgJson.toString())).retrieve().bodyToFlux(String.class); + flux.subscribe(res -> logger.debug("Send Camunda Message: " + res)); + } + protected RestTemplate getRestTemplate(boolean retry) { int timeout; if (retry) { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java index 028abd6d25..88028d32a1 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java @@ -95,7 +95,7 @@ public class InstanceManagement { @Path("/{version:[vV][1]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/workflows/{workflowUuid}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Execute custom workflow", responses = @ApiResponse( + @Operation(description = "Execute custom VNF workflow", responses = @ApiResponse( content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response executeVNFCustomWorkflow(String request, @PathParam("version") String version, @@ -112,20 +112,20 @@ public class InstanceManagement { } @POST - @Path("/{version:[vV][1]}/serviceInstances/{serviceInstanceId}/pnfs/{pnfId}/workflows/{workflowUuid}") + @Path("/{version:[vV][1]}/serviceInstances/{serviceInstanceId}/pnfs/{pnfName}/workflows/{workflowUuid}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Execute custom workflow", responses = @ApiResponse( + @Operation(description = "Execute custom PNF workflow", responses = @ApiResponse( content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response executePNFCustomWorkflow(String request, @PathParam("version") String version, - @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("pnfId") String pnfId, + @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("pnfName") String pnfName, @PathParam("workflowUuid") String workflowUuid, @Context ContainerRequestContext requestContext) throws ApiException { String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); - instanceIdMap.put("pnfId", pnfId); + instanceIdMap.put("pnfName", pnfName); instanceIdMap.put("workflowUuid", workflowUuid); return processPNFCustomWorkflowRequest(request, Action.forCustomWorkflow, instanceIdMap, version, requestId, requestContext); @@ -255,18 +255,18 @@ public class InstanceManagement { String apiVersion = version.substring(1); String serviceInstanceId = ""; - String pnfId = ""; + String pnfName = ""; String workflowUuid = ""; if (instanceIdMap != null) { serviceInstanceId = instanceIdMap.get("serviceInstanceId"); - pnfId = instanceIdMap.get("pnfId"); + pnfName = instanceIdMap.get("pnfName"); workflowUuid = instanceIdMap.get("workflowUuid"); } String requestUri = requestHandlerUtils.getRequestUri(requestContext, uriPrefix); sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, requestId, requestUri); sir.setServiceInstanceId(serviceInstanceId); - sir.setPnfId(pnfId); + sir.setPnfName(pnfName); String requestScope = ModelType.pnf.name(); InfraActiveRequests currentActiveReq = msoRequest.createRequestObject(sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope); @@ -299,7 +299,7 @@ public class InstanceManagement { try { requestClientParameter = new RequestClientParameter.Builder().setRequestId(requestId) .setRecipeTimeout(recipeLookupResult.getRecipeTimeout()).setRequestAction(action.toString()) - .setServiceInstanceId(serviceInstanceId).setPnfCorrelationId(pnfId) + .setServiceInstanceId(serviceInstanceId).setPnfCorrelationId(pnfName) .setRequestDetails(requestHandlerUtils.mapJSONtoMSOStyle(requestJSON, null, aLaCarte, action)) .setApiVersion(apiVersion).setRequestUri(requestUri).build(); } catch (IOException e) { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/JerseyConfiguration.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/JerseyConfiguration.java index b7288e4c91..0afc272b0a 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/JerseyConfiguration.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/JerseyConfiguration.java @@ -92,6 +92,7 @@ public class JerseyConfiguration extends ResourceConfig { register(NoRecipeExceptionMapper.class); register(RequestConflictMapper.class); register(WorkflowEngineConnectionMapper.class); + register(OrchestrationTasks.class); // this registration seems to be needed to get predictable // execution behavior for the above JSON Exception Mappers register(com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider.class); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java index 5c81f4e6a5..31e026b332 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java @@ -311,9 +311,9 @@ public class MsoRequest { aq.setVnfId(servInsReq.getVnfInstanceId()); } - if (servInsReq.getPnfId() != null) { + if (servInsReq.getPnfName() != null) { aq.setRequestScope(requestScope); - aq.setPnfId(servInsReq.getPnfId()); + aq.setPnfName(servInsReq.getPnfName()); } if (ModelType.service.name().equalsIgnoreCase(requestScope)) { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationTasks.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationTasks.java new file mode 100644 index 0000000000..21129d7c2d --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationTasks.java @@ -0,0 +1,209 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.apihandlerinfra; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.swagger.v3.oas.annotations.OpenAPIDefinition; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.info.Info; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import org.apache.http.HttpStatus; +import org.json.JSONObject; +import org.onap.so.apihandler.common.ErrorNumbers; +import org.onap.so.apihandler.common.ResponseBuilder; +import org.onap.so.apihandlerinfra.exceptions.ApiException; +import org.onap.so.db.request.beans.OrchestrationTask; +import org.onap.so.db.request.client.RequestsDbClient; +import org.onap.so.logger.ErrorCode; +import org.onap.so.logger.LoggingAnchor; +import org.onap.so.logger.MessageEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import javax.transaction.Transactional; +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import static org.onap.so.apihandlerinfra.Constants.MSO_PROP_APIHANDLER_INFRA; + +@Path("/onap/so/infra/orchestrationTasks") +@OpenAPIDefinition( + info = @Info(title = "onap/so/infra/orchestrationTasks", description = "API Requests for Orchestration Task")) +@Component +public class OrchestrationTasks { + + private static Logger logger = LoggerFactory.getLogger(OrchestrationTasks.class); + + @Autowired + private MsoRequest msoRequest; + + @Autowired + private CamundaRequestHandler camundaRequestHandler; + + @Autowired + private RequestsDbClient requestsDbClient; + + @Autowired + private ResponseBuilder builder; + + private ObjectMapper mapper = new ObjectMapper(); + + @GET + @Path("/{version:[vV][4-7]}/") + @Operation(description = "Find All Orchestrated Task", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) + @Produces(MediaType.APPLICATION_JSON) + @Transactional + public Response getAllOrchestrationTasks(@QueryParam("status") String status, + @PathParam("version") String version) { + List<OrchestrationTask> orchestrationTaskList = requestsDbClient.getAllOrchestrationTasks(); + if (status != null && !status.isEmpty()) { + for (Iterator<OrchestrationTask> it = orchestrationTaskList.iterator(); it.hasNext();) { + OrchestrationTask task = it.next(); + if (!status.equals(task.getStatus())) { + it.remove(); + } + } + } + return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationTaskList, version); + } + + @GET + @Path("/{version:[vV][4-7]}/{taskId}") + @Operation(description = "Find Orchestrated Task for a given TaskId", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) + @Produces(MediaType.APPLICATION_JSON) + @Transactional + public Response getOrchestrationTask(@PathParam("taskId") String taskId, @PathParam("version") String version) + throws ApiException { + try { + OrchestrationTask orchestrationTask = requestsDbClient.getOrchestrationTask(taskId); + return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationTask, version); + } catch (Exception e) { + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.AvailabilityError.getValue(), + "Exception while communciate with Request DB - Orchestration Task Lookup", e); + Response response = + msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, + e.getMessage(), ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB, null, version); + return response; + } + } + + @POST + @Path("/{version:[vV][4-7]}/") + @Operation(description = "Create an Orchestrated Task", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) + @Produces(MediaType.APPLICATION_JSON) + @Transactional + public Response CreateOrchestrationTask(String requestJson, @PathParam("version") String version) { + try { + OrchestrationTask orchestrationTask = mapper.readValue(requestJson, OrchestrationTask.class); + requestsDbClient.createOrchestrationTask(orchestrationTask); + return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationTask, version); + } catch (Exception e) { + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.AvailabilityError.getValue(), + "Exception while communciate with Request DB - Orchestration Task Create", e); + Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, + MsoException.ServiceException, e.getMessage(), ErrorNumbers.COULD_NOT_WRITE_TO_REQUESTS_DB, null, + version); + return response; + } + } + + @PUT + @Path("/{version:[vV][4-7]}/{taskId}") + @Operation(description = "Update an Orchestrated Task", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) + @Produces(MediaType.APPLICATION_JSON) + @Transactional + public Response UpdateOrchestrationTask(@PathParam("taskId") String taskId, String requestJson, + @PathParam("version") String version) { + try { + OrchestrationTask orchestrationTask = requestsDbClient.getOrchestrationTask(taskId); + } catch (Exception e) { + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.AvailabilityError.getValue(), + "Exception while communciate with Request DB - Orchestration Task Update", e); + Response response = + msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, + e.getMessage(), ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB, null, version); + return response; + } + + try { + OrchestrationTask orchestrationTask = mapper.readValue(requestJson, OrchestrationTask.class); + requestsDbClient.updateOrchestrationTask(taskId, orchestrationTask); + return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationTask, version); + } catch (Exception e) { + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.AvailabilityError.getValue(), + "Exception while communciate with Request DB - Orchestration Task Update", e); + Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, + MsoException.ServiceException, e.getMessage(), ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB, null, + version); + return response; + } + } + + @DELETE + @Path("/{version:[vV][4-7]}/{taskId}") + @Operation(description = "Delete an Orchestrated Task", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) + @Produces(MediaType.APPLICATION_JSON) + @Transactional + public Response DeleteOrchestrationTask(@PathParam("taskId") String taskId, @PathParam("version") String version) { + try { + OrchestrationTask orchestrationTask = requestsDbClient.getOrchestrationTask(taskId); + } catch (Exception e) { + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.AvailabilityError.getValue(), + "Exception while communciate with Request DB - Orchestration Task Delete", e); + Response response = + msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, + e.getMessage(), ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB, null, version); + return response; + } + + try { + requestsDbClient.deleteOrchestrationTask(taskId); + return builder.buildResponse(HttpStatus.SC_OK, null, null, version); + } catch (Exception e) { + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.AvailabilityError.getValue(), + "Exception while communciate with Request DB - Orchestration Task Delete", e); + Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, + MsoException.ServiceException, e.getMessage(), ErrorNumbers.COULD_NOT_WRITE_TO_REQUESTS_DB, null, + version); + return response; + } + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java index 75b7e74d49..38fb1596d0 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java @@ -506,8 +506,8 @@ public class RequestHandlerUtils extends AbstractRestHandler { if (instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID) != null) { currentActiveReq.setInstanceGroupId(instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID)); } - if (instanceIdMap.get("PnfId") != null) { - currentActiveReq.setPnfId(instanceIdMap.get("PnfId")); + if (instanceIdMap.get("pnfName") != null) { + currentActiveReq.setPnfName(instanceIdMap.get("pnfName")); } } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandler.java index 0d0e6ee92f..d9955352c6 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandler.java @@ -6,6 +6,8 @@ * ================================================================================ * Modifications Copyright (c) 2019 Samsung * ================================================================================ + * Modifications Copyright (c) 2020 Nordix + * ================================================================================ * 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 @@ -21,36 +23,23 @@ */ package org.onap.so.apihandlerinfra; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.TreeSet; -import java.util.Comparator; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; -import javax.transaction.Transactional; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Response; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.swagger.v3.oas.annotations.OpenAPIDefinition; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.info.Info; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; import org.apache.http.HttpStatus; import org.onap.so.apihandler.common.ErrorNumbers; import org.onap.so.apihandler.common.ResponseBuilder; import org.onap.so.apihandlerinfra.exceptions.ValidateException; import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; -import org.onap.so.apihandlerinfra.workflowspecificationbeans.ActivitySequence; -import org.onap.so.apihandlerinfra.workflowspecificationbeans.ArtifactInfo; -import org.onap.so.apihandlerinfra.workflowspecificationbeans.Validation; -import org.onap.so.apihandlerinfra.workflowspecificationbeans.WorkflowInputParameter; -import org.onap.so.apihandlerinfra.workflowspecificationbeans.WorkflowSpecification; -import org.onap.so.apihandlerinfra.workflowspecificationbeans.WorkflowSpecificationList; -import org.onap.so.apihandlerinfra.workflowspecificationbeans.WorkflowSpecifications; -import org.onap.so.db.catalog.beans.ActivitySpec; -import org.onap.so.db.catalog.beans.ActivitySpecUserParameters; -import org.onap.so.db.catalog.beans.UserParameters; -import org.onap.so.db.catalog.beans.Workflow; -import org.onap.so.db.catalog.beans.WorkflowActivitySpecSequence; +import org.onap.so.apihandlerinfra.workflowspecificationbeans.*; +import org.onap.so.db.catalog.beans.*; import org.onap.so.db.catalog.client.CatalogDbClient; import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; @@ -58,16 +47,15 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import io.swagger.v3.oas.annotations.OpenAPIDefinition; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.info.Info; -import io.swagger.v3.oas.annotations.media.ArraySchema; -import io.swagger.v3.oas.annotations.media.Content; -import io.swagger.v3.oas.annotations.media.Schema; -import io.swagger.v3.oas.annotations.responses.ApiResponse; +import javax.transaction.Transactional; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Response; +import java.util.*; +import java.util.stream.Collectors; + @Path("onap/so/infra/workflowSpecifications") @OpenAPIDefinition(info = @Info(title = "onap/so/infra/workflowSpecifications", @@ -84,6 +72,7 @@ public class WorkflowSpecificationsHandler { private static Logger logger = LoggerFactory.getLogger(WorkflowSpecificationsHandler.class); private static final String ARTIFACT_TYPE_WORKFLOW = "workflow"; private static final String NATIVE_WORKFLOW = "native"; + private static final String EMPTY_BODY = ""; @Path("/{version:[vV]1}/workflows") @GET @@ -125,24 +114,29 @@ public class WorkflowSpecificationsHandler { Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Workflow::getArtifactUUID))), ArrayList::new)); - WorkflowSpecifications workflowSpecifications = mapWorkflowsToWorkflowSpecifications(retWorkflows); + Optional<String> optional = getResponseByWorkflowSpec(retWorkflows); + return builder.buildResponse(HttpStatus.SC_OK, "", optional.isPresent() ? optional.get() : EMPTY_BODY, + apiVersion); + } - String jsonResponse; - try { - ObjectMapper mapper = new ObjectMapper(); - jsonResponse = mapper.writeValueAsString(workflowSpecifications); - } catch (JsonProcessingException e) { - ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError) - .build(); - ValidateException validateException = - new ValidateException.Builder("Mapping of request to JSON object failed : " + e.getMessage(), - HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) - .errorInfo(errorLoggerInfo).build(); - throw validateException; - } + @Path("/{version:[vV]1}/pnfWorkflows") + @GET + @Operation(description = "Finds pnf workflow specifications", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) + @Transactional + public Response getWorkflowsSpecForPnf(@PathParam("version") String version) throws Exception { + + final String pnf_resource = "pnf"; + String apiVersion = version.substring(1); + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - return builder.buildResponse(HttpStatus.SC_OK, "", jsonResponse, apiVersion); + List<Workflow> workflows = catalogDbClient.findWorkflowByResourceTarget(pnf_resource); + + Optional<String> optional = getResponseByWorkflowSpec(workflows); + return builder.buildResponse(HttpStatus.SC_OK, "", optional.isPresent() ? optional.get() : EMPTY_BODY, + apiVersion); } protected WorkflowSpecifications mapWorkflowsToWorkflowSpecifications(List<Workflow> workflows) { @@ -165,6 +159,28 @@ public class WorkflowSpecificationsHandler { return workflowSpecifications; } + private Optional<String> getResponseByWorkflowSpec(List<Workflow> workflows) throws ValidateException { + WorkflowSpecifications workflowSpecifications = mapWorkflowsToWorkflowSpecifications(workflows); + + try { + ObjectMapper mapper = new ObjectMapper(); + return Optional.of(mapper.writeValueAsString(workflowSpecifications)); + } catch (JsonProcessingException e) { + catchAndThrowValidationEx(e); + } + return Optional.empty(); + } + + private Response catchAndThrowValidationEx(JsonProcessingException e) throws ValidateException { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError).build(); + ValidateException validateException = + new ValidateException.Builder("Mapping of request to JSON object failed : " + e.getMessage(), + HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo) + .build(); + throw validateException; + } + private ArtifactInfo buildArtifactInfo(Workflow workflow) { ArtifactInfo artifactInfo = new ArtifactInfo(); artifactInfo.setArtifactType(ARTIFACT_TYPE_WORKFLOW); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidation.java index c05ef98fbb..01c7fd33f9 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidation.java @@ -29,20 +29,13 @@ import com.google.common.base.Strings; public class CustomWorkflowValidation implements ValidationRule { + /** + * This function should be generic both for custom VNF workflow and PNF workflow + */ @Override public ValidationInformation validate(ValidationInformation info) throws ValidationException { RequestParameters requestParameters = info.getSir().getRequestDetails().getRequestParameters(); - CloudConfiguration cloudConfiguration = info.getSir().getRequestDetails().getCloudConfiguration(); - if (cloudConfiguration == null) { - // throw new ValidationException("cloudConfiguration"); - } else if (Strings.isNullOrEmpty((cloudConfiguration.getCloudOwner()))) { - // throw new ValidationException("cloudOwner"); - } else if (Strings.isNullOrEmpty((cloudConfiguration.getLcpCloudRegionId()))) { - // throw new ValidationException("lcpCloudRegionId"); - } else if (Strings.isNullOrEmpty((cloudConfiguration.getTenantId()))) { - // throw new ValidationException("tenantId"); - } if (requestParameters == null) { throw new ValidationException("requestParameters"); } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java index 5c78af3601..ba7fe2b9cb 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java @@ -192,11 +192,12 @@ public class InstanceManagementTest extends BaseTest { requestReferences.setRequestSelfLink(createExpectedSelfLink("v1", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = instanceManagementUri + "v1" - + "/serviceInstances/5df8b6de-2083-11e7-93ae-92361f002676/pnfs/testpnfcId/workflows/81526781-e55c-4cb7-adb3-97e09d9c76bf"; + + "/serviceInstances/5df8b6de-2083-11e7-93ae-92361f002676/pnfs/testPnfName/workflows/81526781-e55c-4cb7-adb3-97e09d9c76bf"; ResponseEntity<String> response = sendRequest(inputStream("/ExecutePNFCustomWorkflow.json"), uri, HttpMethod.POST, headers); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); + ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandlerTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandlerTest.java index 7af92cb8ef..21e6d53c14 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandlerTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandlerTest.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (c) 2020 Nordix + * ================================================================================ * 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 @@ -20,30 +22,15 @@ package org.onap.so.apihandlerinfra; -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.get; -import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; -import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.List; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; import org.json.JSONException; import org.junit.Test; import org.onap.so.apihandlerinfra.workflowspecificationbeans.WorkflowInputParameter; import org.onap.so.apihandlerinfra.workflowspecificationbeans.WorkflowSpecifications; -import org.onap.so.db.catalog.beans.ActivitySpec; -import org.onap.so.db.catalog.beans.ActivitySpecUserParameters; -import org.onap.so.db.catalog.beans.UserParameters; -import org.onap.so.db.catalog.beans.Workflow; -import org.onap.so.db.catalog.beans.WorkflowActivitySpecSequence; +import org.onap.so.db.catalog.beans.*; import org.skyscreamer.jsonassert.JSONAssert; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -53,10 +40,19 @@ import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.util.ResourceUtils; import org.springframework.web.util.UriComponentsBuilder; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.List; +import static com.github.tomakehurst.wiremock.client.WireMock.*; +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; public class WorkflowSpecificationsHandlerTest extends BaseTest { @Autowired @@ -65,12 +61,13 @@ public class WorkflowSpecificationsHandlerTest extends BaseTest { @Value("${wiremock.server.port}") private String wiremockPort; - private final String basePath = "onap/so/infra/workflowSpecifications/v1/workflows"; + private final String basePath = "onap/so/infra/workflowSpecifications"; @Test public void queryWorkflowSpecificationsByVnfModelUUID_Test_Success() throws ParseException, JSONException, JsonParseException, JsonMappingException, IOException { + final String urlPath = basePath + "/v1/workflows"; HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON); headers.set("Content-Type", MediaType.APPLICATION_JSON); @@ -147,7 +144,7 @@ public class WorkflowSpecificationsHandlerTest extends BaseTest { .withBody(getWiremockResponseForCatalogdb("UserParameters6_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath)) + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(urlPath)) .queryParam("vnfModelVersionId", "b5fa707a-f55a-11e7-a796-005056856d52"); ResponseEntity<String> response = @@ -174,7 +171,7 @@ public class WorkflowSpecificationsHandlerTest extends BaseTest { @Test public void mapWorkflowsToWorkflowSpecifications_Test_Success() throws Exception { - List<Workflow> workflows = new ArrayList<Workflow>(); + List<Workflow> workflows = new ArrayList<>(); Workflow workflow = new Workflow(); workflow.setArtifactUUID("ab6478e4-ea33-3346-ac12-ab121484a333"); workflow.setArtifactName("inPlaceSoftwareUpdate-1_0.bpmn"); @@ -267,8 +264,7 @@ public class WorkflowSpecificationsHandlerTest extends BaseTest { activitySpecUserParameter6.setUserParameters(userParameter6); activitySpecUserParameters.add(activitySpecUserParameter6); - List<WorkflowActivitySpecSequence> workflowActivitySpecSequences = - new ArrayList<WorkflowActivitySpecSequence>(); + List<WorkflowActivitySpecSequence> workflowActivitySpecSequences = new ArrayList<>(); ActivitySpec activitySpec1 = new ActivitySpec(); activitySpec1.setName("VNFQuiesceTrafficActivity"); @@ -325,9 +321,9 @@ public class WorkflowSpecificationsHandlerTest extends BaseTest { } @Test - public void queryWorkflowSpecificationsByPnfModelUUID_Test_Success() - throws ParseException, JSONException, JsonParseException, JsonMappingException, IOException { + public void queryWorkflowSpecificationsByPnfModelUUID_Test_Success() throws JSONException, IOException { + final String urlPath = basePath + "/v1/workflows"; HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON); headers.set("Content-Type", MediaType.APPLICATION_JSON); @@ -345,7 +341,7 @@ public class WorkflowSpecificationsHandlerTest extends BaseTest { .withBody(getWiremockResponseForCatalogdb("Empty_workflowActivitySpecSequence_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath)) + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(urlPath)) .queryParam("pnfModelVersionId", "f2d1f2b2-88bb-49da-b716-36ae420ccbff"); ResponseEntity<String> response = @@ -370,6 +366,54 @@ public class WorkflowSpecificationsHandlerTest extends BaseTest { assertEquals("1.0.0", response.getHeaders().get("X-LatestVersion").get(0)); } + @Test + public void testWorkflowSpecificationsForPnf_Success() throws JSONException, IOException { + + final String urlPath = basePath + "/v1/pnfWorkflows"; + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity(null, headers); + + wireMockServer.stubFor(get(urlMatching("/workflow/search/findByResourceTarget[?]resource_target=pnf")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody( + getWiremockResponseForCatalogdb("WorkflowSpecificationsForPnfWorkflows_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching("/infraActiveRequests.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching("/workflow/1/workflowActivitySpecSequence")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("Empty_workflowActivitySpecSequence_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(urlPath)); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class); + + assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + + WorkflowSpecifications expectedResponse = mapper.readValue( + new String(Files.readAllBytes( + Paths.get("src/test/resources/__files/catalogdb/WorkflowSpecificationsForPnf.json"))), + WorkflowSpecifications.class); + WorkflowSpecifications realResponse = mapper.readValue(response.getBody(), WorkflowSpecifications.class); + + assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); + assertThat(expectedResponse, sameBeanAs(realResponse)); + assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0)); + assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); + assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); + assertEquals("1.0.0", response.getHeaders().get("X-LatestVersion").get(0)); + } + private String getWiremockResponseForCatalogdb(String file) { try { File resource = ResourceUtils.getFile("classpath:__files/catalogdb/" + file); diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ExecutePNFCustomWorkflow.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ExecutePNFCustomWorkflow.json index 63021b611f..09f94b61a4 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ExecutePNFCustomWorkflow.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ExecutePNFCustomWorkflow.json @@ -1,20 +1,47 @@ { - "requestDetails": { - "requestParameters": { - "userParams": [{ - "nrmObj": { - "EUtranGenericCell" : [ - {"cellLocalId":1, "pci":5}, - {"cellLocalId":2, "pci":6} - ], - "ExternalEUtranCell" : [ - {"cellLocalId":3, "eNBId": "x"}, - {"cellLocalId":4, "eNBId": "y"} - ], - "EUtranRelation": [{"scellLocalId":5, "tcellLocalId":6}] - } - }], - "payload": "[{\"GNBDUFunction\":{\"gNBId\":1,\"gNBDUId\":5}}]" - } - } + "requestDetails":{ + "subscriberInfo":{ + "globalSubscriberId":"Test" + }, + "requestInfo":{ + "suppressRollback": false, + "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", + "requestorId": "tester", + "instanceName":"testInstanceName", + "source":"test" + }, + "cloudConfiguration":{ + "lcpCloudRegionId": "RegionOne", + "tenantId": "7320ec4a5b9d4589ba7c4412ccfd290f", + "cloudOwner": "CloudOwner" + }, + "requestParameters":{ + "subscriptionServiceType": "test", + "userParams":[ + { + "name": "key1", + "value": "val1" + }, + { + "name": "key2", + "value": "val2" + }], + "aLaCarte": false, + "payload": "{\"k1\": \"v1\"}" + }, + "project":{ + "projectName": "Test" + }, + "owningEntity":{ + "owningEntityId":"67f2e84c-734d-4e90-a1e4-d2ffa2e75849", + "owningEntityName":"OE-Test" + }, + "modelInfo":{ + "modelVersion": "2.0", + "modelVersionId": "test-version-id", + "modelInvariantId": "test-invariantUUID", + "modelName": "test-name", + "modelType": "pnf" + } + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/Empty_workflowActivitySpecSequence_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/Empty_workflowActivitySpecSequence_Response.json index 89675e8f02..6779c1f3e4 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/Empty_workflowActivitySpecSequence_Response.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/Empty_workflowActivitySpecSequence_Response.json @@ -2,4 +2,4 @@ "_embedded": { "workflowActivitySpecSequence": [] } -} +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecificationsForPnf.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecificationsForPnf.json index 257b9dc843..b5b93873c8 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecificationsForPnf.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecificationsForPnf.json @@ -17,4 +17,4 @@ } } ] -} +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecificationsForPnfWorkflows_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecificationsForPnfWorkflows_Response.json new file mode 100644 index 0000000000..2447617897 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecificationsForPnfWorkflows_Response.json @@ -0,0 +1,41 @@ +{ + "_embedded": { + "workflow": [ + { + "artifactChecksum": "MANUAL RECORD", + "artifactName": "DummyPnfWorkflow", + "artifactUUID": "b2fd5627-55e4-4f4f-8064-9e6f443e9152", + "body": null, + "created": "2020-02-18T08:28:15.000+0000", + "description": "Dummy Pnf Workflow to test custom Pnf workflow", + "id": 4, + "name": "Dummy Pnf Workflow", + "operationName": "DummyPnfWorkflow", + "pnfResourceWorkflow": null, + "resourceTarget": "pnf", + "source": "native", + "timeoutMinutes": null, + "version": 1.0, + "_links": { + "self": { + "href": "http://localhost:8090/workflow/search/findByResourceTarget?resource_target=pnf" + }, + "workflow": { + "href": "http://localhost:8090/workflow/4" + }, + "workflowActivitySpecSequence": { + "href": "http://localhost:8090/workflow/4/workflowActivitySpecSequence" + } + } + } + ] + }, + "_links": { + "self": { + "href": "http://localhost:8090/workflow/search/findByResourceTarget?resource_target=pnf" + }, + "workflowActivitySpecSequence": { + "href": "http://localhost:8090/workflow/4/workflowActivitySpecSequence" + } + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql b/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql index 050780c9a2..1a1e9bec79 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql @@ -1262,7 +1262,7 @@ CREATE TABLE `infra_active_requests` ( `END_TIME` datetime DEFAULT NULL, `SOURCE` varchar(45) DEFAULT NULL, `VNF_ID` varchar(45) DEFAULT NULL, - `PNF_ID` varchar(45) DEFAULT NULL, + `PNF_NAME` varchar(45) DEFAULT NULL, `VNF_NAME` varchar(80) DEFAULT NULL, `VNF_TYPE` varchar(200) DEFAULT NULL, `SERVICE_TYPE` varchar(45) DEFAULT NULL, diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImpl.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImpl.java index bba0ad4696..da8f30ab1e 100644 --- a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImpl.java +++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImpl.java @@ -245,8 +245,8 @@ public class InfraActiveRequestsRepositoryImpl implements InfraActiveRequestsRep mapKey = "serviceInstanceName"; } else if ("vnfInstanceId".equalsIgnoreCase(mapKey)) { mapKey = "vnfId"; - } else if ("pnfId".equalsIgnoreCase(mapKey)) { - mapKey = "pnfId"; + } else if ("pnfName".equalsIgnoreCase(mapKey)) { + mapKey = "pnfName"; } else if ("vnfInstanceName".equalsIgnoreCase(mapKey)) { mapKey = "vnfName"; } else if ("vfModuleInstanceId".equalsIgnoreCase(mapKey)) { diff --git a/mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/db/request/OrchestrationTaskTest.java b/mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/db/request/OrchestrationTaskTest.java new file mode 100644 index 0000000000..0b2aae6730 --- /dev/null +++ b/mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/db/request/OrchestrationTaskTest.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.db.request; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.so.TestApplication; +import org.onap.so.db.request.beans.OrchestrationTask; +import org.onap.so.db.request.data.repository.OrchestrationTaskRepository; +import org.onap.so.db.request.exceptions.NoEntityFoundException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; +import javax.transaction.Transactional; +import java.util.Date; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = TestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@ActiveProfiles("test") +public class OrchestrationTaskTest { + + @Autowired + private OrchestrationTaskRepository repository; + + @Test + @Transactional + public void timeStampCreated() throws NoEntityFoundException { + + final String testTaskId = "test-task-id"; + final String testRequestId = "test-request-id"; + final String testTaskName = "test-task-name"; + final String testTaskStatus = "test-task-status"; + final String testIsManual = "test-is-manual"; + OrchestrationTask task = new OrchestrationTask(); + + task.setTaskId(testTaskId); + task.setRequestId(testRequestId); + task.setName(testTaskName); + task.setStatus(testTaskStatus); + task.setIsManual(testIsManual); + repository.saveAndFlush(task); + + OrchestrationTask found = + repository.findById(testTaskId).orElseThrow(() -> new NoEntityFoundException("Cannot Find Task")); + + Date createdTime = found.getCreatedTime(); + assertNotNull(createdTime); + assertEquals(testTaskId, found.getTaskId()); + assertEquals(testRequestId, found.getRequestId()); + assertEquals(testTaskName, found.getName()); + assertEquals(testTaskStatus, found.getStatus()); + assertEquals(testIsManual, found.getIsManual()); + } +} diff --git a/mso-api-handlers/mso-requests-db-repositories/src/test/resources/schema.sql b/mso-api-handlers/mso-requests-db-repositories/src/test/resources/schema.sql index 4f6c19f4d0..1efd125c2b 100644 --- a/mso-api-handlers/mso-requests-db-repositories/src/test/resources/schema.sql +++ b/mso-api-handlers/mso-requests-db-repositories/src/test/resources/schema.sql @@ -64,7 +64,7 @@ CREATE TABLE IF NOT EXISTS PUBLIC.INFRA_ACTIVE_REQUESTS( END_TIME VARCHAR, SOURCE VARCHAR SELECTIVITY 2, VNF_ID VARCHAR SELECTIVITY 15, - PNF_ID VARCHAR SELECTIVITY 15, + PNF_NAME VARCHAR SELECTIVITY 15, VNF_NAME VARCHAR SELECTIVITY 11, VNF_TYPE VARCHAR SELECTIVITY 5, SERVICE_TYPE VARCHAR SELECTIVITY 1, @@ -246,14 +246,14 @@ CREATE CACHED TABLE PUBLIC.WATCHDOG_SERVICE_MOD_VER_ID_LOOKUP( INSERT INTO PUBLIC.WATCHDOG_SERVICE_MOD_VER_ID_LOOKUP(DISTRIBUTION_ID, SERVICE_MODEL_VERSION_ID, CREATE_TIME, MODIFY_TIME) VALUES ('1533c4bd-a3e3-493f-a16d-28c20614415e', '7e813ab5-88d3-4fcb-86c0-498c5d7eef9a', '2017-11-30 15:48:08', '2017-11-30 15:48:08'), ('55429711-809b-4a3b-9ee5-5120d46d9de0', 'cc031e75-4442-4d1a-b774-8a2b434e0a50', '2017-11-30 16:35:36', '2017-11-30 16:35:36'), -('67f0b2d1-9013-4b2b-9914-bbe2288284fb', 'eade1e9d-c1ec-4ef3-bc31-60570fba1573', '2017-11-30 15:54:39', '2017-11-30 15:54:39'); +('67f0b2d1-9013-4b2b-9914-bbe2288284fb', 'eade1e9d-c1ec-4ef3-bc31-60570fba1573', '2017-11-30 15:54:39', '2017-11-30 15:54:39'); -ALTER TABLE PUBLIC.INFRA_ACTIVE_REQUESTS ADD CONSTRAINT PUBLIC.CONSTRAINT_E PRIMARY KEY(REQUEST_ID); -ALTER TABLE PUBLIC.SITE_STATUS ADD CONSTRAINT PUBLIC.CONSTRAINT_C PRIMARY KEY(SITE_NAME); +ALTER TABLE PUBLIC.INFRA_ACTIVE_REQUESTS ADD CONSTRAINT PUBLIC.CONSTRAINT_E PRIMARY KEY(REQUEST_ID); +ALTER TABLE PUBLIC.SITE_STATUS ADD CONSTRAINT PUBLIC.CONSTRAINT_C PRIMARY KEY(SITE_NAME); ALTER TABLE PUBLIC.WATCHDOG_DISTRIBUTIONID_STATUS ADD CONSTRAINT PUBLIC.CONSTRAINT_7 PRIMARY KEY(DISTRIBUTION_ID); ALTER TABLE PUBLIC.WATCHDOG_PER_COMPONENT_DISTRIBUTION_STATUS ADD CONSTRAINT PUBLIC.CONSTRAINT_D PRIMARY KEY(DISTRIBUTION_ID, COMPONENT_NAME); -ALTER TABLE PUBLIC.WATCHDOG_SERVICE_MOD_VER_ID_LOOKUP ADD CONSTRAINT PUBLIC.CONSTRAINT_6 PRIMARY KEY(DISTRIBUTION_ID, SERVICE_MODEL_VERSION_ID); -ALTER TABLE PUBLIC.WATCHDOG_PER_COMPONENT_DISTRIBUTION_STATUS ADD CONSTRAINT PUBLIC.CONSTRAINT_DE FOREIGN KEY(DISTRIBUTION_ID) REFERENCES PUBLIC.WATCHDOG_DISTRIBUTIONID_STATUS(DISTRIBUTION_ID) NOCHECK; +ALTER TABLE PUBLIC.WATCHDOG_SERVICE_MOD_VER_ID_LOOKUP ADD CONSTRAINT PUBLIC.CONSTRAINT_6 PRIMARY KEY(DISTRIBUTION_ID, SERVICE_MODEL_VERSION_ID); +ALTER TABLE PUBLIC.WATCHDOG_PER_COMPONENT_DISTRIBUTION_STATUS ADD CONSTRAINT PUBLIC.CONSTRAINT_DE FOREIGN KEY(DISTRIBUTION_ID) REFERENCES PUBLIC.WATCHDOG_DISTRIBUTIONID_STATUS(DISTRIBUTION_ID) NOCHECK; CREATE TABLE `orchestration_task` ( `TASK_ID` varchar(200) NOT NULL, diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraActiveRequests.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraActiveRequests.java index 5848f3b3d9..9b246460b8 100644 --- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraActiveRequests.java +++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraActiveRequests.java @@ -72,15 +72,15 @@ public class InfraActiveRequests extends InfraRequests { .append("statusMessage", getStatusMessage()).append("progress", getProgress()) .append("startTime", getStartTime()).append("endTime", getEndTime()).append("source", getSource()) .append("vnfId", getVnfId()).append("vnfName", getVnfName()).append("vnfType", getVnfType()) - .append("pnfId", getPnfId()).append("serviceType", getServiceType()).append("tenantId", getTenantId()) - .append("vnfParams", getVnfParams()).append("vnfOutputs", getVnfOutputs()) - .append("requestBody", getRequestBody()).append("responseBody", getResponseBody()) - .append("lastModifiedBy", getLastModifiedBy()).append("modifyTime", getModifyTime()) - .append("volumeGroupId", getVolumeGroupId()).append("volumeGroupName", getVolumeGroupName()) - .append("vfModuleId", getVfModuleId()).append("vfModuleName", getVfModuleName()) - .append("vfModuleModelName", getVfModuleModelName()).append("CloudRegion", getCloudRegion()) - .append("callBackUrl", getCallBackUrl()).append("correlator", getCorrelator()) - .append("serviceInstanceId", getServiceInstanceId()) + .append("pnfName", getPnfName()).append("serviceType", getServiceType()) + .append("tenantId", getTenantId()).append("vnfParams", getVnfParams()) + .append("vnfOutputs", getVnfOutputs()).append("requestBody", getRequestBody()) + .append("responseBody", getResponseBody()).append("lastModifiedBy", getLastModifiedBy()) + .append("modifyTime", getModifyTime()).append("volumeGroupId", getVolumeGroupId()) + .append("volumeGroupName", getVolumeGroupName()).append("vfModuleId", getVfModuleId()) + .append("vfModuleName", getVfModuleName()).append("vfModuleModelName", getVfModuleModelName()) + .append("CloudRegion", getCloudRegion()).append("callBackUrl", getCallBackUrl()) + .append("correlator", getCorrelator()).append("serviceInstanceId", getServiceInstanceId()) .append("serviceInstanceName", getServiceInstanceName()).append("requestScope", getRequestScope()) .append("requestAction", getRequestAction()).append("networkId", getNetworkId()) .append("networkName", getNetworkName()).append("networkType", getNetworkType()) diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraRequests.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraRequests.java index 8f798a207c..6d6b5a825e 100644 --- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraRequests.java +++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraRequests.java @@ -74,8 +74,8 @@ public abstract class InfraRequests implements java.io.Serializable { private String source; @Column(name = "VNF_ID", length = 45) private String vnfId; - @Column(name = "PNF_ID", length = 45) - private String pnfId; + @Column(name = "PNF_NAME", length = 45) + private String pnfName; @Column(name = "VNF_NAME", length = 80) private String vnfName; @Column(name = "VNF_TYPE", length = 200) @@ -249,12 +249,12 @@ public abstract class InfraRequests implements java.io.Serializable { this.vnfId = vnfId; } - public String getPnfId() { - return this.pnfId; + public String getPnfName() { + return this.pnfName; } - public void setPnfId(String pnfId) { - this.pnfId = pnfId; + public void setPnfName(String pnfName) { + this.pnfName = pnfName; } public String getVnfName() { @@ -592,7 +592,7 @@ public abstract class InfraRequests implements java.io.Serializable { .append("flowStatus", getFlowStatus()).append("retryStatusMessage", getRetryStatusMessage()) .append("progress", getProgress()).append("startTime", getStartTime()).append("endTime", getEndTime()) .append("source", getSource()).append("vnfId", getVnfId()).append("vnfName", getVnfName()) - .append("pnfId", getPnfId()).append("vnfType", getVnfType()).append("serviceType", getServiceType()) + .append("pnfName", getPnfName()).append("vnfType", getVnfType()).append("serviceType", getServiceType()) .append("tenantId", getTenantId()).append("vnfParams", getVnfParams()) .append("vnfOutputs", getVnfOutputs()).append("requestBody", getRequestBody()) .append("responseBody", getResponseBody()).append("lastModifiedBy", getLastModifiedBy()) diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/client/CatalogDbClient.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/client/CatalogDbClient.java index cf066f9721..26c33941ed 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/client/CatalogDbClient.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/client/CatalogDbClient.java @@ -7,9 +7,9 @@ * 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. @@ -158,6 +158,7 @@ public class CatalogDbClient { protected static final String HOMING_INSTANCE = "/homingInstance"; protected static final String ARTIFACT_UUID = "artifactUUID"; protected static final String SOURCE = "source"; + protected static final String RESOURCE_TARGET = "resource_target"; private static final String TARGET_ENTITY = "SO:CatalogDB"; private static final String ASTERISK = "*"; @@ -209,6 +210,7 @@ public class CatalogDbClient { private String findVnfResourceCustomizationByModelUuid = "/findVnfResourceCustomizationByModelUuid"; private String findBBNameSelectionReferenceByControllerActorAndScopeAndAction = "/findBBNameSelectionReferenceByControllerActorAndScopeAndAction"; + private String findWorkflowByResourceTarget = "/findByResourceTarget"; private String serviceURI; private String vfModuleURI; @@ -348,6 +350,7 @@ public class CatalogDbClient { findWorkflowByVnfModelUUID = endpoint + WORKFLOW + SEARCH + findWorkflowByVnfModelUUID; findWorkflowByPnfModelUUID = endpoint + WORKFLOW + SEARCH + findWorkflowByPnfModelUUID; findWorkflowBySource = endpoint + WORKFLOW + SEARCH + findWorkflowBySource; + findWorkflowByResourceTarget = endpoint + WORKFLOW + SEARCH + findWorkflowByResourceTarget; findVnfResourceCustomizationByModelUuid = endpoint + VNF_RESOURCE_CUSTOMIZATION + SEARCH + findVnfResourceCustomizationByModelUuid; @@ -1084,6 +1087,11 @@ public class CatalogDbClient { getUri(UriBuilder.fromUri(findWorkflowBySource).queryParam(SOURCE, source).build().toString())); } + public List<Workflow> findWorkflowByResourceTarget(String resourceTarget) { + return this.getMultipleResources(workflowClient, getUri(UriBuilder.fromUri(findWorkflowByResourceTarget) + .queryParam(RESOURCE_TARGET, resourceTarget).build().toString())); + } + public String getEndpoint() { return endpoint; } diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/WorkflowRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/WorkflowRepository.java index 91c6940e95..93ec54a2eb 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/WorkflowRepository.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/WorkflowRepository.java @@ -7,9 +7,9 @@ * 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. @@ -33,6 +33,8 @@ public interface WorkflowRepository extends JpaRepository<Workflow, Integer> { List<Workflow> findBySource(String source); + List<Workflow> findByResourceTarget(String resourceTarget); + /** * Used to fetch the @{link Workflow} by the Model UUID. * diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientTest.java index 66fc0f5dc5..79e3cbcc08 100644 --- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientTest.java +++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientTest.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (c) 2020 Nordix + * ================================================================================ * 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 @@ -179,7 +181,7 @@ public class CatalogDbClientTest { } @Test - public final void testFindWorkflowByPnfModelUUID() throws Exception { + public final void testFindWorkflowByPnfModelUUID() { String pnfResourceModelUUID = "f2d1f2b2-88bb-49da-b716-36ae420ccbff"; doReturn(new ArrayList()).when(catalogDbClient).getMultipleResources(any(), any()); @@ -190,4 +192,16 @@ public class CatalogDbClientTest { } + @Test + public final void testFindWorkflowByResourceTarget() { + // when + final String pnf_resource = "pnf"; + doReturn(new ArrayList()).when(catalogDbClient).getMultipleResources(any(), any()); + catalogDbClient.findWorkflowByResourceTarget(pnf_resource); + + // verify + verify(catalogDbClient).getMultipleResources(any(Client.class), eq(UriBuilder.fromUri("/findByResourceTarget") + .queryParam(CatalogDbClient.RESOURCE_TARGET, pnf_resource).build())); + } + } diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/WorkflowRepositoryTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/WorkflowRepositoryTest.java index b07e82b8a8..e47c61d8b4 100644 --- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/WorkflowRepositoryTest.java +++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/WorkflowRepositoryTest.java @@ -55,4 +55,14 @@ public class WorkflowRepositoryTest extends BaseTest { Assert.assertTrue("testingWorkflow.bpmn".equals(workflows.get(0).getArtifactName())); } + @Test + public void findByResourceTargetTest() { + List<Workflow> workflows = workflowRepository.findByResourceTarget("pnf"); + + Assert.assertTrue(workflows != null); + Assert.assertTrue(workflows.size() == 1); + + Assert.assertTrue("DummyPnfWorkflow".equals(workflows.get(0).getArtifactName())); + } + } diff --git a/version.properties b/version.properties index 9eb3b93ac9..a0756adf2b 100644 --- a/version.properties +++ b/version.properties @@ -3,8 +3,8 @@ # because they are used in Jenkins, whose plug-in doesn't support major=1 -minor=5 -patch=3 +minor=6 +patch=0 base_version=${major}.${minor}.${patch} |