From 0e9a90774a86475f40d4e946798cf765910a31f6 Mon Sep 17 00:00:00 2001 From: Fiete Ostkamp Date: Wed, 17 Apr 2024 16:06:40 +0200 Subject: [PATCH] Refactor Babel related code in model-loader - introduce BabelArtifactService - simplify babel http client by removing factory and https support Issue-ID: AAI-3827 Change-Id: I5c004d342687c8aaa8f26927342752d472f05da3 Signed-off-by: Fiete Ostkamp --- pom.xml | 2 +- .../onap/aai/modelloader/babel/BabelArtifact.java | 35 +++ .../modelloader/babel/BabelArtifactService.java | 100 ++++++++ .../onap/aai/modelloader/config/BeanConfig.java | 1 - .../notification/ArtifactDownloadManager.java | 97 +------- .../notification/BabelArtifactConverter.java | 4 +- .../modelloader/restclient/BabelServiceClient.java | 4 +- .../restclient/BabelServiceClientImpl.java | 99 ++++++++ .../restclient/HttpsBabelServiceClient.java | 257 --------------------- .../service/HttpsBabelServiceClientFactory.java | 56 ----- .../modelloader/BabelClientTestConfiguration.java | 57 +++++ .../ArtifactDownloadManagerVnfcTest.java | 14 +- .../notification/ModelArtifactHandlerTest.java | 2 - .../notification/TestArtifactDownloadManager.java | 22 +- .../restclient/MockBabelServiceClient.java | 5 +- .../restclient/TestBabelServiceClient.java | 52 ++--- .../modelloader/service/TestModelController.java | 7 +- 17 files changed, 350 insertions(+), 464 deletions(-) create mode 100644 src/main/java/org/onap/aai/modelloader/babel/BabelArtifact.java create mode 100644 src/main/java/org/onap/aai/modelloader/babel/BabelArtifactService.java create mode 100644 src/main/java/org/onap/aai/modelloader/restclient/BabelServiceClientImpl.java delete mode 100644 src/main/java/org/onap/aai/modelloader/restclient/HttpsBabelServiceClient.java delete mode 100644 src/main/java/org/onap/aai/modelloader/service/HttpsBabelServiceClientFactory.java create mode 100644 src/test/java/org/onap/aai/modelloader/BabelClientTestConfiguration.java diff --git a/pom.xml b/pom.xml index 1bf31f4..2efcd39 100644 --- a/pom.xml +++ b/pom.xml @@ -33,7 +33,7 @@ org.onap.aai.model-loader model-loader aai-model-loader - 1.13.6-SNAPSHOT + 1.14.0-SNAPSHOT diff --git a/src/main/java/org/onap/aai/modelloader/babel/BabelArtifact.java b/src/main/java/org/onap/aai/modelloader/babel/BabelArtifact.java new file mode 100644 index 0000000..6de318b --- /dev/null +++ b/src/main/java/org/onap/aai/modelloader/babel/BabelArtifact.java @@ -0,0 +1,35 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2024 Deutsche Telekom AG Intellectual Property. 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.aai.modelloader.babel; + +import org.onap.aai.modelloader.entity.ArtifactType; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class BabelArtifact { + String name; + public ArtifactType type; + String payload; +} diff --git a/src/main/java/org/onap/aai/modelloader/babel/BabelArtifactService.java b/src/main/java/org/onap/aai/modelloader/babel/BabelArtifactService.java new file mode 100644 index 0000000..1221861 --- /dev/null +++ b/src/main/java/org/onap/aai/modelloader/babel/BabelArtifactService.java @@ -0,0 +1,100 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2024 Deutsche Telekom AG Intellectual Property. 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.aai.modelloader.babel; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.onap.aai.babel.service.data.BabelArtifact; +import org.onap.aai.babel.service.data.BabelRequest; +import org.onap.aai.babel.service.data.BabelArtifact.ArtifactType; +import org.onap.aai.cl.api.Logger; +import org.onap.aai.cl.eelf.LoggerFactory; +import org.onap.aai.modelloader.entity.Artifact; +import org.onap.aai.modelloader.entity.model.BabelArtifactParsingException; +import org.onap.aai.modelloader.notification.BabelArtifactConverter; +import org.onap.aai.modelloader.notification.ProcessToscaArtifactsException; +import org.onap.aai.modelloader.restclient.BabelServiceClient; +import org.onap.aai.modelloader.service.ModelLoaderMsgs; +import org.springframework.stereotype.Service; + +@Service +public class BabelArtifactService { + + private static Logger logger = LoggerFactory.getInstance().getLogger(BabelArtifactService.class); + + private final BabelServiceClient babelServiceClient; + private final BabelArtifactConverter babelArtifactConverter; + + public BabelArtifactService(BabelServiceClient babelServiceClient, BabelArtifactConverter babelArtifactConverter) { + this.babelServiceClient = babelServiceClient; + this.babelArtifactConverter = babelArtifactConverter; + } + + public void invokeBabelService(List modelArtifacts, List catalogArtifacts, BabelRequest babelRequest, String distributionId) + throws ProcessToscaArtifactsException { + try { + logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, + "Posting artifact: " + babelRequest.getArtifactName() + ", service version: " + babelRequest.getArtifactVersion() + + ", artifact version: " + babelRequest.getArtifactVersion()); + + List babelArtifacts = + babelServiceClient.postArtifact(babelRequest, distributionId); + + // Sort Babel artifacts based on type + Map> artifactMap = + babelArtifacts.stream().collect(Collectors.groupingBy(BabelArtifact::getType)); + + if (artifactMap.containsKey(BabelArtifact.ArtifactType.MODEL)) { + modelArtifacts.addAll( + babelArtifactConverter.convertToModel(artifactMap.get(BabelArtifact.ArtifactType.MODEL))); + artifactMap.remove(BabelArtifact.ArtifactType.MODEL); + } + + if (artifactMap.containsKey(BabelArtifact.ArtifactType.VNFCATALOG)) { + catalogArtifacts.addAll(babelArtifactConverter + .convertToCatalog(artifactMap.get(BabelArtifact.ArtifactType.VNFCATALOG))); + artifactMap.remove(BabelArtifact.ArtifactType.VNFCATALOG); + } + + // Log unexpected artifact types + if (!artifactMap.isEmpty()) { + logger.warn(ModelLoaderMsgs.ARTIFACT_PARSE_ERROR, + babelRequest.getArtifactName() + " " + babelRequest.getArtifactVersion() + + ". Unexpected artifact types returned by the babel service: " + + artifactMap.keySet().toString()); + } + + } catch (BabelArtifactParsingException e) { + logger.error(ModelLoaderMsgs.ARTIFACT_PARSE_ERROR, + "Error for artifact " + babelRequest.getArtifactName() + " " + babelRequest.getArtifactVersion() + " " + e); + throw new ProcessToscaArtifactsException( + "An error occurred while trying to parse the Babel artifacts: " + e.getLocalizedMessage()); + } catch (Exception e) { + logger.error(ModelLoaderMsgs.BABEL_REST_REQUEST_ERROR, e, "POST", + "Error posting artifact " + babelRequest.getArtifactName() + " " + babelRequest.getArtifactVersion() + " to Babel: " + + e.getLocalizedMessage()); + throw new ProcessToscaArtifactsException( + "An error occurred while calling the Babel service: " + e.getLocalizedMessage()); + } + } + +} diff --git a/src/main/java/org/onap/aai/modelloader/config/BeanConfig.java b/src/main/java/org/onap/aai/modelloader/config/BeanConfig.java index 63956e2..cc6702b 100644 --- a/src/main/java/org/onap/aai/modelloader/config/BeanConfig.java +++ b/src/main/java/org/onap/aai/modelloader/config/BeanConfig.java @@ -30,7 +30,6 @@ import org.onap.aai.cl.eelf.LoggerFactory; import org.onap.aai.modelloader.service.ModelLoaderMsgs; import org.onap.sdc.api.IDistributionClient; import org.onap.sdc.impl.DistributionClientFactory; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/src/main/java/org/onap/aai/modelloader/notification/ArtifactDownloadManager.java b/src/main/java/org/onap/aai/modelloader/notification/ArtifactDownloadManager.java index dcec799..f0c96bd 100644 --- a/src/main/java/org/onap/aai/modelloader/notification/ArtifactDownloadManager.java +++ b/src/main/java/org/onap/aai/modelloader/notification/ArtifactDownloadManager.java @@ -24,24 +24,18 @@ import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Base64; import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; -import org.onap.aai.babel.service.data.BabelArtifact; -import org.onap.aai.babel.service.data.BabelArtifact.ArtifactType; +import org.onap.aai.babel.service.data.BabelRequest; import org.onap.aai.cl.api.Logger; import org.onap.aai.cl.eelf.LoggerFactory; import org.onap.aai.cl.mdc.MdcContext; import org.onap.aai.cl.mdc.MdcOverride; -import org.onap.aai.modelloader.config.ModelLoaderConfig; +import org.onap.aai.modelloader.babel.BabelArtifactService; import org.onap.aai.modelloader.entity.Artifact; import org.onap.aai.modelloader.entity.model.BabelArtifactParsingException; import org.onap.aai.modelloader.entity.model.IModelParser; import org.onap.aai.modelloader.entity.model.NamedQueryArtifactParser; import org.onap.aai.modelloader.extraction.InvalidArchiveException; import org.onap.aai.modelloader.extraction.VnfCatalogExtractor; -import org.onap.aai.modelloader.restclient.BabelServiceClient; -import org.onap.aai.modelloader.restclient.BabelServiceClientException; -import org.onap.aai.modelloader.service.BabelServiceClientFactory; import org.onap.aai.modelloader.service.ModelLoaderMsgs; import org.onap.sdc.api.IDistributionClient; import org.onap.sdc.api.notification.IArtifactInfo; @@ -68,19 +62,15 @@ public class ArtifactDownloadManager { private final IDistributionClient client; private final NotificationPublisher notificationPublisher; - private final BabelArtifactConverter babelArtifactConverter; - private final ModelLoaderConfig config; - private final BabelServiceClientFactory clientFactory; private final VnfCatalogExtractor vnfCatalogExtractor; + private final BabelArtifactService babelArtifactService; - public ArtifactDownloadManager(IDistributionClient client, ModelLoaderConfig config, - BabelServiceClientFactory clientFactory, BabelArtifactConverter babelArtifactConverter, NotificationPublisher notificationPublisher, VnfCatalogExtractor vnfCatalogExtractor) { + public ArtifactDownloadManager(IDistributionClient client, + NotificationPublisher notificationPublisher, VnfCatalogExtractor vnfCatalogExtractor, BabelArtifactService babelArtifactService) { this.client = client; this.notificationPublisher = notificationPublisher; - this.babelArtifactConverter = babelArtifactConverter; - this.config = config; - this.clientFactory = clientFactory; this.vnfCatalogExtractor = vnfCatalogExtractor; + this.babelArtifactService = babelArtifactService; } /** @@ -158,7 +148,11 @@ public class ArtifactDownloadManager { IArtifactInfo artifactInfo, String distributionId, String serviceVersion) throws ProcessToscaArtifactsException, InvalidArchiveException { // Get translated artifacts from Babel Service - invokeBabelService(modelArtifacts, catalogArtifacts, payload, artifactInfo, distributionId, serviceVersion); + BabelRequest babelRequest = new BabelRequest(); + babelRequest.setArtifactName(artifactInfo.getArtifactName()); + babelRequest.setCsar(Base64.getEncoder().encodeToString(payload)); + babelRequest.setArtifactVersion(serviceVersion); + babelArtifactService.invokeBabelService(modelArtifacts, catalogArtifacts, babelRequest, distributionId); // Get VNF Catalog artifacts directly from CSAR List csarCatalogArtifacts = vnfCatalogExtractor.extract(payload, artifactInfo.getArtifactName()); @@ -173,75 +167,6 @@ public class ArtifactDownloadManager { } } - public void invokeBabelService(List modelArtifacts, List catalogArtifacts, byte[] payload, - IArtifactInfo artifactInfo, String distributionId, String serviceVersion) - throws ProcessToscaArtifactsException { - try { - BabelServiceClient babelClient = createBabelServiceClient(artifactInfo, serviceVersion); - - logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, - "Posting artifact: " + artifactInfo.getArtifactName() + ", service version: " + serviceVersion - + ", artifact version: " + artifactInfo.getArtifactVersion()); - - List babelArtifacts = - babelClient.postArtifact(payload, artifactInfo.getArtifactName(), serviceVersion, distributionId); - - // Sort Babel artifacts based on type - Map> artifactMap = - babelArtifacts.stream().collect(Collectors.groupingBy(BabelArtifact::getType)); - - if (artifactMap.containsKey(BabelArtifact.ArtifactType.MODEL)) { - modelArtifacts.addAll( - babelArtifactConverter.convertToModel(artifactMap.get(BabelArtifact.ArtifactType.MODEL))); - artifactMap.remove(BabelArtifact.ArtifactType.MODEL); - } - - if (artifactMap.containsKey(BabelArtifact.ArtifactType.VNFCATALOG)) { - catalogArtifacts.addAll(babelArtifactConverter - .convertToCatalog(artifactMap.get(BabelArtifact.ArtifactType.VNFCATALOG))); - artifactMap.remove(BabelArtifact.ArtifactType.VNFCATALOG); - } - - // Log unexpected artifact types - if (!artifactMap.isEmpty()) { - logger.warn(ModelLoaderMsgs.ARTIFACT_PARSE_ERROR, - artifactInfo.getArtifactName() + " " + serviceVersion - + ". Unexpected artifact types returned by the babel service: " - + artifactMap.keySet().toString()); - } - - } catch (BabelArtifactParsingException e) { - logger.error(ModelLoaderMsgs.ARTIFACT_PARSE_ERROR, - "Error for artifact " + artifactInfo.getArtifactName() + " " + serviceVersion + e); - throw new ProcessToscaArtifactsException( - "An error occurred while trying to parse the Babel artifacts: " + e.getLocalizedMessage()); - } catch (Exception e) { - logger.error(ModelLoaderMsgs.BABEL_REST_REQUEST_ERROR, e, "POST", config.getBabelBaseUrl(), - "Error posting artifact " + artifactInfo.getArtifactName() + " " + serviceVersion + " to Babel: " - + e.getLocalizedMessage()); - throw new ProcessToscaArtifactsException( - "An error occurred while calling the Babel service: " + e.getLocalizedMessage()); - } - } - - BabelServiceClient createBabelServiceClient(IArtifactInfo artifact, String serviceVersion) - throws ProcessToscaArtifactsException { - BabelServiceClient babelClient; - try { - logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Creating Babel client"); - babelClient = clientFactory.create(config); - } catch (BabelServiceClientException e) { - logger.error(ModelLoaderMsgs.BABEL_REST_REQUEST_ERROR, e, "POST", config.getBabelBaseUrl(), - "Error posting artifact " + artifact.getArtifactName() + " " + serviceVersion + " to Babel: " - + e.getLocalizedMessage()); - throw new ProcessToscaArtifactsException( - "An error occurred tyring to convert the tosca artifacts to xml artifacts: " - + e.getLocalizedMessage()); - } - - return babelClient; - } - private void processModelQuerySpecArtifact(List modelArtifacts, IDistributionClientDownloadResult downloadResult) throws BabelArtifactParsingException { logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Processing named query artifact."); diff --git a/src/main/java/org/onap/aai/modelloader/notification/BabelArtifactConverter.java b/src/main/java/org/onap/aai/modelloader/notification/BabelArtifactConverter.java index 480a461..5118652 100644 --- a/src/main/java/org/onap/aai/modelloader/notification/BabelArtifactConverter.java +++ b/src/main/java/org/onap/aai/modelloader/notification/BabelArtifactConverter.java @@ -46,7 +46,7 @@ public class BabelArtifactConverter { * @throws BabelArtifactParsingException if an error occurs trying to parse the generated XML files that were * converted from tosca artifacts */ - List convertToModel(List xmlArtifacts) throws BabelArtifactParsingException { + public List convertToModel(List xmlArtifacts) throws BabelArtifactParsingException { Objects.requireNonNull(xmlArtifacts); List modelArtifacts = new ArrayList<>(); ModelArtifactParser modelArtParser = new ModelArtifactParser(); @@ -72,7 +72,7 @@ public class BabelArtifactConverter { * @param xmlArtifacts xml artifacts to be parsed * @return List list of converted catalog artifacts */ - List convertToCatalog(List xmlArtifacts) { + public List convertToCatalog(List xmlArtifacts) { Objects.requireNonNull(xmlArtifacts); List catalogArtifacts = new ArrayList<>(); diff --git a/src/main/java/org/onap/aai/modelloader/restclient/BabelServiceClient.java b/src/main/java/org/onap/aai/modelloader/restclient/BabelServiceClient.java index f69752b..8328c42 100644 --- a/src/main/java/org/onap/aai/modelloader/restclient/BabelServiceClient.java +++ b/src/main/java/org/onap/aai/modelloader/restclient/BabelServiceClient.java @@ -23,10 +23,10 @@ package org.onap.aai.modelloader.restclient; import java.util.List; import org.onap.aai.babel.service.data.BabelArtifact; +import org.onap.aai.babel.service.data.BabelRequest; public interface BabelServiceClient { - List postArtifact(byte[] artifactPayload, String artifactName, String artifactVersion, - String transactionId) throws BabelServiceClientException; + List postArtifact(BabelRequest babelRequest, String transactionId) throws BabelServiceClientException; } diff --git a/src/main/java/org/onap/aai/modelloader/restclient/BabelServiceClientImpl.java b/src/main/java/org/onap/aai/modelloader/restclient/BabelServiceClientImpl.java new file mode 100644 index 0000000..5400892 --- /dev/null +++ b/src/main/java/org/onap/aai/modelloader/restclient/BabelServiceClientImpl.java @@ -0,0 +1,99 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2019 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017-2019 European Software Marketing Ltd. + * ================================================================================ + * 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.aai.modelloader.restclient; + +import java.util.List; +import java.util.stream.Collectors; +import org.onap.aai.babel.service.data.BabelArtifact; +import org.onap.aai.babel.service.data.BabelRequest; +import org.onap.aai.babel.service.data.BabelArtifact.ArtifactType; +import org.onap.aai.cl.api.Logger; +import org.onap.aai.cl.eelf.LoggerFactory; +import org.onap.aai.modelloader.config.ModelLoaderConfig; +import org.onap.aai.modelloader.service.ModelLoaderMsgs; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestTemplate; + +/** + * HTTPS Client for interfacing with Babel. + * + */ +@Component +public class BabelServiceClientImpl implements BabelServiceClient { + + private static final Logger logger = LoggerFactory.getInstance().getLogger(BabelServiceClientImpl.class); + private final ModelLoaderConfig config; + private final RestTemplate restTemplate; + + public BabelServiceClientImpl(ModelLoaderConfig config, RestTemplate restTemplate) { + this.config = config; + this.restTemplate = restTemplate; + } + + @Override + public List postArtifact(BabelRequest babelRequest, String transactionId) throws BabelServiceClientException { + if (logger.isInfoEnabled()) { + logger.info(ModelLoaderMsgs.BABEL_REST_REQUEST_PAYLOAD, " Artifact Name: " + babelRequest.getArtifactName() + + " Artifact version: " + babelRequest.getArtifactVersion() + " Artifact payload: " + babelRequest.getCsar()); + } + + String resourceUrl = config.getBabelBaseUrl() + config.getBabelGenerateArtifactsUrl(); + + HttpHeaders headers = new HttpHeaders(); + headers.set(AaiRestClient.HEADER_TRANS_ID, transactionId); + headers.set(AaiRestClient.HEADER_FROM_APP_ID, AaiRestClient.ML_APP_NAME); + HttpEntity entity = new HttpEntity<>(babelRequest, headers); + + ResponseEntity> artifactResponse = restTemplate.exchange(resourceUrl, HttpMethod.POST, entity, new ParameterizedTypeReference>() {}); + + if (logger.isDebugEnabled()) { + logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, + "Babel response " + artifactResponse.getStatusCode() + " " + artifactResponse.getBody().toString()); + } + + if (!artifactResponse.getStatusCode().equals(HttpStatus.OK)) { + throw new BabelServiceClientException(artifactResponse.getBody().toString()); + } + + List babelArtifact = artifactResponse.getBody().stream() + .map(this::mapBabelDto) + .collect(Collectors.toList()); + + return babelArtifact; + } + + private BabelArtifact mapBabelDto(org.onap.aai.modelloader.babel.BabelArtifact babelDto) { + ArtifactType artifactType = babelDto.getType() == null + ? null + : ArtifactType.valueOf(babelDto.getType().name()); + return new BabelArtifact( + babelDto.getName(), + artifactType, + babelDto.getPayload()); + } +} diff --git a/src/main/java/org/onap/aai/modelloader/restclient/HttpsBabelServiceClient.java b/src/main/java/org/onap/aai/modelloader/restclient/HttpsBabelServiceClient.java deleted file mode 100644 index 0789996..0000000 --- a/src/main/java/org/onap/aai/modelloader/restclient/HttpsBabelServiceClient.java +++ /dev/null @@ -1,257 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2019 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017-2019 European Software Marketing Ltd. - * ================================================================================ - * 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.aai.modelloader.restclient; - -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; -import com.google.json.JsonSanitizer; -import com.sun.jersey.api.client.Client; // NOSONAR -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.api.client.config.DefaultClientConfig; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.security.KeyManagementException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.UnrecoverableKeyException; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import java.util.Base64; -import java.util.Collections; -import java.util.List; -import java.util.Objects; -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.X509TrustManager; -import javax.ws.rs.core.Response; -import org.json.JSONException; -import org.json.JSONObject; -import org.onap.aai.babel.service.data.BabelArtifact; -import org.onap.aai.cl.api.LogFields; -import org.onap.aai.cl.api.LogLine; -import org.onap.aai.cl.api.Logger; -import org.onap.aai.cl.eelf.LoggerFactory; -import org.onap.aai.cl.mdc.MdcContext; -import org.onap.aai.cl.mdc.MdcOverride; -import org.onap.aai.modelloader.config.ModelLoaderConfig; -import org.onap.aai.modelloader.service.ModelLoaderMsgs; - -/** - * HTTPS Client for interfacing with Babel. - * - */ -public class HttpsBabelServiceClient implements BabelServiceClient { - - private static final Logger logger = LoggerFactory.getInstance().getLogger(HttpsBabelServiceClient.class); - private static final Logger metricsLogger = - LoggerFactory.getInstance().getMetricsLogger(HttpsBabelServiceClient.class); - private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); - - private static final String SSL_PROTOCOL = "TLS"; - private static final String KEYSTORE_ALGORITHM = "SunX509"; - private static final String KEYSTORE_TYPE = "PKCS12"; - - private final ModelLoaderConfig config; - private final Client client; - - /** - * @param config - * @throws NoSuchAlgorithmException - * @throws KeyStoreException - * @throws CertificateException - * @throws IOException - * @throws UnrecoverableKeyException - * @throws KeyManagementException - * @throws BabelServiceClientException - */ - public HttpsBabelServiceClient(ModelLoaderConfig config) - throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, - UnrecoverableKeyException, KeyManagementException, BabelServiceClientException { - this.config = config; - - logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Creating Babel Service client"); - //Initialize SSL Context only if SSL is enabled - if (config.useHttpsWithBabel()) { - SSLContext ctx = SSLContext.getInstance(SSL_PROTOCOL); - KeyManagerFactory kmf = KeyManagerFactory.getInstance(KEYSTORE_ALGORITHM); - KeyStore keyStore = KeyStore.getInstance(KEYSTORE_TYPE); - - String clientCertPassword = config.getBabelKeyStorePassword(); - - char[] pwd = null; - if (clientCertPassword != null) { - pwd = clientCertPassword.toCharArray(); - } - - TrustManager[] trustManagers = getTrustManagers(); - - String clientCertFileName = config.getBabelKeyStorePath(); - if (clientCertFileName == null) { - ctx.init(null, trustManagers, null); - } else { - InputStream fin = Files.newInputStream(Paths.get(clientCertFileName)); - keyStore.load(fin, pwd); - kmf.init(keyStore, pwd); - ctx.init(kmf.getKeyManagers(), trustManagers, null); - } - - logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Initialised context"); - - HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory()); - HttpsURLConnection.setDefaultHostnameVerifier((host, session) -> true); - } - - client = Client.create(new DefaultClientConfig()); - client.setConnectTimeout(config.getClientConnectTimeoutMs()); - client.setReadTimeout(config.getClientReadTimeoutMs()); - - logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Jersey client created"); - } - - private TrustManager[] getTrustManagers() throws NoSuchAlgorithmException, KeyStoreException, CertificateException, - IOException, BabelServiceClientException { - TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - // Using null here initializes the TMF with the default trust store. - tmf.init((KeyStore) null); - - // Create a new Trust Manager from the local trust store. - String trustStoreFile = config.getBabelTrustStorePath(); - if (trustStoreFile == null) { - throw new BabelServiceClientException("No Babel trust store defined"); - } - try (InputStream myKeys = Files.newInputStream(Paths.get(trustStoreFile))) { - KeyStore myTrustStore = KeyStore.getInstance(KeyStore.getDefaultType()); - myTrustStore.load(myKeys, config.getBabelTrustStorePassword().toCharArray()); - tmf.init(myTrustStore); - } - X509TrustManager localTm = findX509TrustManager(tmf); - - // Create a custom trust manager that wraps both our trust store and the default. - final X509TrustManager finalLocalTm = localTm; - - // Find the default trust manager. - final X509TrustManager defaultTrustManager = findX509TrustManager(tmf); - - return new TrustManager[] {new X509TrustManager() { - @Override - public X509Certificate[] getAcceptedIssuers() { - return defaultTrustManager.getAcceptedIssuers(); - } - - @Override - public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { - try { - finalLocalTm.checkServerTrusted(chain, authType); - } catch (CertificateException e) { // NOSONAR - defaultTrustManager.checkServerTrusted(chain, authType); - } - } - - @Override - public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { - defaultTrustManager.checkClientTrusted(chain, authType); - } - }}; - } - - private X509TrustManager findX509TrustManager(TrustManagerFactory tmf) { - X509TrustManager trustManager = null; - for (TrustManager tm : tmf.getTrustManagers()) { - if (tm instanceof X509TrustManager) { - trustManager = (X509TrustManager) tm; - break; - } - } - return trustManager; - } - - /** - * @param artifactPayload - * @param artifactName - * @param artifactVersion - * @param transactionId - * @return - * @throws BabelServiceClientException - * @throws JSONException - */ - @Override - public List postArtifact(byte[] artifactPayload, String artifactName, String artifactVersion, - String transactionId) throws BabelServiceClientException { - Objects.requireNonNull(artifactPayload); - - String encodedPayload = Base64.getEncoder().encodeToString(artifactPayload); - - JSONObject obj = new JSONObject(); - try { - obj.put("csar", encodedPayload); - obj.put("artifactVersion", artifactVersion); - obj.put("artifactName", artifactName); - } catch (JSONException ex) { - throw new BabelServiceClientException(ex); - } - - if (logger.isInfoEnabled()) { - logger.info(ModelLoaderMsgs.BABEL_REST_REQUEST_PAYLOAD, " Artifact Name: " + artifactName - + " Artifact version: " + artifactVersion + " Artifact payload: " + encodedPayload); - } - - MdcOverride override = new MdcOverride(); - override.addAttribute(MdcContext.MDC_START_TIME, ZonedDateTime.now().format(formatter)); - - String resourceUrl = config.getBabelBaseUrl() + config.getBabelGenerateArtifactsUrl(); - WebResource webResource = client.resource(resourceUrl); - ClientResponse response = webResource.type("application/json") - .header(AaiRestClient.HEADER_TRANS_ID, transactionId) - .header(AaiRestClient.HEADER_FROM_APP_ID, AaiRestClient.ML_APP_NAME) - .post(ClientResponse.class, obj.toString()); - String sanitizedJson = JsonSanitizer.sanitize(response.getEntity(String.class)); - - if (logger.isDebugEnabled()) { - logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, - "Babel response " + response.getStatus() + " " + sanitizedJson); - } - - metricsLogger.info(ModelLoaderMsgs.BABEL_REST_REQUEST, new LogFields() // - .setField(LogLine.DefinedFields.TARGET_ENTITY, "Babel") - .setField(LogLine.DefinedFields.STATUS_CODE, - Response.Status.fromStatusCode(response.getStatus()).getFamily() - .equals(Response.Status.Family.SUCCESSFUL) ? "COMPLETE" : "ERROR") - .setField(LogLine.DefinedFields.RESPONSE_CODE, response.getStatus()) - .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, response.getStatusInfo().toString()), // - override, response.toString()); - - if (response.getStatus() != Response.Status.OK.getStatusCode()) { - throw new BabelServiceClientException(sanitizedJson); - } - - return new Gson().fromJson(sanitizedJson, new TypeToken>() {}.getType()); - } -} diff --git a/src/main/java/org/onap/aai/modelloader/service/HttpsBabelServiceClientFactory.java b/src/main/java/org/onap/aai/modelloader/service/HttpsBabelServiceClientFactory.java deleted file mode 100644 index 2414991..0000000 --- a/src/main/java/org/onap/aai/modelloader/service/HttpsBabelServiceClientFactory.java +++ /dev/null @@ -1,56 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017-2018 European Software Marketing Ltd. - * ================================================================================ - * 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.aai.modelloader.service; - -import java.io.IOException; -import java.security.KeyManagementException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.UnrecoverableKeyException; -import java.security.cert.CertificateException; -import org.onap.aai.modelloader.config.ModelLoaderConfig; -import org.onap.aai.modelloader.restclient.BabelServiceClient; -import org.onap.aai.modelloader.restclient.BabelServiceClientException; -import org.onap.aai.modelloader.restclient.HttpsBabelServiceClient; -import org.springframework.context.annotation.Primary; -import org.springframework.stereotype.Service; - -@Service -@Primary -public class HttpsBabelServiceClientFactory implements BabelServiceClientFactory { - - /* - * (non-Javadoc) - * - * @see org.onap.aai.modelloader.service.BabelServiceClientFactory#create(org.onap.aai.modelloader.config. - * ModelLoaderConfig) - */ - @Override - public BabelServiceClient create(ModelLoaderConfig config) throws BabelServiceClientException { - try { - return new HttpsBabelServiceClient(config); - } catch (UnrecoverableKeyException | KeyManagementException | NoSuchAlgorithmException | KeyStoreException - | CertificateException | IOException ex) { - throw new BabelServiceClientException(ex); - } - } - -} diff --git a/src/test/java/org/onap/aai/modelloader/BabelClientTestConfiguration.java b/src/test/java/org/onap/aai/modelloader/BabelClientTestConfiguration.java new file mode 100644 index 0000000..9df74fa --- /dev/null +++ b/src/test/java/org/onap/aai/modelloader/BabelClientTestConfiguration.java @@ -0,0 +1,57 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2024 Deutsche Telekom AG Intellectual Property. 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.aai.modelloader; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Properties; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Primary; + +@TestConfiguration +public class BabelClientTestConfiguration { + @Value("${CONFIG_HOME}") + private String configDir; + + @Value("${wiremock.server.port}") + private int wiremockPort; + + @Primary + @Bean(name = "testProperties") + public Properties configProperties() throws IOException { + // Load model loader system configuration + InputStream configInputStream = Files.newInputStream(Paths.get(configDir, "model-loader.properties")); + Properties configProperties = new Properties(); + configProperties.load(configInputStream); + + setOverrides(configProperties); + + return configProperties; + } + + private void setOverrides(Properties configProperties) { + configProperties.setProperty("ml.babel.BASE_URL", "http://localhost:" + wiremockPort); + } +} diff --git a/src/test/java/org/onap/aai/modelloader/notification/ArtifactDownloadManagerVnfcTest.java b/src/test/java/org/onap/aai/modelloader/notification/ArtifactDownloadManagerVnfcTest.java index aa2d299..a64c00c 100644 --- a/src/test/java/org/onap/aai/modelloader/notification/ArtifactDownloadManagerVnfcTest.java +++ b/src/test/java/org/onap/aai/modelloader/notification/ArtifactDownloadManagerVnfcTest.java @@ -35,11 +35,12 @@ import java.util.Properties; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.onap.aai.babel.service.data.BabelArtifact; -import org.onap.aai.modelloader.config.ModelLoaderConfig; +import org.onap.aai.modelloader.babel.BabelArtifactService; import org.onap.aai.modelloader.entity.Artifact; import org.onap.aai.modelloader.entity.ArtifactType; import org.onap.aai.modelloader.entity.catalog.VnfCatalogArtifact; @@ -70,6 +71,7 @@ public class ArtifactDownloadManagerVnfcTest { @Mock private BabelArtifactConverter mockBabelArtifactConverter; @Mock private BabelServiceClientFactory mockClientFactory; @Mock private VnfCatalogExtractor mockVnfCatalogExtractor; + @InjectMocks private BabelArtifactService babelArtifactService; @BeforeEach public void setup() throws Exception { @@ -79,7 +81,7 @@ public class ArtifactDownloadManagerVnfcTest { Properties configProperties = new Properties(); configProperties.load(this.getClass().getClassLoader().getResourceAsStream("model-loader.properties")); downloadManager = new ArtifactDownloadManager(mockDistributionClient, - new ModelLoaderConfig(configProperties, "."), mockClientFactory, mockBabelArtifactConverter, mockNotificationPublisher, mockVnfCatalogExtractor); + mockNotificationPublisher, mockVnfCatalogExtractor, babelArtifactService); } @Test @@ -89,7 +91,7 @@ public class ArtifactDownloadManagerVnfcTest { IArtifactInfo artifactInfo = data.getServiceArtifacts().get(0); setupValidDownloadCsarMocks(data, artifactInfo); - when(mockBabelClient.postArtifact(any(), any(), any(), any())).thenReturn(createBabelArtifacts()); + when(mockBabelClient.postArtifact(any(), any())).thenReturn(createBabelArtifacts()); when(mockVnfCatalogExtractor.extract(any(), any())).thenReturn(new ArrayList<>()); List modelArtifacts = new ArrayList<>(); @@ -107,7 +109,7 @@ public class ArtifactDownloadManagerVnfcTest { IArtifactInfo artifactInfo = data.getServiceArtifacts().get(0); setupValidDownloadCsarMocks(data, artifactInfo); - when(mockBabelClient.postArtifact(any(), any(), any(), any())).thenReturn(createBabelArtifactsNoVnfc()); + when(mockBabelClient.postArtifact(any(), any())).thenReturn(createBabelArtifactsNoVnfc()); when(mockVnfCatalogExtractor.extract(any(), any())).thenReturn(createXmlVnfcArtifacts()); List modelArtifacts = new ArrayList<>(); @@ -125,7 +127,7 @@ public class ArtifactDownloadManagerVnfcTest { IArtifactInfo artifactInfo = data.getServiceArtifacts().get(0); setupValidDownloadCsarMocks(data, artifactInfo); - when(mockBabelClient.postArtifact(any(), any(), any(), any())).thenReturn(createBabelArtifactsNoVnfc()); + when(mockBabelClient.postArtifact(any(), any())).thenReturn(createBabelArtifactsNoVnfc()); when(mockVnfCatalogExtractor.extract(any(), any())).thenReturn(new ArrayList<>()); List modelArtifacts = new ArrayList<>(); @@ -143,7 +145,7 @@ public class ArtifactDownloadManagerVnfcTest { IArtifactInfo artifactInfo = data.getServiceArtifacts().get(0); setupValidDownloadCsarMocks(data, artifactInfo); - when(mockBabelClient.postArtifact(any(), any(), any(), any())).thenReturn(createBabelArtifacts()); + when(mockBabelClient.postArtifact(any(), any())).thenReturn(createBabelArtifacts()); when(mockVnfCatalogExtractor.extract(any(), any())).thenReturn(createXmlVnfcArtifacts()); doNothing().when(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifactInfo); diff --git a/src/test/java/org/onap/aai/modelloader/notification/ModelArtifactHandlerTest.java b/src/test/java/org/onap/aai/modelloader/notification/ModelArtifactHandlerTest.java index b1269ee..4d7b53e 100644 --- a/src/test/java/org/onap/aai/modelloader/notification/ModelArtifactHandlerTest.java +++ b/src/test/java/org/onap/aai/modelloader/notification/ModelArtifactHandlerTest.java @@ -28,7 +28,6 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.deleteRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; -import static com.github.tomakehurst.wiremock.client.WireMock.ok; import java.util.List; @@ -48,7 +47,6 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock; import org.springframework.http.HttpStatus; -import org.springframework.web.client.RestTemplate; import org.w3c.dom.Node; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/src/test/java/org/onap/aai/modelloader/notification/TestArtifactDownloadManager.java b/src/test/java/org/onap/aai/modelloader/notification/TestArtifactDownloadManager.java index 48b9a66..27d0aa9 100644 --- a/src/test/java/org/onap/aai/modelloader/notification/TestArtifactDownloadManager.java +++ b/src/test/java/org/onap/aai/modelloader/notification/TestArtifactDownloadManager.java @@ -43,11 +43,12 @@ import org.hamcrest.collection.IsEmptyCollection; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.onap.aai.babel.service.data.BabelArtifact; -import org.onap.aai.modelloader.config.ModelLoaderConfig; +import org.onap.aai.modelloader.babel.BabelArtifactService; import org.onap.aai.modelloader.entity.Artifact; import org.onap.aai.modelloader.entity.model.BabelArtifactParsingException; import org.onap.aai.modelloader.extraction.VnfCatalogExtractor; @@ -73,6 +74,7 @@ public class TestArtifactDownloadManager { @Mock private NotificationPublisher mockNotificationPublisher; @Mock private BabelArtifactConverter mockBabelArtifactConverter; @Mock private BabelServiceClientFactory mockClientFactory; + @InjectMocks BabelArtifactService babelArtifactService; private VnfCatalogExtractor vnfCatalogExtractor; @BeforeEach @@ -84,7 +86,7 @@ public class TestArtifactDownloadManager { Properties configProperties = new Properties(); configProperties.load(this.getClass().getClassLoader().getResourceAsStream("model-loader.properties")); downloadManager = new ArtifactDownloadManager(mockDistributionClient, - new ModelLoaderConfig(configProperties, "."), mockClientFactory, mockBabelArtifactConverter, mockNotificationPublisher, vnfCatalogExtractor); + mockNotificationPublisher, vnfCatalogExtractor, babelArtifactService); } @AfterEach @@ -142,8 +144,6 @@ public class TestArtifactDownloadManager { Mockito.verify(mockDistributionClient).download(artifactInfo); Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifactInfo); Mockito.verify(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifactInfo); - - Mockito.verifyNoInteractions(mockBabelArtifactConverter); } @Test @@ -153,14 +153,14 @@ public class TestArtifactDownloadManager { when(mockDistributionClient.download(artifact)).thenReturn(createDistributionClientDownloadResult( DistributionActionResultEnum.SUCCESS, null, "This is not a valid Tosca CSAR File".getBytes())); doNothing().when(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifact); - when(mockBabelClient.postArtifact(any(), any(), any(), any())).thenThrow(new BabelServiceClientException("")); + when(mockBabelClient.postArtifact(any(), any())).thenThrow(new BabelServiceClientException("")); doNothing().when(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifact); assertThat(downloadManager.downloadArtifacts(data, data.getServiceArtifacts(), null, null), is(false)); Mockito.verify(mockDistributionClient).download(artifact); Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifact); - Mockito.verify(mockBabelClient).postArtifact(any(), any(), any(), any()); + Mockito.verify(mockBabelClient).postArtifact(any(), any()); Mockito.verify(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifact); Mockito.verifyNoInteractions(mockBabelArtifactConverter); @@ -204,7 +204,7 @@ public class TestArtifactDownloadManager { Mockito.verify(mockDistributionClient).download(artifactInfo); Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, artifactInfo); - Mockito.verify(mockBabelClient).postArtifact(any(), any(), any(), any()); + Mockito.verify(mockBabelClient).postArtifact(any(), any()); Mockito.verify(mockBabelArtifactConverter).convertToModel(any()); Mockito.verify(mockBabelArtifactConverter).convertToCatalog(any()); } @@ -214,7 +214,7 @@ public class TestArtifactDownloadManager { when(mockDistributionClient.download(artifactInfo)) .thenReturn(createDistributionClientDownloadResult(DistributionActionResultEnum.SUCCESS, null, artifactTestUtils.loadResource("compressedArtifacts/service-VscpaasTest-csar.csar"))); - when(mockBabelClient.postArtifact(any(), any(), any(), any())).thenReturn(createBabelArtifacts()); + when(mockBabelClient.postArtifact(any(), any())).thenReturn(createBabelArtifacts()); } private List createBabelArtifacts() { @@ -275,7 +275,7 @@ public class TestArtifactDownloadManager { Mockito.verify(mockDistributionClient).download(serviceArtifact); Mockito.verify(mockNotificationPublisher).publishDownloadSuccess(mockDistributionClient, data, serviceArtifact); - Mockito.verify(mockBabelClient).postArtifact(any(), any(), any(), any()); + Mockito.verify(mockBabelClient).postArtifact(any(), any()); Mockito.verify(mockBabelArtifactConverter).convertToModel(any()); Mockito.verify(mockBabelArtifactConverter).convertToCatalog(any()); @@ -298,7 +298,7 @@ public class TestArtifactDownloadManager { when(mockBabelArtifactConverter.convertToModel(anyList())) .thenThrow(BabelArtifactParsingException.class); doNothing().when(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifactInfo); - when(mockBabelClient.postArtifact(any(), any(), any(), any())).thenReturn(createBabelArtifacts()); + when(mockBabelClient.postArtifact(any(), any())).thenReturn(createBabelArtifacts()); List modelArtifacts = new ArrayList<>(); List catalogFiles = new ArrayList<>(); @@ -309,7 +309,7 @@ public class TestArtifactDownloadManager { Mockito.verify(mockDistributionClient).download(artifactInfo); Mockito.verify(mockNotificationPublisher).publishDeployFailure(mockDistributionClient, data, artifactInfo); - Mockito.verify(mockBabelClient).postArtifact(any(), any(), any(), any()); + Mockito.verify(mockBabelClient).postArtifact(any(), any()); Mockito.verify(mockBabelArtifactConverter).convertToModel(any()); } diff --git a/src/test/java/org/onap/aai/modelloader/restclient/MockBabelServiceClient.java b/src/test/java/org/onap/aai/modelloader/restclient/MockBabelServiceClient.java index 604aca7..783ad2e 100644 --- a/src/test/java/org/onap/aai/modelloader/restclient/MockBabelServiceClient.java +++ b/src/test/java/org/onap/aai/modelloader/restclient/MockBabelServiceClient.java @@ -23,6 +23,7 @@ package org.onap.aai.modelloader.restclient; import java.util.Collections; import java.util.List; import org.onap.aai.babel.service.data.BabelArtifact; +import org.onap.aai.babel.service.data.BabelRequest; import org.onap.aai.modelloader.config.ModelLoaderConfig; /** @@ -34,8 +35,8 @@ public class MockBabelServiceClient implements BabelServiceClient { public MockBabelServiceClient(ModelLoaderConfig config) throws BabelServiceClientException {} @Override - public List postArtifact(byte[] artifactPayload, String artifactName, String artifactVersion, - String transactionId) throws BabelServiceClientException { + public List postArtifact(BabelRequest babelRequest, String transactionId) + throws BabelServiceClientException { return Collections.emptyList(); } } diff --git a/src/test/java/org/onap/aai/modelloader/restclient/TestBabelServiceClient.java b/src/test/java/org/onap/aai/modelloader/restclient/TestBabelServiceClient.java index 169943c..d82bff0 100644 --- a/src/test/java/org/onap/aai/modelloader/restclient/TestBabelServiceClient.java +++ b/src/test/java/org/onap/aai/modelloader/restclient/TestBabelServiceClient.java @@ -28,34 +28,40 @@ import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Paths; +import java.util.Base64; import java.util.List; -import java.util.Properties; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.onap.aai.babel.service.data.BabelArtifact; -import org.onap.aai.modelloader.config.ModelLoaderConfig; -import org.onap.aai.modelloader.service.HttpsBabelServiceClientFactory; +import org.onap.aai.babel.service.data.BabelRequest; +import org.onap.aai.modelloader.BabelClientTestConfiguration; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock; +import org.springframework.context.annotation.Import; +import org.springframework.test.annotation.DirtiesContext; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.tomakehurst.wiremock.client.WireMock; -import com.github.tomakehurst.wiremock.matching.EqualToPattern; /** * Local testing of the Babel service client. * */ @SpringBootTest +@DirtiesContext @AutoConfigureWireMock(port = 0) +@Import(BabelClientTestConfiguration.class) public class TestBabelServiceClient { @Value("${wiremock.server.port}") private int wiremockPort; + @Autowired BabelServiceClient client; + @BeforeAll public static void setup() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); @@ -64,7 +70,7 @@ public class TestBabelServiceClient { new BabelArtifact("art2", null, ""), new BabelArtifact("art3", null, "")); WireMock.stubFor( - WireMock.post(WireMock.urlEqualTo("/generate")) + WireMock.post(WireMock.urlEqualTo("/services/babel-service/v1/app/generateArtifacts")) .withHeader("X-TransactionId", WireMock.equalTo("Test-Transaction-ID-BabelClient")) .withHeader("X-FromAppId", WireMock.equalTo("ModelLoader")) .withRequestBody(WireMock.matchingJsonPath("$.artifactName", WireMock.equalTo("service-Vscpass-Test"))) @@ -78,39 +84,13 @@ public class TestBabelServiceClient { @Test public void testRestClient() throws BabelServiceClientException, IOException, URISyntaxException { - String url = "http://localhost:" + wiremockPort; - Properties configProperties = new Properties(); - configProperties.put("ml.babel.KEYSTORE_PASSWORD", "OBF:1vn21ugu1saj1v9i1v941sar1ugw1vo0"); - configProperties.put("ml.babel.KEYSTORE_FILE", "src/test/resources/auth/aai-client-dummy.p12"); - configProperties.put("ml.babel.TRUSTSTORE_PASSWORD", "OBF:1vn21ugu1saj1v9i1v941sar1ugw1vo0"); - // In a real deployment this would be a different file (to the client keystore) - configProperties.put("ml.babel.TRUSTSTORE_FILE", "src/test/resources/auth/aai-client-dummy.p12"); - configProperties.put("ml.babel.BASE_URL", url); - configProperties.put("ml.babel.GENERATE_ARTIFACTS_URL", "/generate"); - configProperties.put("ml.aai.RESTCLIENT_CONNECT_TIMEOUT", "12000"); - configProperties.put("ml.aai.RESTCLIENT_READ_TIMEOUT", "12000"); - BabelServiceClient client = - new HttpsBabelServiceClientFactory().create(new ModelLoaderConfig(configProperties, ".")); - List result = - client.postArtifact(readBytesFromFile("compressedArtifacts/service-VscpaasTest-csar.csar"), - "service-Vscpass-Test", "1.0", "Test-Transaction-ID-BabelClient"); - assertThat(result.size(), is(equalTo(3))); - } + BabelRequest babelRequest = new BabelRequest(); + babelRequest.setArtifactName("service-Vscpass-Test"); + babelRequest.setCsar(Base64.getEncoder().encodeToString(readBytesFromFile("compressedArtifacts/service-VscpaasTest-csar.csar"))); + babelRequest.setArtifactVersion("1.0"); - @Test - public void testRestClientHttp() throws BabelServiceClientException, IOException, URISyntaxException { - String url = "http://localhost:" + wiremockPort; - Properties configProperties = new Properties(); - configProperties.put("ml.babel.USE_HTTPS", "false"); - configProperties.put("ml.babel.BASE_URL", url); - configProperties.put("ml.babel.GENERATE_ARTIFACTS_URL", "/generate"); - configProperties.put("ml.aai.RESTCLIENT_CONNECT_TIMEOUT", "3000"); - configProperties.put("ml.aai.RESTCLIENT_READ_TIMEOUT", "3000"); - BabelServiceClient client = - new HttpsBabelServiceClientFactory().create(new ModelLoaderConfig(configProperties, ".")); List result = - client.postArtifact(readBytesFromFile("compressedArtifacts/service-VscpaasTest-csar.csar"), - "service-Vscpass-Test", "1.0", "Test-Transaction-ID-BabelClient"); + client.postArtifact(babelRequest, "Test-Transaction-ID-BabelClient"); assertThat(result.size(), is(equalTo(3))); } diff --git a/src/test/java/org/onap/aai/modelloader/service/TestModelController.java b/src/test/java/org/onap/aai/modelloader/service/TestModelController.java index 9d7d5ea..970aa7a 100644 --- a/src/test/java/org/onap/aai/modelloader/service/TestModelController.java +++ b/src/test/java/org/onap/aai/modelloader/service/TestModelController.java @@ -33,7 +33,9 @@ import javax.ws.rs.core.Response; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; import org.mockito.Mock; +import org.onap.aai.modelloader.babel.BabelArtifactService; import org.onap.aai.modelloader.config.ModelLoaderConfig; import org.onap.aai.modelloader.extraction.VnfCatalogExtractor; import org.onap.aai.modelloader.notification.ArtifactDownloadManager; @@ -64,14 +66,15 @@ public class TestModelController { @Mock BabelServiceClientFactory clientFactory; @Mock BabelServiceClient babelServiceClient; + @InjectMocks BabelArtifactService babelArtifactService; private ModelController modelController; @BeforeEach public void init() throws BabelServiceClientException { when(clientFactory.create(any())).thenReturn(babelServiceClient); - when(babelServiceClient.postArtifact(any(), any(), any(), any())).thenReturn(Collections.emptyList()); - ArtifactDownloadManager artifactDownloadManager = new ArtifactDownloadManager(iDistributionClient, modelLoaderConfig, clientFactory, babelArtifactConverter, notificationPublisher, vnfCatalogExtractor); + when(babelServiceClient.postArtifact(any(), any())).thenReturn(Collections.emptyList()); + ArtifactDownloadManager artifactDownloadManager = new ArtifactDownloadManager(iDistributionClient, notificationPublisher, vnfCatalogExtractor, babelArtifactService); this.modelController = new ModelController(iDistributionClient, modelLoaderConfig, artifactDeploymentManager, artifactDownloadManager); } -- 2.16.6