diff options
Diffstat (limited to 'vnfm-simulator/vnfm-service')
10 files changed, 387 insertions, 64 deletions
diff --git a/vnfm-simulator/vnfm-service/pom.xml b/vnfm-simulator/vnfm-service/pom.xml index 7beccb6561..1e3244bae4 100644 --- a/vnfm-simulator/vnfm-service/pom.xml +++ b/vnfm-simulator/vnfm-service/pom.xml @@ -44,6 +44,11 @@ <scope>runtime</scope> </dependency> <dependency> + <groupId>org.springframework.security.oauth</groupId> + <artifactId>spring-security-oauth2</artifactId> + <version>2.3.6.RELEASE</version> + </dependency> + <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> diff --git a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/config/ApplicationConfig.java b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/config/ApplicationConfig.java index 32c05ebca8..a1abb05f07 100644 --- a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/config/ApplicationConfig.java +++ b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/config/ApplicationConfig.java @@ -1,6 +1,5 @@ package org.onap.svnfm.simulator.config; -import java.net.InetAddress; import java.util.Arrays; import org.onap.svnfm.simulator.constants.Constant; import org.springframework.beans.factory.annotation.Autowired; @@ -23,6 +22,9 @@ public class ApplicationConfig implements ApplicationRunner { @Value("${server.dns.name:so-vnfm-simulator.onap}") private String serverDnsName; + @Value("${server.request.grant.auth:oauth}") + private String grantAuth; + @Autowired private Environment environment; @@ -37,6 +39,10 @@ public class ApplicationConfig implements ApplicationRunner { return baseUrl; } + public String getGrantAuth() { + return grantAuth; + } + @Bean public CacheManager cacheManager() { final Cache inlineResponse201 = new ConcurrentMapCache(Constant.IN_LINE_RESPONSE_201_CACHE); diff --git a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/controller/SvnfmController.java b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/controller/SvnfmController.java index d3ff66aed0..2140b57488 100644 --- a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/controller/SvnfmController.java +++ b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/controller/SvnfmController.java @@ -26,7 +26,6 @@ import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.CreateVnfRequest; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse200; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse2001; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201; -import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InstantiateVnfRequest; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.LccnSubscriptionRequest; import org.onap.svnfm.simulator.constants.Constant; import org.onap.svnfm.simulator.repository.VnfmCacheRepository; @@ -101,13 +100,12 @@ public class SvnfmController { * @throws InterruptedException */ @PostMapping(value = "/vnf_instances/{vnfInstanceId}/instantiate") - public ResponseEntity<Void> instantiateVnf(@PathVariable("vnfInstanceId") final String vnfId, - @RequestBody final InstantiateVnfRequest instantiateVNFRequest) { - LOGGER.info("Start instantiateVNFRequest {} ", instantiateVNFRequest); + public ResponseEntity<Void> instantiateVnf(@PathVariable("vnfInstanceId") final String vnfId) { + LOGGER.info("Start instantiateVNFRequest for vnf id {} ", vnfId); final HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); - headers.add(HttpHeaders.LOCATION, svnfmService.instantiateVnf(vnfId, instantiateVNFRequest)); + headers.add(HttpHeaders.LOCATION, svnfmService.instantiateVnf(vnfId)); return new ResponseEntity<>(headers, HttpStatus.ACCEPTED); } diff --git a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/oauth/AuthorizationServerConfig.java b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/oauth/AuthorizationServerConfig.java new file mode 100644 index 0000000000..5d2c310635 --- /dev/null +++ b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/oauth/AuthorizationServerConfig.java @@ -0,0 +1,28 @@ +package org.onap.svnfm.simulator.oauth; + +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; +import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; + +@Configuration +@EnableAuthorizationServer +@Profile("oauth-authentication") +/** + * Configures the authorization server for oauth token based authentication when the spring profile + * "oauth-authentication" is active + */ +public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { + + private static final int ONE_DAY = 60 * 60 * 24; + + @Override + public void configure(final ClientDetailsServiceConfigurer clients) throws Exception { + clients.inMemory().withClient("vnfmadapter") + .secret("$2a$10$dHzTlqSBcm8hdO52LBvnX./zNTvUzzJy.lZrc4bCBL5gkln0wX6T6") + .authorizedGrantTypes("client_credentials").scopes("write").accessTokenValiditySeconds(ONE_DAY) + .refreshTokenValiditySeconds(ONE_DAY); + } + +} diff --git a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/oauth/JsonSerializerConfiguration.java b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/oauth/JsonSerializerConfiguration.java new file mode 100644 index 0000000000..d6eda28eb6 --- /dev/null +++ b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/oauth/JsonSerializerConfiguration.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.svnfm.simulator.oauth; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import java.util.ArrayList; +import java.util.Collection; +import org.springframework.boot.autoconfigure.http.HttpMessageConverters; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.json.GsonHttpMessageConverter; +import org.springframework.security.oauth2.common.OAuth2AccessToken; + +/** + * Configures message converter + */ +@Configuration +public class JsonSerializerConfiguration { + + @Bean + public HttpMessageConverters customConverters() { + final Collection<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); + + final Gson gson = new GsonBuilder() + .registerTypeHierarchyAdapter(OAuth2AccessToken.class, new OAuth2AccessTokenAdapter()).create(); + final GsonHttpMessageConverter gsonHttpMessageConverter = new GsonHttpMessageConverter(gson); + messageConverters.add(gsonHttpMessageConverter); + return new HttpMessageConverters(true, messageConverters); + } +} diff --git a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/oauth/OAuth2AccessTokenAdapter.java b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/oauth/OAuth2AccessTokenAdapter.java new file mode 100644 index 0000000000..7bccffa2e0 --- /dev/null +++ b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/oauth/OAuth2AccessTokenAdapter.java @@ -0,0 +1,31 @@ +package org.onap.svnfm.simulator.oauth; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import java.lang.reflect.Type; +import org.springframework.security.oauth2.common.OAuth2AccessToken; + +public class OAuth2AccessTokenAdapter implements JsonSerializer<OAuth2AccessToken> { + + @Override + public JsonElement serialize(final OAuth2AccessToken src, final Type typeOfSrc, + final JsonSerializationContext context) { + final JsonObject obj = new JsonObject(); + obj.addProperty(OAuth2AccessToken.ACCESS_TOKEN, src.getValue()); + obj.addProperty(OAuth2AccessToken.TOKEN_TYPE, src.getTokenType()); + if (src.getRefreshToken() != null) { + obj.addProperty(OAuth2AccessToken.REFRESH_TOKEN, src.getRefreshToken().getValue()); + } + obj.addProperty(OAuth2AccessToken.EXPIRES_IN, src.getExpiresIn()); + final JsonArray scopeObj = new JsonArray(); + for (final String scope : src.getScope()) { + scopeObj.add(scope); + } + obj.add(OAuth2AccessToken.SCOPE, scopeObj); + + return obj; + } +} diff --git a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/oauth/OAuth2ResourceServer.java b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/oauth/OAuth2ResourceServer.java new file mode 100644 index 0000000000..18fb1a9461 --- /dev/null +++ b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/oauth/OAuth2ResourceServer.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.svnfm.simulator.oauth; + +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; +import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; + +@Configuration +@EnableResourceServer +@Profile("oauth-authentication") +/** + * Enforces oauth token based authentication when the spring profile "oauth-authentication" is active + */ +public class OAuth2ResourceServer extends ResourceServerConfigurerAdapter { + +} diff --git a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/services/OperationProgressor.java b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/services/OperationProgressor.java index 83f079c376..6e9478bdeb 100644 --- a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/services/OperationProgressor.java +++ b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/services/OperationProgressor.java @@ -1,11 +1,24 @@ package org.onap.svnfm.simulator.services; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; import java.nio.charset.StandardCharsets; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.UnrecoverableKeyException; +import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.List; import java.util.UUID; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.KeyManager; +import javax.net.ssl.KeyManagerFactory; import javax.ws.rs.core.MediaType; import org.apache.commons.codec.binary.Base64; import org.modelmapper.ModelMapper; @@ -30,6 +43,7 @@ import org.onap.so.adapters.vnfmadapter.extclients.vnfm.lcn.model.VnfLcmOperatio import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse200; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201InstantiatedVnfInfoVnfcResourceInfo; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.SubscriptionsAuthenticationParamsBasic; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.SubscriptionsAuthenticationParamsOauth2ClientCredentials; import org.onap.svnfm.simulator.config.ApplicationConfig; import org.onap.svnfm.simulator.model.VnfOperation; import org.onap.svnfm.simulator.model.Vnfds; @@ -37,12 +51,16 @@ import org.onap.svnfm.simulator.repository.VnfOperationRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; public abstract class OperationProgressor implements Runnable { private static final Logger LOGGER = LoggerFactory.getLogger(OperationProgressor.class); private static final String CERTIFICATE_TO_TRUST = "so-vnfm-adapter.crt.pem"; + private Resource keyStoreResource = new ClassPathResource("so-vnfm-simulator.p12"); + private String keyStorePassword = "7Em3&j4.19xYiMelhD5?xbQ."; + protected final VnfOperation operation; protected final SvnfmService svnfmService; private final VnfOperationRepository vnfOperationRepository; @@ -66,12 +84,14 @@ public abstract class OperationProgressor implements Runnable { String callBackUrl = subscriptionService.getSubscriptions().iterator().next().getCallbackUri(); callBackUrl = callBackUrl.substring(0, callBackUrl.indexOf("/lcn/")); apiClient.setBasePath(callBackUrl); + apiClient.setKeyManagers(getKeyManagers()); apiClient.setSslCaCert(getCertificateToTrust()); notificationClient = new DefaultApi(apiClient); final org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.ApiClient grantApiClient = new org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.ApiClient(); grantApiClient.setBasePath(callBackUrl); + grantApiClient.setKeyManagers(getKeyManagers()); grantApiClient.setSslCaCert(getCertificateToTrust()); grantClient = new org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.api.DefaultApi(grantApiClient); } @@ -85,6 +105,22 @@ public abstract class OperationProgressor implements Runnable { } } + private KeyManager[] getKeyManagers() { + KeyStore keystore; + try { + keystore = KeyStore.getInstance("pkcs12"); + keystore.load(keyStoreResource.getInputStream(), keyStorePassword.toCharArray()); + KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509"); + keyManagerFactory.init(keystore, keyStorePassword.toCharArray()); + return keyManagerFactory.getKeyManagers(); + } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException + | UnrecoverableKeyException exception) { + LOGGER.error("Error reading certificate, https calls using two way TLS to VNFM adapter will fail", + exception); + return new KeyManager[0]; + } + } + @Override public void run() { try { @@ -187,7 +223,8 @@ public abstract class OperationProgressor implements Runnable { final String auth = subscriptionAuthentication.getUserName() + ":" + subscriptionAuthentication.getPassword(); final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.ISO_8859_1)); - final String authHeader = "Basic " + new String(encodedAuth); + String authHeader = "Basic " + new String(encodedAuth); + notificationClient.lcnVnfLcmOperationOccurrenceNotificationPostWithHttpInfo(notification, MediaType.APPLICATION_JSON, authHeader); } catch (final ApiException exception) { @@ -235,8 +272,17 @@ public abstract class OperationProgressor implements Runnable { private InlineResponse201 sendGrantRequest(final GrantRequest grantRequest) { LOGGER.info("Sending grant request: {}", grantRequest); try { + + final SubscriptionsAuthenticationParamsOauth2ClientCredentials subscriptionAuthentication = + subscriptionService.getSubscriptions().iterator().next().getAuthentication() + .getParamsOauth2ClientCredentials(); + + final String authHeader = applicationConfig.getGrantAuth().equals("oauth") + ? "Bearer " + getToken(notificationClient.getApiClient(), subscriptionAuthentication) + : null; + final ApiResponse<InlineResponse201> response = grantClient.grantsPostWithHttpInfo(grantRequest, - MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON, "Basic dm5mbTpwYXNzd29yZDEk"); + MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON, authHeader); LOGGER.info("Grant Response: {}", response); return response.getData(); } catch (final org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.ApiException exception) { @@ -257,4 +303,46 @@ public abstract class OperationProgressor implements Runnable { return applicationConfig.getBaseUrl() + "/vnflcm/v1"; } + private String getToken(final ApiClient apiClient, + final SubscriptionsAuthenticationParamsOauth2ClientCredentials oauthClientCredentials) { + final String basePath = apiClient.getBasePath().substring(0, apiClient.getBasePath().indexOf("/so/")); + final String tokenUrl = basePath + "/oauth/token?grant_type=client_credentials"; + + try { + URL url = new URL(tokenUrl); + HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); + connection.setRequestMethod("POST"); + final String authorizationHeader = getAuthorizationHeader(oauthClientCredentials); + connection.addRequestProperty("Authorization", authorizationHeader); + + connection.connect(); + + return getResponse(connection).get("access_token").getAsString(); + + } catch (IOException exception) { + LOGGER.error("Error getting token", exception); + return null; + } + } + + private String getAuthorizationHeader( + final SubscriptionsAuthenticationParamsOauth2ClientCredentials oauthClientCredentials) { + final String auth = oauthClientCredentials.getClientId() + ":" + oauthClientCredentials.getClientPassword(); + final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.UTF_8)); + return "Basic " + new String(encodedAuth); + } + + private JsonObject getResponse(HttpsURLConnection connection) throws IOException { + BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); + String line, data = ""; + while ((line = in.readLine()) != null) { + data += line; + } + in.close(); + connection.getInputStream().close(); + + JsonObject jsonObject = new JsonParser().parse(data).getAsJsonObject(); + return jsonObject; + } + } diff --git a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/services/SvnfmService.java b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/services/SvnfmService.java index 21bb00dba7..95043d35ed 100644 --- a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/services/SvnfmService.java +++ b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/services/SvnfmService.java @@ -32,7 +32,6 @@ import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201.InstantiationStateEnum; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201InstantiatedVnfInfo; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201VimConnectionInfo; -import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InstantiateVnfRequest; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.LccnSubscriptionRequest; import org.onap.svnfm.simulator.config.ApplicationConfig; import org.onap.svnfm.simulator.constants.Constant; @@ -60,36 +59,31 @@ import org.springframework.stereotype.Service; @Service public class SvnfmService { - @Autowired - VnfmRepository vnfmRepository; - - @Autowired - VnfOperationRepository vnfOperationRepository; - - @Autowired + private VnfmRepository vnfmRepository; + private VnfOperationRepository vnfOperationRepository; private VnfmHelper vnfmHelper; - - @Autowired - ApplicationConfig applicationConfig; - - @Autowired - CacheManager cacheManager; - - @Autowired - Vnfds vnfds; - - @Autowired - SubscriptionService subscriptionService; + private ApplicationConfig applicationConfig; + private CacheManager cacheManager; + private Vnfds vnfds; + private SubscriptionService subscriptionService; private final ExecutorService executor = Executors.newCachedThreadPool(); private static final Logger LOGGER = LoggerFactory.getLogger(SvnfmService.class); - /** - * - * @param createVNFRequest - * @return inlineResponse201 - */ + @Autowired + public SvnfmService(VnfmRepository vnfmRepository, VnfOperationRepository vnfOperationRepository, + VnfmHelper vnfmHelper, ApplicationConfig applicationConfig, CacheManager cacheManager, Vnfds vnfds, + SubscriptionService subscriptionService) { + this.vnfmRepository = vnfmRepository; + this.vnfOperationRepository = vnfOperationRepository; + this.vnfmHelper = vnfmHelper; + this.applicationConfig = applicationConfig; + this.cacheManager = cacheManager; + this.vnfds = vnfds; + this.subscriptionService = subscriptionService; + } + public InlineResponse201 createVnf(final CreateVnfRequest createVNFRequest, final String id) { InlineResponse201 inlineResponse201 = null; try { @@ -106,24 +100,16 @@ public class SvnfmService { } @CachePut(value = Constant.IN_LINE_RESPONSE_201_CACHE, key = "#id") - public InlineResponse201 updateVnf(final InstantiationStateEnum instantiationState, + public void updateVnf(final InstantiationStateEnum instantiationState, final InlineResponse201InstantiatedVnfInfo instantiatedVnfInfo, final String id, final List<InlineResponse201VimConnectionInfo> vimConnectionInfo) { final InlineResponse201 vnf = getVnf(id); vnf.setInstantiatedVnfInfo(instantiatedVnfInfo); vnf.setInstantiationState(instantiationState); vnf.setVimConnectionInfo(vimConnectionInfo); - return vnf; } - /** - * - * @param vnfId - * @param instantiateVNFRequest - * @param operationId - * @throws InterruptedException - */ - public String instantiateVnf(final String vnfId, final InstantiateVnfRequest instantiateVNFRequest) { + public String instantiateVnf(final String vnfId) { final VnfOperation vnfOperation = buildVnfOperation(InlineResponse200.OperationEnum.INSTANTIATE, vnfId); vnfOperationRepository.save(vnfOperation); executor.submit(new InstantiateOperationProgressor(vnfOperation, this, vnfOperationRepository, @@ -131,13 +117,7 @@ public class SvnfmService { return vnfOperation.getId(); } - /** - * vnfOperationRepository - * - * @param vnfId - * @param instantiateOperationId - */ - public VnfOperation buildVnfOperation(final InlineResponse200.OperationEnum operation, final String vnfId) { + private VnfOperation buildVnfOperation(final InlineResponse200.OperationEnum operation, final String vnfId) { final VnfOperation vnfOperation = new VnfOperation(); vnfOperation.setId(UUID.randomUUID().toString()); vnfOperation.setOperation(operation); @@ -146,11 +126,6 @@ public class SvnfmService { return vnfOperation; } - /** - * - * @param operationId - * @throws InterruptedException - */ public InlineResponse200 getOperationStatus(final String operationId) { LOGGER.info("Getting operation status with id: {}", operationId); final Thread instantiationNotification = new Thread(new VnfInstantiationNotification()); @@ -165,14 +140,13 @@ public class SvnfmService { return null; } - /** - * - * @param vnfId - * @return inlineResponse201 - */ public InlineResponse201 getVnf(final String vnfId) { final Cache ca = cacheManager.getCache(Constant.IN_LINE_RESPONSE_201_CACHE); + if (ca == null) + return null; final SimpleValueWrapper wrapper = (SimpleValueWrapper) ca.get(vnfId); + if (wrapper == null) + return null; final InlineResponse201 inlineResponse201 = (InlineResponse201) wrapper.get(); if (inlineResponse201 != null) { LOGGER.info("Cache Read Successful"); @@ -181,10 +155,6 @@ public class SvnfmService { return null; } - /** - * @param vnfId - * @return - */ public String terminateVnf(final String vnfId) { final VnfOperation vnfOperation = buildVnfOperation(InlineResponse200.OperationEnum.TERMINATE, vnfId); vnfOperationRepository.save(vnfOperation); diff --git a/vnfm-simulator/vnfm-service/src/test/java/org/onap/svnfm/simulator/services/SvnfmServiceTest.java b/vnfm-simulator/vnfm-service/src/test/java/org/onap/svnfm/simulator/services/SvnfmServiceTest.java new file mode 100644 index 0000000000..ed77775421 --- /dev/null +++ b/vnfm-simulator/vnfm-service/src/test/java/org/onap/svnfm/simulator/services/SvnfmServiceTest.java @@ -0,0 +1,112 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.svnfm.simulator.services; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import org.junit.Before; +import org.junit.Test; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201; +import org.onap.svnfm.simulator.config.ApplicationConfig; +import org.onap.svnfm.simulator.constants.Constant; +import org.onap.svnfm.simulator.model.Vnfds; +import org.onap.svnfm.simulator.repository.VnfOperationRepository; +import org.onap.svnfm.simulator.repository.VnfmRepository; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.cache.support.SimpleValueWrapper; + +public class SvnfmServiceTest { + + private SvnfmService testedObject; + private CacheManager cacheManagerMock; + + @Before + public void setup() { + VnfmRepository vnfmRepositoryMock = mock(VnfmRepository.class); + VnfOperationRepository vnfOperationRepositoryMock = mock(VnfOperationRepository.class); + VnfmHelper vnfmHelperMock = mock(VnfmHelper.class); + ApplicationConfig applicationConfigMock = mock(ApplicationConfig.class); + cacheManagerMock = mock(CacheManager.class); + Vnfds vnfdsMock = mock(Vnfds.class); + SubscriptionService subscriptionServiceMock = mock(SubscriptionService.class); + + testedObject = new SvnfmService(vnfmRepositoryMock, vnfOperationRepositoryMock, vnfmHelperMock, + applicationConfigMock, cacheManagerMock, vnfdsMock, subscriptionServiceMock); + } + + @Test + public void getVnfSuccessful() { + // given + String vnfId = "vnfId"; + String vnfInstanceName = "testVnf"; + Cache cacheMock = mock(Cache.class); + SimpleValueWrapper simpleValueWrapperMock = mock(SimpleValueWrapper.class); + when(cacheManagerMock.getCache(Constant.IN_LINE_RESPONSE_201_CACHE)).thenReturn(cacheMock); + when(cacheMock.get(vnfId)).thenReturn(simpleValueWrapperMock); + when(simpleValueWrapperMock.get()).thenReturn(prepareInlineResponse(vnfId, vnfInstanceName)); + // when + InlineResponse201 result = testedObject.getVnf(vnfId); + // then + assertThat(result.getVnfdId()).isEqualTo(vnfId); + assertThat(result.getVnfInstanceName()).isEqualTo(vnfInstanceName); + } + + @Test + public void getVnf_ifCacheNullThenReturnNull() { + // given + when(cacheManagerMock.getCache(Constant.IN_LINE_RESPONSE_201_CACHE)).thenReturn(null); + // then + assertThat(testedObject.getVnf("any")).isNull(); + } + + @Test + public void getVnf_ifWrapperNullThenReturnNull() { + // given + String vnfId = "vnfId"; + Cache cacheMock = mock(Cache.class); + when(cacheManagerMock.getCache(Constant.IN_LINE_RESPONSE_201_CACHE)).thenReturn(cacheMock); + when(cacheMock.get(vnfId)).thenReturn(null); + // then + assertThat(testedObject.getVnf(vnfId)).isNull(); + } + + @Test + public void getVnf_ifResultIsNullThenReturnNull() { + // when + String vnfId = "vnfId"; + Cache cacheMock = mock(Cache.class); + SimpleValueWrapper simpleValueWrapperMock = mock(SimpleValueWrapper.class); + when(cacheManagerMock.getCache(Constant.IN_LINE_RESPONSE_201_CACHE)).thenReturn(cacheMock); + when(cacheMock.get(vnfId)).thenReturn(simpleValueWrapperMock); + when(simpleValueWrapperMock.get()).thenReturn(null); + // then + assertThat(testedObject.getVnf(vnfId)).isNull(); + } + + private InlineResponse201 prepareInlineResponse(String vnfId, String vnfInstanceName) { + InlineResponse201 response201 = new InlineResponse201(); + response201.setVnfdId(vnfId); + response201.vnfInstanceName(vnfInstanceName); + return response201; + } +} |