Validates the Resource Model selected during the Import VSP.
This model must be aligned with one of the models that the
imported VSP relates to.
Fix VSP package retrieval to get the exact version from the
VSP chosen during the Import VSP process.
Introduces a client in the Catalog to retrieve from the
Onboarding backend a VSP information using its Id and
version Id.
Change-Id: Ic8fb52b6daadc0e7203c81a9c15c3e46d5b9fffb
Issue-ID: SDC-3675
Signed-off-by: andre.schmid <andre.schmid@est.tech>
heatEnvArtifactHeader: ""
heatEnvArtifactFooter: ""
-onboarding:
- protocol: http
- host: <%= @host_ip %>
- port: <%= @catalog_port %>
- downloadCsarUri: "/onboarding-api/v1.0/vendor-software-products/packages"
- healthCheckUri: "/onboarding-api/v1.0/healthcheck"
-
# #GSS IDNS
switchoverDetector:
gBeFqdn:
protocol: http
host: localhost
port: 8080
- downloadCsarUri: "/onboarding-api/v1.0/vendor-software-products/packages"
+ getVspPackageUri: "/onboarding-api/v1.0/vendor-software-products/packages/%s?versionId=%s" # /onboarding-api/v1.0/vendor-software-products/packages/:vspId?versionId=:vspVersionId
+ getLatestVspPackageUri: "/onboarding-api/v1.0/vendor-software-products/packages/%s" # /onboarding-api/v1.0/vendor-software-products/packages/:vspId
+ getVspUri: "/onboarding-api/v1.0/vendor-software-products/%s/versions/%s" # /onboarding-api/v1.0/vendor-software-products/:vspId/versions/:vspVersionId
healthCheckUri: "/onboarding-api/v1.0/healthcheck"
switchoverDetector:
package org.openecomp.sdc.asdctool.configuration;
-import org.junit.Test;
-public class ConfigurationUploaderTest {
+import static org.junit.jupiter.api.Assertions.assertEquals;
- private ConfigurationUploader createTestSubject() {
- return new ConfigurationUploader();
- }
+import org.junit.jupiter.api.Test;
+
+class ConfigurationUploaderTest {
@Test
- public void testUploadConfigurationFiles() throws Exception {
- String appConfigDir = "src/main/resources/config/";
+ void testUploadConfigurationFiles() {
+ final var appConfigDir = "src/main/resources/config/";
- // default test
+ //when
ConfigurationUploader.uploadConfigurationFiles(appConfigDir);
+
+ //then
+ assertEquals(appConfigDir, System.getProperty("config.home"));
+ assertEquals(appConfigDir + "Artifact-Generator.properties", System.getProperty("artifactgenerator.config"));
}
}
messageId: "SVC4154"
}
+ #-----------SVC4155---------------------------
+ # %1 - "VSP id"
+ # %2 - "VSP version id"
+ VSP_FIND_ERROR: {
+ code: 500,
+ message: "An error has occurred while retrieving the Vendor Software Product of id '%1', version id '%2'",
+ messageId: "SVC4155"
+ }
+
+ #-----------SVC4156---------------------------
+ # %1 - "VSP id"
+ # %2 - "VSP version id"
+ VSP_NOT_FOUND: {
+ code: 404,
+ message: "Could not find Vendor Software Product of id '%1', version id '%2'",
+ messageId: "SVC4156"
+ }
+
+ #-----------SVC4157---------------------------
+ # %1 - "The model name"
+ # %2 - "List of allowed models"
+ VSP_MODEL_NOT_ALLOWED: {
+ code: 400,
+ message: "The Model '%1' is not allowed for the imported Vendor Software Product. Allowed Models: '%2'",
+ messageId: "SVC4157"
+ }
\ No newline at end of file
protocol: http
port: <%= node['ONBOARDING_BE'][:http_port] %>
<% end -%>
- downloadCsarUri: "/onboarding-api/v1.0/vendor-software-products/packages"
+ getVspPackageUri: "/onboarding-api/v1.0/vendor-software-products/packages/%s?versionId=%s" # /onboarding-api/v1.0/vendor-software-products/packages/:vspId?versionId=:vspVersionId
+ getLatestVspPackageUri: "/onboarding-api/v1.0/vendor-software-products/packages/%s" # /onboarding-api/v1.0/vendor-software-products/packages/:vspId
+ getVspUri: "/onboarding-api/v1.0/vendor-software-products/%s/versions/%s" # /onboarding-api/v1.0/vendor-software-products/:vspId/versions/:vspVersionId
healthCheckUri: "/onboarding-api/v1.0/healthcheck"
# #GSS IDNS
import fj.data.Either;
import java.util.Map;
+import java.util.Optional;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.components.impl.BaseBusinessLogic;
import org.openecomp.sdc.be.components.impl.CsarValidationUtils;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.VendorSoftwareProduct;
import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
import org.openecomp.sdc.be.model.operations.StorageException;
import org.openecomp.sdc.be.model.operations.impl.CsarOperation;
import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
@Autowired
public CsarBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
- IGroupTypeOperation groupTypeOperation, GroupBusinessLogic groupBusinessLogic, InterfaceOperation interfaceOperation,
+ IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
InterfaceLifecycleOperation interfaceLifecycleTypeOperation, YamlTemplateParsingHandler yamlHandler,
ArtifactsOperations artifactToscaOperation) {
super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
if (status == StorageOperationStatus.ENTITY_ALREADY_EXISTS) {
log.debug("Failed to create resource {}, csarUUID {} already exist for a different VF ", resource.getSystemName(), csarUUID);
} else if (status != StorageOperationStatus.OK) {
- log.debug("Failed to validate uniqueness of CsarUUID {} for resource", csarUUID, resource.getSystemName());
+ log.debug("Failed to validate uniqueness of CsarUUID '{}' for resource '{}'", csarUUID, resource.getSystemName());
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status));
}
}
public CsarInfo getCsarInfo(Resource resource, Resource oldResource, User user, Map<String, byte[]> payload, String csarUUID) {
- Map<String, byte[]> csar = getCsar(resource, user, payload, csarUUID);
+ Map<String, byte[]> csar = payload;
+ if (csar == null) {
+ final var vendorSoftwareProduct = getCsar(resource, user);
+ validateModel(resource, vendorSoftwareProduct);
+
+ csar = vendorSoftwareProduct.getFileMap();
+ }
ImmutablePair<String, String> toscaYamlCsarStatus = validateAndParseCsar(resource, user, csar, csarUUID).left()
.on(this::throwComponentException);
String checksum = CsarValidationUtils.getToscaYamlChecksum(csar, csarUUID, componentsUtils).left()
csarUUID, oldResource.getComponentMetadataDefinition().getMetadataDataDefinition().getImportedToscaChecksum(), checksum);
oldResource.getComponentMetadataDefinition().getMetadataDataDefinition().setImportedToscaChecksum(checksum);
}
- return new CsarInfo(user, csarUUID, csar, resource.getName(), toscaYamlCsarStatus.getKey(), toscaYamlCsarStatus.getValue(), true);
+ return new CsarInfo(user, csarUUID, resource.getCsarVersionId(), csar, resource.getName(), toscaYamlCsarStatus.getKey(),
+ toscaYamlCsarStatus.getValue(), true);
+ }
+
+ private void validateModel(final Resource resource, final VendorSoftwareProduct vendorSoftwareProduct) {
+ if (resource.getModel() == null) {
+ if (!vendorSoftwareProduct.getModelList().isEmpty()) {
+ var modelStringList = String.join(", ", vendorSoftwareProduct.getModelList());
+ throw new ByActionStatusComponentException(ActionStatus.VSP_MODEL_NOT_ALLOWED, "SDC AID", modelStringList);
+ }
+ return;
+ }
+ if (!vendorSoftwareProduct.getModelList().contains(resource.getModel())) {
+ var modelStringList =
+ vendorSoftwareProduct.getModelList().isEmpty() ? "SDC AID" : String.join(", ", vendorSoftwareProduct.getModelList());
+ throw new ByActionStatusComponentException(ActionStatus.VSP_MODEL_NOT_ALLOWED, resource.getModel(), modelStringList);
+ }
}
public CsarInfo getCsarInfo(Service service, Service oldResource, User user, Map<String, byte[]> payload, String csarUUID) {
throw new ByResponseFormatComponentException(responseFormat);
}
- private Either<ImmutablePair<String, String>, ResponseFormat> validateAndParseCsar(Component component, User user, Map<String, byte[]> payload,
+ private Either<ImmutablePair<String, String>, ResponseFormat> validateAndParseCsar(Component component, User user, Map<String, byte[]> csar,
String csarUUID) {
- Map<String, byte[]> csar = getCsar(component, user, payload, csarUUID);
Either<Boolean, ResponseFormat> validateCsarStatus = CsarValidationUtils.validateCsar(csar, csarUUID, componentsUtils);
if (validateCsarStatus.isRight()) {
ResponseFormat responseFormat = validateCsarStatus.right().value();
if (payload != null) {
return payload;
}
- Either<Map<String, byte[]>, StorageOperationStatus> csar = csarOperation.getCsar(csarUUID, user);
+ Either<Map<String, byte[]>, StorageOperationStatus> csar = csarOperation.findVspLatestPackage(csarUUID, user);
if (csar.isRight()) {
StorageOperationStatus value = csar.right().value();
log.debug("#getCsar - failed to fetch csar with ID {}, error: {}", csarUUID, value);
return csar.left().value();
}
+ private VendorSoftwareProduct getCsar(final Resource resource, final User user) {
+ final Optional<VendorSoftwareProduct> vendorSoftwareProductOpt;
+ try {
+ vendorSoftwareProductOpt = csarOperation.findVsp(resource.getCsarUUID(), resource.getCsarVersionId(), user);
+ } catch (final Exception exception) {
+ log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, CsarBusinessLogic.class.getName(), exception.getMessage());
+ auditGetCsarError(resource, user, resource.getCsarUUID(), StorageOperationStatus.GENERAL_ERROR);
+ throw new ByActionStatusComponentException(ActionStatus.VSP_FIND_ERROR, resource.getCsarUUID(), resource.getCsarVersionId());
+ }
+ if (vendorSoftwareProductOpt.isEmpty()) {
+ auditGetCsarError(resource, user, resource.getCsarUUID(), StorageOperationStatus.CSAR_NOT_FOUND);
+ throw new ByActionStatusComponentException(ActionStatus.VSP_NOT_FOUND, resource.getCsarUUID(), resource.getCsarVersionId());
+ }
+ return vendorSoftwareProductOpt.get();
+ }
+
+ private void auditGetCsarError(Component component, User user, String csarUUID, StorageOperationStatus storageOperationStatus) {
+ log.debug("#getCsar - failed to fetch csar with ID {}, error: {}", csarUUID, storageOperationStatus);
+ BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATING_RESOURCE_FROM_CSAR_FETCHING_CSAR_WITH_ID + csarUUID + FAILED);
+ var responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageOperationStatus), csarUUID);
+ if (component instanceof Resource) {
+ componentsUtils.auditResource(responseFormat, user, (Resource) component, AuditingActionEnum.CREATE_RESOURCE);
+ }
+ }
+
private void auditAndThrowException(Resource resource, User user, AuditingActionEnum auditingAction, ActionStatus status, String... params) {
ResponseFormat errorResponse = componentsUtils.getResponseFormat(status, params);
componentsUtils.auditResource(errorResponse, user, resource, auditingAction);
@Setter
private String csarUUID;
@Getter
+ private String csarVersionId;
+ @Getter
@Setter
private Map<String, byte[]> csar;
@Getter
private List<Map.Entry<String, byte[]>> globalSubstitutes;
- @SuppressWarnings("unchecked")
public CsarInfo(User modifier, String csarUUID, Map<String, byte[]> csar, String vfResourceName, String mainTemplateName,
String mainTemplateContent, boolean isUpdate) {
this.vfResourceName = vfResourceName;
this.csar = csar;
this.mainTemplateName = mainTemplateName;
this.mainTemplateContent = mainTemplateContent;
- this.mappedToscaMainTemplate = (Map<String, Object>) new Yaml().load(mainTemplateContent);
+ this.mappedToscaMainTemplate = new Yaml().load(mainTemplateContent);
this.createdNodesToscaResourceNames = new HashMap<>();
this.cvfcToCreateQueue = new PriorityQueue<>();
this.isUpdate = isUpdate;
return globalSubstitutesInCsar;
}
+ public CsarInfo(final User modifier, final String csarUUID, final String csarVersionId, final Map<String, byte[]> csarContent,
+ final String vfResourceName, final String mainTemplateName, final String mainTemplateContent, final boolean isUpdate) {
+ this(modifier, csarUUID, csarContent, vfResourceName, mainTemplateName, mainTemplateContent, isUpdate);
+ this.csarVersionId = csarVersionId;
+ }
+
@VisibleForTesting
CsarInfo(final NonManoConfiguration nonManoConfiguration) {
this.nonManoConfiguration = nonManoConfiguration;
/*
-
- * Copyright (c) 2018 Huawei Intellectual Property.
-
- * Modifications Copyright (c) 2019 Samsung
-
- * 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
-
+ * -
+ * ============LICENSE_START=======================================================
+ * Copyright (c) 2018 Huawei Intellectual Property.
+ * Modifications Copyright (c) 2019 Samsung.
+ * Modifications Copyright (c) 2021 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
-
+ * 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.
-
+ * 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.openecomp.sdc.be.components.csar;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
import fj.data.Either;
-import org.junit.Before;
-import org.junit.Test;
+import java.io.IOException;
+import java.net.URISyntaxException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.openecomp.sdc.be.components.impl.BaseBusinessLogicMock;
+import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.VendorSoftwareProduct;
import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.CsarOperation;
import org.openecomp.sdc.common.zip.exception.ZipException;
import org.openecomp.sdc.exception.ResponseFormat;
-import java.io.IOException;
-import java.net.URISyntaxException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.Map;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.Mockito.when;
+class CsarBusinessLogicTest extends BaseBusinessLogicMock {
-public class CsarBusinessLogicTest extends BaseBusinessLogicMock {
+ private final CsarOperation csarOperation = Mockito.mock(CsarOperation.class);
+ private final ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
+ private final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class);
+ private final User user = Mockito.mock(User.class);
+ private final YamlTemplateParsingHandler yamlHandler = Mockito.mock(YamlTemplateParsingHandler.class);
- private CsarOperation csarOperation = Mockito.mock(CsarOperation.class);
- private ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
- private ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class);
- private User user = Mockito.mock(User.class);
- private YamlTemplateParsingHandler yamlHandler = Mockito.mock(YamlTemplateParsingHandler.class);
-
- private CsarBusinessLogic test = new CsarBusinessLogic(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
- groupBusinessLogic, interfaceOperation, interfaceLifecycleTypeOperation, yamlHandler, artifactToscaOperation);
+ private final CsarBusinessLogic csarBusinessLogic = new CsarBusinessLogic(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
+ interfaceOperation, interfaceLifecycleTypeOperation, yamlHandler, artifactToscaOperation);
private static final String CSAR_UUID = "csarUUID";
private static final String CSAR_ENTRY = "Definitions/tosca_mock_vf.yaml";
private static final String RESOURCE_NAME = "resourceName";
private static final String PAYLOAD_NAME = "mock_vf.csar";
- @Before
- public void setUp() throws Exception {
- test.setCsarOperation(csarOperation);
- test.setToscaOperationFacade(toscaOperationFacade);
- test.setComponentsUtils(componentsUtils);
+ @BeforeEach
+ void setUp() throws Exception {
+ csarBusinessLogic.setCsarOperation(csarOperation);
+ csarBusinessLogic.setToscaOperationFacade(toscaOperationFacade);
+ csarBusinessLogic.setComponentsUtils(componentsUtils);
}
- @Test()
- public void testGetCsarInfo() {
+ @Test
+ void testGetCsarInfo() {
// given
Resource resource = new Resource();
resource.setName(RESOURCE_NAME);
+ resource.setCsarUUID(CSAR_UUID);
+ resource.setCsarVersionId("csarVersionId");
Map<String, byte[]> csar_data = new HashMap<>();
csar_data.put(CSAR_METADATA, CSAR_METADATA_CONTENT.getBytes());
csar_data.put(CSAR_ENTRY, CSAR_ENTRY_CONTENT.getBytes());
- when(csarOperation.getCsar(anyString(), any(User.class))).thenReturn(Either.left(csar_data));
+ final var vendorSoftwareProduct = new VendorSoftwareProduct();
+ vendorSoftwareProduct.setFileMap(csar_data);
+ vendorSoftwareProduct.setModelList(Collections.emptyList());
+ when(csarOperation.findVsp(eq(resource.getCsarUUID()), eq(resource.getCsarVersionId()), any(User.class)))
+ .thenReturn(Optional.of(vendorSoftwareProduct));
// when
- CsarInfo csarInfo = test.getCsarInfo(resource, null, user, null, CSAR_UUID);
+ final CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(resource, null, user, null, CSAR_UUID);
// then
assertNotNull(csarInfo);
- assertEquals(CSAR_UUID, csarInfo.getCsarUUID());
+ assertEquals(resource.getCsarUUID(), csarInfo.getCsarUUID());
+ assertEquals(resource.getCsarVersionId(), csarInfo.getCsarVersionId());
assertEquals(CSAR_ENTRY, csarInfo.getMainTemplateName());
assertEquals(RESOURCE_NAME, csarInfo.getVfResourceName());
assertTrue(csarInfo.getCsar().keySet().containsAll(Arrays.asList(CSAR_ENTRY, CSAR_METADATA)));
}
- @Test()
- public void testGetCsarInfoWithPayload() throws IOException, URISyntaxException, ZipException {
+ @Test
+ void testGetCsarInfo_vspWithModelAndResourceWithInvalidModel() {
+ final var resource = new Resource();
+ resource.setCsarUUID(CSAR_UUID);
+ final String csarVersionId = "csarVersionId";
+ resource.setCsarVersionId(csarVersionId);
+ resource.setModel("model1");
+ var vendorSoftwareProduct = new VendorSoftwareProduct();
+ final List<String> modelList = List.of("model2", "model3");
+ vendorSoftwareProduct.setModelList(modelList);
+
+ when(csarOperation.findVsp(resource.getCsarUUID(), resource.getCsarVersionId(), user)).thenReturn(Optional.of(vendorSoftwareProduct));
+
+ final ByActionStatusComponentException actualException = assertThrows(ByActionStatusComponentException.class,
+ () -> csarBusinessLogic.getCsarInfo(resource, null, user, null, CSAR_UUID));
+ assertEquals(ActionStatus.VSP_MODEL_NOT_ALLOWED, actualException.getActionStatus());
+ assertEquals(2, actualException.getParams().length);
+ assertEquals(resource.getModel(), actualException.getParams()[0]);
+ assertEquals(String.join(", ", modelList), actualException.getParams()[1]);
+ }
+
+
+ @Test
+ void testGetCsarInfo_vspWithNoModelAndResourceWithInvalidModel() {
+ final var resource = new Resource();
+ resource.setCsarUUID(CSAR_UUID);
+ final String csarVersionId = "csarVersionId";
+ resource.setCsarVersionId(csarVersionId);
+ resource.setModel("model1");
+ var vendorSoftwareProduct = new VendorSoftwareProduct();
+ final List<String> modelList = new ArrayList<>();
+ vendorSoftwareProduct.setModelList(modelList);
+
+ when(csarOperation.findVsp(resource.getCsarUUID(), resource.getCsarVersionId(), user)).thenReturn(Optional.of(vendorSoftwareProduct));
+
+ final ByActionStatusComponentException actualException = assertThrows(ByActionStatusComponentException.class,
+ () -> csarBusinessLogic.getCsarInfo(resource, null, user, null, CSAR_UUID));
+ assertEquals(ActionStatus.VSP_MODEL_NOT_ALLOWED, actualException.getActionStatus());
+ assertEquals(2, actualException.getParams().length);
+ assertEquals(resource.getModel(), actualException.getParams()[0]);
+ assertEquals("SDC AID", actualException.getParams()[1]);
+ }
+
+ @Test
+ void testGetCsarInfo_vspWithModelAndResourceWithNoModel() {
+ final var resource = new Resource();
+ resource.setCsarUUID(CSAR_UUID);
+ final String csarVersionId = "csarVersionId";
+ resource.setCsarVersionId(csarVersionId);
+ resource.setModel(null);
+ var vendorSoftwareProduct = new VendorSoftwareProduct();
+ final List<String> modelList = List.of("model2", "model3");
+ vendorSoftwareProduct.setModelList(modelList);
+
+ when(csarOperation.findVsp(resource.getCsarUUID(), resource.getCsarVersionId(), user)).thenReturn(Optional.of(vendorSoftwareProduct));
+
+ final ByActionStatusComponentException actualException = assertThrows(ByActionStatusComponentException.class,
+ () -> csarBusinessLogic.getCsarInfo(resource, null, user, null, CSAR_UUID));
+ assertEquals(ActionStatus.VSP_MODEL_NOT_ALLOWED, actualException.getActionStatus());
+ assertEquals(2, actualException.getParams().length);
+ assertEquals("SDC AID", actualException.getParams()[0]);
+ assertEquals(String.join(", ", modelList), actualException.getParams()[1]);
+ }
+
+ @Test
+ void testGetCsarInfo_vspWithNoModelAndResourceWithNoModel() {
+ final var resource = new Resource();
+ resource.setCsarUUID(CSAR_UUID);
+ final String csarVersionId = "csarVersionId";
+ resource.setCsarVersionId(csarVersionId);
+ resource.setModel(null);
+ var vendorSoftwareProduct = new VendorSoftwareProduct();
+ final List<String> modelList = new ArrayList<>();
+ vendorSoftwareProduct.setModelList(modelList);
+ when(csarOperation.findVsp(resource.getCsarUUID(), resource.getCsarVersionId(), user)).thenThrow(new RuntimeException());
+
+ final ByActionStatusComponentException actualException = assertThrows(ByActionStatusComponentException.class,
+ () -> csarBusinessLogic.getCsarInfo(resource, null, user, null, CSAR_UUID));
+ assertEquals(ActionStatus.VSP_FIND_ERROR, actualException.getActionStatus());
+ assertEquals(2, actualException.getParams().length);
+ assertEquals(resource.getCsarUUID(), actualException.getParams()[0]);
+ assertEquals(resource.getCsarVersionId(), actualException.getParams()[1]);
+ }
+
+ @Test
+ void testGetCsarInfoWithPayload() throws IOException, URISyntaxException, ZipException {
// given
Resource resource = new Resource();
resource.setName(RESOURCE_NAME);
Map<String, byte[]> payload = loadPayload(PAYLOAD_NAME);
// when
- CsarInfo csarInfo = test.getCsarInfo(resource, null, user, payload, CSAR_UUID);
+ CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(resource, null, user, payload, CSAR_UUID);
// then
assertNotNull(csarInfo);
assertTrue(csarInfo.getCsar().keySet().containsAll(Arrays.asList(CSAR_ENTRY, CSAR_METADATA)));
}
- @Test(expected = ComponentException.class)
- public void testGetCsarInfoWithBadData(){
+ @Test
+ void testGetCsarInfoWithBadData(){
// given
Resource resource = new Resource();
resource.setName(RESOURCE_NAME);
Map<String, byte[]> csar_data = new HashMap<>();
- when(csarOperation.getCsar(anyString(), any(User.class))).thenReturn(Either.left(csar_data));
+ when(csarOperation.findVspLatestPackage(anyString(), any(User.class))).thenReturn(Either.left(csar_data));
- // when
- test.getCsarInfo(resource, null, user, null, CSAR_UUID);
+ // when/then
+ assertThrows(ComponentException.class, () -> csarBusinessLogic.getCsarInfo(resource, null, user, null, CSAR_UUID));
}
@Test
- public void testValidateCsarBeforeCreate() {
+ void testValidateCsarBeforeCreate() {
Resource resource = new Resource();
StorageOperationStatus status = StorageOperationStatus.OK;
when(toscaOperationFacade.validateCsarUuidUniqueness(CSAR_UUID)).thenReturn(status);
- test.validateCsarBeforeCreate(resource, AuditingActionEnum.ARTIFACT_DOWNLOAD, user, CSAR_UUID);
+ csarBusinessLogic.validateCsarBeforeCreate(resource, AuditingActionEnum.ARTIFACT_DOWNLOAD, user, CSAR_UUID);
}
- @Test(expected = ComponentException.class)
- public void testValidateCsarBeforeCreate_Exists() {
+ @Test
+ void testValidateCsarBeforeCreate_ResourceExists() {
Resource resource = new Resource();
ResponseFormat responseFormat = new ResponseFormat();
StorageOperationStatus status = StorageOperationStatus.ENTITY_ALREADY_EXISTS;
when(toscaOperationFacade.validateCsarUuidUniqueness(CSAR_UUID)).thenReturn(status);
when(componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, CSAR_UUID)).thenReturn(responseFormat);
- test.validateCsarBeforeCreate(resource, AuditingActionEnum.ARTIFACT_DOWNLOAD, user, "csarUUID");
+ assertThrows(ComponentException.class, () -> csarBusinessLogic
+ .validateCsarBeforeCreate(resource, AuditingActionEnum.ARTIFACT_DOWNLOAD, user, CSAR_UUID));
+ }
+
+ @Test
+ void testValidateCsarBeforeCreate_ServiceExists() {
+ final var service = new Service();
+ final var status = StorageOperationStatus.ENTITY_ALREADY_EXISTS;
+ when(toscaOperationFacade.validateCsarUuidUniqueness(CSAR_UUID)).thenReturn(status);
+ csarBusinessLogic.validateCsarBeforeCreate(service, CSAR_UUID);
+ verify(toscaOperationFacade).validateCsarUuidUniqueness(CSAR_UUID);
+ }
+
+ @Test
+ void testValidateCsarBeforeCreate_ServiceValidateError() {
+ final var service = new Service();
+ final var status = StorageOperationStatus.GENERAL_ERROR;
+ when(toscaOperationFacade.validateCsarUuidUniqueness(CSAR_UUID)).thenReturn(status);
+ when(componentsUtils.convertFromStorageResponse(status)).thenReturn(ActionStatus.GENERAL_ERROR);
+ assertThrows(ComponentException.class, () -> csarBusinessLogic.validateCsarBeforeCreate(service, CSAR_UUID));
+ verify(toscaOperationFacade).validateCsarUuidUniqueness(CSAR_UUID);
}
- @Test(expected = ComponentException.class)
- public void testValidateCsarBeforeCreate_Fail() {
+ @Test
+ void testValidateCsarBeforeCreate_Fail() {
Resource resource = new Resource();
String csarUUID = "csarUUID";
when(toscaOperationFacade.validateCsarUuidUniqueness(csarUUID)).thenReturn(StorageOperationStatus.EXEUCTION_FAILED);
when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.EXEUCTION_FAILED)).thenReturn(ActionStatus.GENERAL_ERROR);
- test.validateCsarBeforeCreate(resource, AuditingActionEnum.ARTIFACT_DOWNLOAD, user, "csarUUID");
+ assertThrows(ComponentException.class, () -> csarBusinessLogic
+ .validateCsarBeforeCreate(resource, AuditingActionEnum.ARTIFACT_DOWNLOAD, user, "csarUUID"));
}
- public Map<String, byte[]> loadPayload(String payloadName) throws IOException, URISyntaxException, ZipException {
-
- Path path = Paths.get(getClass().getResource("/" + payloadName).toURI());
+ private Map<String, byte[]> loadPayload(String payloadName) throws IOException, URISyntaxException, ZipException {
+ var path = Paths.get(getClass().getResource("/" + payloadName).toURI());
byte[] data = Files.readAllBytes(path);
return ZipUtils.readZip(data, false);
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.UploadComponentInstanceInfo;
import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.VendorSoftwareProduct;
import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
@Test
public void testUpdateUnhappyScenario() {
Resource resource = createResourceObjectCsar(true);
+ final var csarVersionId = "csarVersionId";
+ resource.setCsarVersionId(csarVersionId);
+
+ final var vendorSoftwareProduct = new VendorSoftwareProduct();
+ vendorSoftwareProduct.setFileMap(new HashMap<>());
+ vendorSoftwareProduct.setModelList(Collections.emptyList());
setCanWorkOnResource(resource);
validateUserRoles(Role.ADMIN, Role.DESIGNER);
when(toscaOperationFacade.validateToscaResourceNameExists("tosca.nodes.Root")).thenReturn(Either.left(true));
when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(Either.left(setCanWorkOnResource(resource)));
when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(Either.left(resource));
-
- when(csarOperation.getCsar("valid_vf.csar", user)).thenReturn(Either.left(new HashMap<>()));
-
+ when(csarOperation.findVsp("valid_vf.csar", csarVersionId, user)).thenReturn(Optional.of(vendorSoftwareProduct));
try {
Resource createdResource = bl.validateAndUpdateResourceFromCsar(resource, user, null, "", resource.getUniqueId());
protocol: http
host: localhost
port: 8080
- downloadCsarUri: "/onboarding-api/v1.0/vendor-software-products/packages"
healthCheckUri: "/onboarding-api/v1.0/healthcheck"
ecompPortal:
code: 500,
message: "An unexpected error occurred while updating the capability '%1'.",
messageId: "SVC4143"
+ }
+ #-----------SVC4154---------------------------
+ # %1 - "VSP id"
+ # %2 - "VSP version id"
+ VSP_FIND_ERROR: {
+ code: 500,
+ message: "An error has occurred while retrieving the Vendor Software Product of id '%1', version id '%2'",
+ messageId: "SVC4154"
+ }
+
+ #-----------SVC4155---------------------------
+ # %1 - "VSP id"
+ # %2 - "VSP version id"
+ VSP_NOT_FOUND: {
+ code: 404,
+ message: "Could not find Vendor Software Product of id '%1', version id '%2'",
+ messageId: "SVC4155"
+ }
+
+ #-----------SVC4156---------------------------
+ # %1 - "The model name"
+ # %2 - "List of allowed models"
+ VSP_MODEL_NOT_ALLOWED: {
+ code: 400,
+ message: "The Model '%1' is not allowed for the imported Vendor Software Product. Allowed Models: '%2'",
+ messageId: "SVC4156"
}
\ No newline at end of file
org.openecomp.sdc.be.components.validation,
org.openecomp.sdc.be.switchover.detector,
org.openecomp.sdc.be.tosca,
+ org.openecomp.sdc.be.client,
org.openecomp.sdc.be.model.operations.impl,
org.openecomp.sdc.be.model.jsonjanusgraph.operations,
org.openecomp.sdc.be.model.jsonjanusgraph.utils,
ANNOTATION_TYPE_ALREADY_EXIST,
// CSAR
MISSING_CSAR_UUID, CSAR_INVALID, CSAR_INVALID_FORMAT, CSAR_NOT_FOUND, YAML_NOT_FOUND_IN_CSAR, VSP_ALREADY_EXISTS, RESOURCE_LINKED_TO_DIFFERENT_VSP, RESOURCE_FROM_CSAR_NOT_FOUND, AAI_ARTIFACT_GENERATION_FAILED, ASSET_NOT_FOUND_DURING_CSAR_CREATION, ARTIFACT_PAYLOAD_NOT_FOUND_DURING_CSAR_CREATION, TOSCA_SCHEMA_FILES_NOT_FOUND, ARTIFACT_NAME_INVALID, ARTIFACT_PAYLOAD_EMPTY, ERROR_DURING_CSAR_CREATION, SERVICE_LINKED_TO_DIFFERENT_VSP,
+ VSP_NOT_FOUND, VSP_FIND_ERROR, VSP_MODEL_NOT_ALLOWED,
// Group
GROUP_HAS_CYCLIC_DEPENDENCY, GROUP_ALREADY_EXIST, GROUP_TYPE_IS_INVALID, GROUP_MISSING_GROUP_TYPE, GROUP_INVALID_COMPONENT_INSTANCE, GROUP_INVALID_TOSCA_NAME_OF_COMPONENT_INSTANCE, GROUP_IS_MISSING, GROUP_ARTIFACT_ALREADY_ASSOCIATED, GROUP_ARTIFACT_ALREADY_DISSOCIATED, GROUP_PROPERTY_NOT_FOUND, INVALID_VF_MODULE_NAME, INVALID_VF_MODULE_NAME_MODIFICATION, INVALID_VF_MODULE_TYPE,
// Group instance
--- /dev/null
+/*
+ * -
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2021 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.openecomp.sdc.be.client.onboarding.api;
+
+import fj.data.Either;
+import java.util.Map;
+import java.util.Optional;
+import org.openecomp.sdc.be.model.VendorSoftwareProduct;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+
+public interface OnboardingClient {
+
+ /**
+ * Finds the CSAR package of the latest version of a Vendor Software Product (VSP) from the onboarding repository.
+ *
+ * @param vspId the VSP id
+ * @param userId the logged user id
+ * @return a Map containing the CSAR files <path, bytes> (left), or a StorageOperationStatus if an error occurs (right)
+ */
+ Either<Map<String, byte[]>, StorageOperationStatus> findLatestPackage(String vspId, String userId);
+
+ Either<Map<String, byte[]>, StorageOperationStatus> findPackage(String vspId, String versionId, String userId);
+
+ /**
+ * Finds the Vendor Software Product (VSP) from the onboarding repository.
+ *
+ * @param id the VSP id
+ * @param versionId the VSP version
+ * @param userId the logged user id
+ * @return a VSP representation if found, empty otherwise.
+ */
+ Optional<VendorSoftwareProduct> findVendorSoftwareProduct(String id, String versionId, String userId);
+
+}
--- /dev/null
+/*
+ * -
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2021 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.openecomp.sdc.be.client.onboarding.exception;
+
+public class OnboardingClientException extends RuntimeException {
+
+ public OnboardingClientException(String message) {
+ super(message);
+ }
+
+ public OnboardingClientException(String message, Throwable cause) {
+ super(message, cause);
+ }
+}
--- /dev/null
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modification Copyright (C) 2021 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.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.client.onboarding.impl;
+
+import static javax.ws.rs.core.HttpHeaders.ACCEPT;
+import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import fj.data.Either;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Properties;
+import javax.ws.rs.core.MediaType;
+import org.apache.http.HttpStatus;
+import org.openecomp.sdc.be.client.onboarding.api.OnboardingClient;
+import org.openecomp.sdc.be.client.onboarding.exception.OnboardingClientException;
+import org.openecomp.sdc.be.config.Configuration.OnboardingConfig;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.model.VendorSoftwareProduct;
+import org.openecomp.sdc.be.model.dto.VendorSoftwareProductDto;
+import org.openecomp.sdc.be.model.mapper.VendorSoftwareProductMapper;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.http.client.api.HttpRequest;
+import org.openecomp.sdc.common.http.client.api.HttpResponse;
+import org.openecomp.sdc.common.log.wrappers.Logger;
+import org.openecomp.sdc.common.zip.ZipUtils;
+
+@org.springframework.stereotype.Component("onboarding-client")
+public class OnboardingClientImpl implements OnboardingClient {
+
+ private static final Logger LOGGER = Logger.getLogger(OnboardingClientImpl.class);
+ private final Properties downloadCsarHeaders;
+
+ public OnboardingClientImpl() {
+ downloadCsarHeaders = new Properties();
+ downloadCsarHeaders.put(ACCEPT, MediaType.APPLICATION_OCTET_STREAM);
+ }
+
+ @Override
+ public Either<Map<String, byte[]>, StorageOperationStatus> findLatestPackage(final String vspId, final String userId) {
+ final String url = buildGetLatestPackageUrl(vspId);
+ return handleGetPackage(userId, url);
+ }
+
+ @Override
+ public Either<Map<String, byte[]>, StorageOperationStatus> findPackage(final String vspId, final String versionId, final String userId) {
+ final String url = buildGetCsarUrl(vspId, versionId);
+ return handleGetPackage(userId, url);
+ }
+
+ private Either<Map<String, byte[]>, StorageOperationStatus> handleGetPackage(final String userId, final String url) {
+ final Properties headers = buildDefaultHeader(userId);
+ downloadCsarHeaders.forEach(headers::put);
+ LOGGER.debug("Get VSP package URL is '{}'. Used headers '{}'", url, headers);
+ try {
+ final HttpResponse<byte[]> httpResponse = HttpRequest.getAsByteArray(url, headers);
+ LOGGER.debug("'{}' HTTP response status was '{}'", url, httpResponse.getStatusCode());
+ switch (httpResponse.getStatusCode()) {
+ case HttpStatus.SC_OK:
+ byte[] data = httpResponse.getResponse();
+ if (data != null && data.length > 0) {
+ Map<String, byte[]> readZip = ZipUtils.readZip(data, false);
+ return Either.left(readZip);
+ }
+ LOGGER.debug("Empty payload received from '{}'", url);
+ return Either.right(StorageOperationStatus.NOT_FOUND);
+ case HttpStatus.SC_NOT_FOUND:
+ return Either.right(StorageOperationStatus.CSAR_NOT_FOUND);
+ default:
+ return Either.right(StorageOperationStatus.GENERAL_ERROR);
+ }
+ } catch (final Exception e) {
+ LOGGER.debug("Get VSP package request failed with exception", e);
+ return Either.right(StorageOperationStatus.GENERAL_ERROR);
+ }
+ }
+
+ @Override
+ public Optional<VendorSoftwareProduct> findVendorSoftwareProduct(final String id, final String versionId, final String userId) {
+ final Either<Map<String, byte[]>, StorageOperationStatus> csarEither = this.findPackage(id, versionId, userId);
+ if (csarEither.isRight()) {
+ final StorageOperationStatus operationStatus = csarEither.right().value();
+ if (operationStatus == StorageOperationStatus.CSAR_NOT_FOUND || operationStatus == StorageOperationStatus.NOT_FOUND) {
+ return Optional.empty();
+ }
+ var errorMsg = String.format("An error has occurred while retrieving the package with id '%s' and versionId '%s': '%s'",
+ id, versionId, operationStatus);
+ throw new OnboardingClientException(errorMsg);
+ }
+ final String url = buildGetVspUrl(id, versionId);
+ final Properties headers = buildDefaultHeader(userId);
+ headers.put(ACCEPT, APPLICATION_JSON);
+ LOGGER.debug("Find VSP built url '{}', with headers '{}'", url, headers);
+ final HttpResponse<String> httpResponse;
+ try {
+ httpResponse = HttpRequest.get(url, headers);
+ } catch (final Exception e) {
+ throw new OnboardingClientException("An error has occurred while retrieving the package", e);
+ }
+
+ if (httpResponse.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
+ return Optional.empty();
+ }
+
+ if (httpResponse.getStatusCode() != HttpStatus.SC_OK) {
+ var errorMsg = String.format("An error has occurred while retrieving the package. Http status was %s", httpResponse.getStatusCode());
+ throw new OnboardingClientException(errorMsg);
+ }
+
+ final String responseData = httpResponse.getResponse();
+ LOGGER.debug("Find vsp response data: '{}'", responseData);
+
+ final VendorSoftwareProductDto vendorSoftwareProductDto;
+ try {
+ vendorSoftwareProductDto = new ObjectMapper().readValue(responseData, VendorSoftwareProductDto.class);
+ } catch (final JsonProcessingException e) {
+ throw new OnboardingClientException("Could not parse retrieve package response to VendorSoftwareProductDto.class.", e);
+ }
+ final Map<String, byte[]> csarFileMap = csarEither.left().value();
+ final var vendorSoftwareProduct = VendorSoftwareProductMapper.mapFrom(vendorSoftwareProductDto);
+ vendorSoftwareProduct.setFileMap(csarFileMap);
+ return Optional.of(vendorSoftwareProduct);
+ }
+
+ private Properties buildDefaultHeader(final String userId) {
+ final var headers = new Properties();
+ if (userId != null) {
+ headers.put(Constants.USER_ID_HEADER, userId);
+ }
+ return headers;
+ }
+
+ private String buildGetCsarUrl(final String vspId, final String versionId) {
+ final var onboardingConfig = getOnboardingConfig();
+ final var uri = String.format(onboardingConfig.getGetVspPackageUri(), vspId, versionId);
+ return buildBaseOnboardingUrl() + uri;
+ }
+
+ private String buildGetLatestPackageUrl(final String vspId) {
+ final var onboardingConfig = getOnboardingConfig();
+ final var uri = String.format(onboardingConfig.getGetLatestVspPackageUri(), vspId);
+ return buildBaseOnboardingUrl() + uri;
+ }
+
+ private String buildBaseOnboardingUrl() {
+ final var onboardingConfig = getOnboardingConfig();
+ final String protocol = onboardingConfig.getProtocol();
+ final String host = onboardingConfig.getHost();
+ final Integer port = onboardingConfig.getPort();
+ return String.format("%s://%s:%s", protocol, host, port);
+ }
+
+ private String buildGetVspUrl(final String id, final String versionId) {
+ final var onboardingConfig = getOnboardingConfig();
+ final String protocol = onboardingConfig.getProtocol();
+ final String host = onboardingConfig.getHost();
+ final Integer port = onboardingConfig.getPort();
+ final var uri = String.format(onboardingConfig.getGetVspUri(), id, versionId);
+ return String.format("%s://%s:%s%s", protocol, host, port, uri);
+ }
+
+ private OnboardingConfig getOnboardingConfig() {
+ return ConfigurationManager.getConfigurationManager().getConfiguration().getOnboarding();
+ }
+
+}
// @formatter:off
"org.openecomp.sdc.be.model.operations.impl",
"org.openecomp.sdc.be.model.cache",
+ "org.openecomp.sdc.be.client",
"org.openecomp.sdc.be.model.jsonjanusgraph.utils",
"org.openecomp.sdc.be.model.jsonjanusgraph.operations",
"org.openecomp.sdc.be.model.jsonjanusgraph.config",
}
public Boolean isAbstract() {
- return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).isAbstract();
+ return getResourceMetadataDataDefinition().isAbstract();
}
public void setAbstract(Boolean isAbstract) {
- ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).setAbstract(isAbstract);
+ getResourceMetadataDataDefinition().setAbstract(isAbstract);
}
public String getCost() {
- return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).getCost();
+ return getResourceMetadataDataDefinition().getCost();
}
public void setCost(String cost) {
- ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).setCost(cost);
+ getResourceMetadataDataDefinition().setCost(cost);
}
public String getLicenseType() {
- return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).getLicenseType();
+ return getResourceMetadataDataDefinition().getLicenseType();
}
public void setLicenseType(String licenseType) {
- ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).setLicenseType(licenseType);
+ getResourceMetadataDataDefinition().setLicenseType(licenseType);
}
public String getToscaResourceName() {
- return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).getToscaResourceName();
+ return getResourceMetadataDataDefinition().getToscaResourceName();
}
public void setToscaResourceName(String toscaResourceName) {
- ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).setToscaResourceName(toscaResourceName);
+ getResourceMetadataDataDefinition().setToscaResourceName(toscaResourceName);
}
public ResourceTypeEnum getResourceType() {
- return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType();
+ return getResourceMetadataDataDefinition().getResourceType();
}
public void setResourceType(ResourceTypeEnum resourceType) {
- ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).setResourceType(resourceType);
+ getResourceMetadataDataDefinition().setResourceType(resourceType);
}
public String getVendorName() {
- return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).getVendorName();
+ return getResourceMetadataDataDefinition().getVendorName();
}
public void setVendorName(String vendorName) {
- ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).setVendorName(vendorName);
+ getResourceMetadataDataDefinition().setVendorName(vendorName);
}
public String getVendorRelease() {
- return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).getVendorRelease();
+ return getResourceMetadataDataDefinition().getVendorRelease();
}
public void setVendorRelease(String vendorRelease) {
- ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).setVendorRelease(vendorRelease);
+ getResourceMetadataDataDefinition().setVendorRelease(vendorRelease);
}
public String getResourceVendorModelNumber() {
- return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceVendorModelNumber();
+ return getResourceMetadataDataDefinition().getResourceVendorModelNumber();
}
public void setResourceVendorModelNumber(String resourceVendorModelNumber) {
- ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition())
+ getResourceMetadataDataDefinition()
.setResourceVendorModelNumber(resourceVendorModelNumber);
}
+ private ResourceMetadataDataDefinition getResourceMetadataDataDefinition() {
+ return (ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition();
+ }
+
+ public String getCsarVersionId() {
+ return getResourceMetadataDataDefinition().getCsarVersionId();
+ }
+
+ public void setCsarVersionId(String csarVersionId) {
+ getResourceMetadataDataDefinition().setCsarVersionId(csarVersionId);
+ }
+
@Override
public String fetchGenericTypeToscaNameFromConfig() {
return fetchToscaNameFromConfigBasedOnCategory().orElse(fetchToscaNameFromConfigBasedOnAssetType());
--- /dev/null
+/*
+ * -
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2021 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.openecomp.sdc.be.model;
+
+import java.util.List;
+import java.util.Map;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+@Data
+@NoArgsConstructor
+public class VendorSoftwareProduct {
+
+ private String name;
+ private String description;
+ private String category;
+ private String subCategory;
+ private String vendorName;
+ private String vendorId;
+ private List<String> modelList;
+ private String onboardingMethod;
+ private String id;
+ private String versionId;
+ private String onboardingOrigin;
+ private String networkPackageName;
+ private Map<String, byte[]> fileMap;
+
+}
--- /dev/null
+/*
+ * -
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2021 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.openecomp.sdc.be.model.dto;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import java.util.List;
+import lombok.Data;
+
+@Data
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class VendorSoftwareProductDto {
+
+ private String name;
+ private String description;
+ private String category;
+ private String subCategory;
+ private String vendorName;
+ private String vendorId;
+ private List<String> selectedModelList;
+ private String onboardingMethod;
+ private String id;
+ @JsonProperty("version")
+ private String versionId;
+ private String onboardingOrigin;
+ private String networkPackageName;
+
+}
--- /dev/null
+/*
+ * -
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2021 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.openecomp.sdc.be.model.mapper;
+
+import java.util.ArrayList;
+import java.util.Objects;
+import org.openecomp.sdc.be.model.VendorSoftwareProduct;
+import org.openecomp.sdc.be.model.dto.VendorSoftwareProductDto;
+
+public class VendorSoftwareProductMapper {
+
+ private VendorSoftwareProductMapper() {
+ }
+
+ public static VendorSoftwareProduct mapFrom(final VendorSoftwareProductDto vendorSoftwareProductDto) {
+ Objects.requireNonNull(vendorSoftwareProductDto);
+ final var vendorSoftwareProduct = new VendorSoftwareProduct();
+ vendorSoftwareProduct.setName(vendorSoftwareProductDto.getName());
+ vendorSoftwareProduct.setDescription(vendorSoftwareProductDto.getDescription());
+ vendorSoftwareProduct.setCategory(vendorSoftwareProductDto.getCategory());
+ vendorSoftwareProduct.setSubCategory(vendorSoftwareProductDto.getSubCategory());
+ vendorSoftwareProduct.setVendorName(vendorSoftwareProductDto.getVendorName());
+ vendorSoftwareProduct.setVendorId(vendorSoftwareProductDto.getVendorId());
+ vendorSoftwareProduct.setModelList(
+ vendorSoftwareProductDto.getSelectedModelList() == null ? new ArrayList<>() : vendorSoftwareProductDto.getSelectedModelList());
+ vendorSoftwareProduct.setOnboardingMethod(vendorSoftwareProductDto.getOnboardingMethod());
+ vendorSoftwareProduct.setId(vendorSoftwareProductDto.getId());
+ vendorSoftwareProduct.setVersionId(vendorSoftwareProductDto.getVersionId());
+ vendorSoftwareProduct.setOnboardingOrigin(vendorSoftwareProductDto.getOnboardingOrigin());
+ vendorSoftwareProduct.setNetworkPackageName(vendorSoftwareProductDto.getNetworkPackageName());
+ return vendorSoftwareProduct;
+ }
+
+
+}
*/
package org.openecomp.sdc.be.model.operations.impl;
-import com.google.gson.Gson;
-import com.google.gson.JsonArray;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonParser;
import fj.data.Either;
import java.util.Map;
-import javax.annotation.PostConstruct;
+import java.util.Optional;
+import org.apache.commons.collections4.MapUtils;
+import org.openecomp.sdc.be.client.onboarding.api.OnboardingClient;
import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.VendorSoftwareProduct;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.common.log.wrappers.Logger;
+import org.springframework.beans.factory.annotation.Autowired;
@org.springframework.stereotype.Component("csar-operation")
public class CsarOperation {
- private static final Logger log = Logger.getLogger(CsarOperation.class.getName());
- @javax.annotation.Resource
- private OnboardingClient onboardingClient;
+ private static final Logger LOGGER = Logger.getLogger(CsarOperation.class.getName());
- @PostConstruct
- public void init() {
+ private final OnboardingClient onboardingClient;
+
+ @Autowired
+ public CsarOperation(final OnboardingClient onboardingClient) {
+ this.onboardingClient = onboardingClient;
}
/**
- * get csar from remote repository
+ * Finds the CSAR package of the latest version of a Vendor Software Product (VSP) from the onboarding repository.
*
- * @param csarUuid
- * @return
+ * @param csarUuid the VSP id
+ * @param user the logged user
+ * @return a Map containing the CSAR files <path, bytes> (left), or a StorageOperationStatus if an error occurs (right)
*/
- public Either<Map<String, byte[]>, StorageOperationStatus> getCsar(String csarUuid, User user) {
- Either<Map<String, byte[]>, StorageOperationStatus> result = onboardingClient.getCsar(csarUuid, user.getUserId());
+ public Either<Map<String, byte[]>, StorageOperationStatus> findVspLatestPackage(String csarUuid, User user) {
+ final Either<Map<String, byte[]>, StorageOperationStatus> result = onboardingClient.findLatestPackage(csarUuid, user.getUserId());
if (result.isRight()) {
- log.debug("Cannot find csar {}. Staus returned is {}", csarUuid, result.right().value());
- } else {
- Map<String, byte[]> values = result.left().value();
- if (values != null) {
- log.debug("The returned files are {}", values.keySet());
- }
+ LOGGER.debug("Could not find VSP Package '{}'. Status '{}'", csarUuid, result.right().value());
+ return result;
}
- return result;
- }
-
- @SuppressWarnings("unchecked")
- public Either<String, StorageOperationStatus> getCsarLatestVersion(String csarUuid, User user) {
- Either<String, StorageOperationStatus> result = onboardingClient.getPackages(user.getUserId());
- if (result.isRight()) {
- log.debug("Cannot find version for package with Id {}. Status returned is {}", csarUuid, result.right().value());
- } else {
- String latestVersion = null;
- JsonElement root = new JsonParser().parse(result.left().value());
- JsonArray csarsInfo = root.getAsJsonObject().get("results").getAsJsonArray();
- for (JsonElement csarInfo : csarsInfo) {
- Map<String, String> csarInfoMap = new Gson().fromJson(csarInfo, Map.class);
- if (csarInfoMap.get("packageId").equals(csarUuid)) {
- String curVersion = csarInfoMap.get("version");
- if (latestVersion == null || isGreater(latestVersion, curVersion)) {
- latestVersion = curVersion;
- }
- }
- }
- if (latestVersion != null) {
- result = Either.left(latestVersion);
- } else {
- log.debug("The returned packages are {}. Failed to find latest version for package with Id {}. ", result.left().value(), csarUuid);
- result = Either.right(StorageOperationStatus.NOT_FOUND);
- }
+ if (MapUtils.isNotEmpty(result.left().value())) {
+ final Map<String, byte[]> values = result.left().value();
+ LOGGER.debug("The returned files are {}", values.keySet());
}
return result;
}
- private boolean isGreater(String latestVersion, String currentVersion) {
- return Double.parseDouble(latestVersion) < Double.parseDouble(currentVersion);
+ /**
+ * Finds the Vendor Software Product (VSP) from the onboarding repository.
+ *
+ * @param id the VSP id
+ * @param versionId the VSP version
+ * @param user the logged user
+ * @return a VSP representation if found, empty otherwise.
+ */
+ public Optional<VendorSoftwareProduct> findVsp(final String id, final String versionId, final User user) {
+ return onboardingClient.findVendorSoftwareProduct(id, versionId, user.getUserId());
}
- public OnboardingClient getOnboardingClient() {
- return onboardingClient;
- }
}
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T 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.openecomp.sdc.be.model.operations.impl;
-
-import fj.data.Either;
-import java.util.Map;
-import java.util.Properties;
-import lombok.NoArgsConstructor;
-import org.apache.http.HttpStatus;
-import org.openecomp.sdc.be.config.Configuration.OnboardingConfig;
-import org.openecomp.sdc.be.config.ConfigurationManager;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.http.client.api.HttpRequest;
-import org.openecomp.sdc.common.http.client.api.HttpResponse;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.common.zip.ZipUtils;
-
-@NoArgsConstructor
-@org.springframework.stereotype.Component("onboarding-client")
-public class OnboardingClient {
-
- private static final Logger log = Logger.getLogger(OnboardingClient.class.getName());
- private static Properties downloadCsarHeaders = new Properties();
-
- static {
- downloadCsarHeaders.put("Accept", "application/octet-stream");
- }
-
- public Either<Map<String, byte[]>, StorageOperationStatus> getCsar(String csarUuid, String userId) {
- String url = buildDownloadCsarUrl() + "/" + csarUuid;
- Properties headers = new Properties();
- if (downloadCsarHeaders != null) {
- downloadCsarHeaders.forEach(headers::put);
- }
- if (userId != null) {
- headers.put(Constants.USER_ID_HEADER, userId);
- }
- log.debug("Url for downloading csar is {}. Headers are {}", url, headers);
- try {
- HttpResponse<byte[]> httpResponse = HttpRequest.getAsByteArray(url, headers);
- log.debug("After fetching csar {}. Http return code is {}", csarUuid, httpResponse.getStatusCode());
- switch (httpResponse.getStatusCode()) {
- case HttpStatus.SC_OK:
- byte[] data = httpResponse.getResponse();
- if (data != null && data.length > 0) {
- Map<String, byte[]> readZip = ZipUtils.readZip(data, false);
- return Either.left(readZip);
- } else {
- log.debug("Data received from rest is null or empty");
- return Either.right(StorageOperationStatus.NOT_FOUND);
- }
- case HttpStatus.SC_NOT_FOUND:
- return Either.right(StorageOperationStatus.CSAR_NOT_FOUND);
- default:
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- } catch (Exception e) {
- log.debug("Request failed with exception", e);
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- }
-
- public Either<String, StorageOperationStatus> getPackages(String userId) {
- String url = buildDownloadCsarUrl();
- Properties headers = new Properties();
- headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
-
- if (userId != null) {
- headers.put(Constants.USER_ID_HEADER, userId);
- }
-
- log.debug("Url for downloading packages is {}. Headers are {}", url, headers);
-
- try {
- HttpResponse<String> httpResposne = HttpRequest.get(url, headers);
- log.debug("After fetching packages. Http return code is {}", httpResposne.getStatusCode());
-
- switch (httpResposne.getStatusCode()) {
- case HttpStatus.SC_OK:
- String data = httpResposne.getResponse();
- return Either.left(data);
-
- case HttpStatus.SC_NOT_FOUND:
- return Either.right(StorageOperationStatus.CSAR_NOT_FOUND);
-
- default:
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- } catch (Exception e) {
- log.debug("Request failed with exception", e);
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- }
-
- /**
- * Build the url for download CSAR
- * <p>
- * E.g., http://0.0.0.0:8181/onboarding-api/v1.0/vendor-software-products/packages/
- *
- * @return
- */
- public String buildDownloadCsarUrl() {
- OnboardingConfig onboardingConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getOnboarding();
- String protocol = onboardingConfig.getProtocol();
- String host = onboardingConfig.getHost();
- Integer port = onboardingConfig.getPort();
- String uri = onboardingConfig.getDownloadCsarUri();
- return protocol + "://" + host + ":" + port + uri;
- }
-}
@Configuration
@ComponentScan({"org.openecomp.sdc.be.dao.cassandra", "org.openecomp.sdc.be.model.cache",
+ "org.openecomp.sdc.be.client",
"org.openecomp.sdc.be.model.jsonjanusgraph.operations",
"org.openecomp.sdc.be.model.jsonjanusgraph.utils",
"org.openecomp.sdc.be.model.jsonjanusgraph.config",
--- /dev/null
+/*
+ * -
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2021 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.openecomp.sdc.be.model.mapper;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.util.ArrayList;
+import java.util.List;
+import org.junit.jupiter.api.Test;
+import org.openecomp.sdc.be.model.VendorSoftwareProduct;
+import org.openecomp.sdc.be.model.dto.VendorSoftwareProductDto;
+
+class VendorSoftwareProductMapperTest {
+
+ @Test
+ void mapFromSuccess() {
+ final var vendorSoftwareProductDto = new VendorSoftwareProductDto();
+ vendorSoftwareProductDto.setName("name");
+ vendorSoftwareProductDto.setDescription("description");
+ vendorSoftwareProductDto.setCategory("category");
+ vendorSoftwareProductDto.setSubCategory("subcategory");
+ vendorSoftwareProductDto.setVendorName("vendorName");
+ vendorSoftwareProductDto.setVendorId("vendorId");
+ vendorSoftwareProductDto.setSelectedModelList(List.of("model1", "model2"));
+ vendorSoftwareProductDto.setOnboardingMethod("onboardingMethod");
+ vendorSoftwareProductDto.setId("id");
+ vendorSoftwareProductDto.setVersionId("versionId");
+ vendorSoftwareProductDto.setOnboardingOrigin("onboardingOrigin");
+ vendorSoftwareProductDto.setNetworkPackageName("packageName");
+ final VendorSoftwareProduct vendorSoftwareProduct = VendorSoftwareProductMapper.mapFrom(vendorSoftwareProductDto);
+ assertVendorSoftwareProduct(vendorSoftwareProduct, vendorSoftwareProductDto);
+ }
+
+ @Test
+ void mapFromNullModelListShouldReturnEmptyModelList() {
+ final var vendorSoftwareProductDto = new VendorSoftwareProductDto();
+ vendorSoftwareProductDto.setSelectedModelList(null);
+ final VendorSoftwareProduct vendorSoftwareProduct = VendorSoftwareProductMapper.mapFrom(vendorSoftwareProductDto);
+ assertVendorSoftwareProduct(vendorSoftwareProduct, vendorSoftwareProductDto);
+ }
+
+ private void assertVendorSoftwareProduct(final VendorSoftwareProduct vendorSoftwareProduct,
+ final VendorSoftwareProductDto vendorSoftwareProductDto) {
+ assertEquals(vendorSoftwareProduct.getId(), vendorSoftwareProductDto.getId(), "id should be equals");
+ assertEquals(vendorSoftwareProduct.getName(), vendorSoftwareProductDto.getName(), "name should be equals");
+ assertEquals(vendorSoftwareProduct.getDescription(), vendorSoftwareProductDto.getDescription(), "description should be equals");
+ assertEquals(vendorSoftwareProduct.getCategory(), vendorSoftwareProductDto.getCategory(), "category should be equals");
+ assertEquals(vendorSoftwareProduct.getSubCategory(), vendorSoftwareProductDto.getSubCategory(), "subCategory should be equals");
+ assertEquals(vendorSoftwareProduct.getVendorName(), vendorSoftwareProductDto.getVendorName(), "vendorName should be equals");
+ assertEquals(vendorSoftwareProduct.getVendorId(), vendorSoftwareProductDto.getVendorId(), "vendorId should be equals");
+ assertEquals(vendorSoftwareProduct.getOnboardingMethod(), vendorSoftwareProductDto.getOnboardingMethod(), "onboardingMethod should be equals");
+ assertEquals(vendorSoftwareProduct.getOnboardingOrigin(), vendorSoftwareProductDto.getOnboardingOrigin(), "onboardingOrigin should be equals");
+ assertEquals(vendorSoftwareProduct.getVersionId(), vendorSoftwareProductDto.getVersionId(), "versionId should be equals");
+ assertEquals(vendorSoftwareProduct.getNetworkPackageName(), vendorSoftwareProductDto.getNetworkPackageName(), "networkPackageName should be equals");
+ if (vendorSoftwareProductDto.getSelectedModelList() == null) {
+ assertTrue(vendorSoftwareProduct.getModelList().isEmpty(), "modelList should be an empty list");
+ } else {
+ assertEquals(vendorSoftwareProduct.getModelList(), vendorSoftwareProductDto.getSelectedModelList(), "modelList should be equals");
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * -
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2021 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.openecomp.sdc.be.model.operations.impl;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.when;
+
+import fj.data.Either;
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.openecomp.sdc.be.client.onboarding.api.OnboardingClient;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.VendorSoftwareProduct;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+
+class CsarOperationTest {
+
+ @Mock
+ private OnboardingClient onboardingClient;
+
+ @InjectMocks
+ private CsarOperation csarOperation;
+
+
+ @BeforeEach
+ void setUp() {
+ MockitoAnnotations.openMocks(this);
+ }
+
+ @Test
+ void findVspLatestPackageSuccessTest() {
+ final var csarUuid = "csarUuid";
+ var user = new User("userId");
+ final Map<String, byte[]> csarFileMap = new HashMap<>();
+ csarFileMap.put("test", "test".getBytes(StandardCharsets.UTF_8));
+ when(onboardingClient.findLatestPackage(csarUuid, user.getUserId())).thenReturn(Either.left(csarFileMap));
+ final Either<Map<String, byte[]>, StorageOperationStatus> vspLatestPackage = csarOperation.findVspLatestPackage(csarUuid, user);
+ assertTrue(vspLatestPackage.isLeft());
+ final Map<String, byte[]> actualCsarFileMap = vspLatestPackage.left().value();
+ assertEquals(csarFileMap, actualCsarFileMap);
+ }
+
+ @Test
+ void findVspLatestPackage_csarNotFoundTest() {
+ //given
+ final var vspId = "vspId";
+ var user = new User("userId");
+ //when
+ when(onboardingClient.findLatestPackage(vspId, user.getUserId())).thenReturn(Either.right(StorageOperationStatus.CSAR_NOT_FOUND));
+ final Either<Map<String, byte[]>, StorageOperationStatus> vspLatestPackage = csarOperation.findVspLatestPackage(vspId, user);
+ //then
+ assertTrue(vspLatestPackage.isRight());
+ final StorageOperationStatus storageOperationStatus = vspLatestPackage.right().value();
+ assertEquals(StorageOperationStatus.CSAR_NOT_FOUND, storageOperationStatus);
+ }
+
+ @Test
+ void findVspSuccessTest() {
+ //given
+ final var vspId = "vspId";
+ final var vspVersionId = "vspVersionId";
+ var user = new User("userId");
+ var vendorSoftwareProduct = new VendorSoftwareProduct();
+ vendorSoftwareProduct.setId(vspId);
+ vendorSoftwareProduct.setVersionId(vspVersionId);
+ //when
+ when(onboardingClient.findVendorSoftwareProduct(vspId, vspVersionId, user.getUserId())).thenReturn(Optional.of(vendorSoftwareProduct));
+ final Optional<VendorSoftwareProduct> vspOptional = csarOperation.findVsp(vspId, vspVersionId, user);
+ //then
+ assertTrue(vspOptional.isPresent());
+ assertEquals(vendorSoftwareProduct, vspOptional.get());
+ }
+
+ @Test
+ void findVsp_vspNotFoundTest() {
+ //given
+ final var vspId = "vspId";
+ final var vspVersionId = "vspVersionId";
+ var user = new User("userId");
+ //when
+ when(onboardingClient.findVendorSoftwareProduct(vspId, vspVersionId, user.getUserId())).thenReturn(Optional.empty());
+ final Optional<VendorSoftwareProduct> vspOptional = csarOperation.findVsp(vspId, vspVersionId, user);
+ //then
+ assertTrue(vspOptional.isEmpty());
+ }
+}
\ No newline at end of file
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
-
+
<context:component-scan
base-package="org.openecomp.sdc.be.model.operations.impl,
org.openecomp.sdc.be.model.jsonjanusgraph.operations,
org.openecomp.sdc.be.dao.jsongraph,
org.openecomp.sdc.be.model.cache,
+ org.openecomp.sdc.be.client,
org.openecomp.sdc.be.dao.janusgraph,
org.openecomp.sdc.be.dao.cassandra,
org.openecomp.sdc.be.model.jsonjanusgraph.utils,
protocol: http
host: localhost
port: 8080
- downloadCsarUri: "/onboarding-api/v1.0/vendor-software-products/packages"
healthCheckUri: "/onboarding-api/v1.0/healthcheck"
switchoverDetector:
protocol: http
host: localhost
port: 8080
- downloadCsarUri: "/onboarding-api/v1.0/vendor-software-products/packages"
healthCheckUri: "/onboarding-api/v1.0/healthcheck"
private String protocol = "http";
private String host;
private Integer port;
- private String downloadCsarUri;
+ private String getLatestVspPackageUri;
+ private String getVspPackageUri;
+ private String getVspUri;
@ToString.Exclude
private String healthCheckUri;
}
@NoArgsConstructor
@EqualsAndHashCode
@ToString
+@Getter
+@Setter
public abstract class ComponentMetadataDataDefinition extends ToscaDataDefinition {
private static final Logger LOGGER = Logger.getLogger(ComponentMetadataDataDefinition.class.getName());
- @Getter
private String uniqueId;
- @Getter
- @Setter
private String name; // archiveName
- @Getter
- @Setter
private String version; // archiveVersion
- @Getter
- @Setter
private Boolean highestVersion;
- @Getter
- @Setter
private Long creationDate;
- @Getter
- @Setter
private Long lastUpdateDate;
- @Getter
- @Setter
private String description;
- @Getter
- @Setter
private String state;
- @Getter
- @Setter
private List<String> tags;
- @Getter
- @Setter
private String conformanceLevel;
- @Getter
- @Setter
private String icon;
- @Getter
private String UUID;
- @Getter
- @Setter
private String normalizedName;
- @Getter
- @Setter
private String systemName;
- @Getter
- @Setter
private String contactId;
- @Getter
- @Setter
private Map<String, String> allVersions;
- @Getter
- @Setter
private Boolean isDeleted;
- @Getter
- @Setter
private String projectCode;
- @Getter
- @Setter
private String csarUUID;
- @Getter
- @Setter
private String csarVersion;
- @Getter
- @Setter
private String importedToscaChecksum;
- @Getter
private String invariantUUID;
- @Getter
- @Setter
protected ComponentTypeEnum componentType;
- // USER
- @Getter
- @Setter
private String creatorUserId;
- @Getter
- @Setter
private String creatorFullName;
- @Getter
- @Setter
private String lastUpdaterUserId;
- @Getter
- @Setter
private String lastUpdaterFullName;
- //Archive/Restore
- @Getter
- @Setter
private Boolean isArchived = false;
- @Getter
- @Setter
private Long archiveTime;
- @Getter
- @Setter
private Boolean isVspArchived = false;
- @Getter
- @Setter
private Map<String, String> categorySpecificMetadata;
- @Getter
- @Setter
private String model;
- public ComponentMetadataDataDefinition(ComponentMetadataDataDefinition other) {
+ protected ComponentMetadataDataDefinition(ComponentMetadataDataDefinition other) {
this.uniqueId = other.getUniqueId();
this.name = other.getName();
this.version = other.getVersion();
this.model = other.getModel();
}
- public ComponentMetadataDataDefinition(JsonPresentationFieldsExtractor extractor) {
+ protected ComponentMetadataDataDefinition(JsonPresentationFieldsExtractor extractor) {
this.uniqueId = extractor.getUniqueId();
this.name = extractor.getName();
this.version = extractor.getVersion();
package org.openecomp.sdc.be.datatypes.components;
import lombok.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFieldsExtractor;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
@EqualsAndHashCode(callSuper = true)
+@Getter
+@Setter
+@ToString(callSuper = true)
public class ResourceMetadataDataDefinition extends ComponentMetadataDataDefinition {
private String vendorName;
private String vendorRelease;
private String resourceVendorModelNumber;
- private ResourceTypeEnum resourceType = ResourceTypeEnum.VFC; // ResourceType.VFC
-
- // is
-
- // default
+ private ResourceTypeEnum resourceType = ResourceTypeEnum.VFC;
private Boolean isAbstract;
private String cost;
private String licenseType;
private String toscaResourceName;
+ private String csarVersionId;
public ResourceMetadataDataDefinition() {
super();
this.isAbstract = other.isHighestVersion();
this.resourceType = other.getResourceType();
this.toscaResourceName = other.getToscaResourceName();
+ this.csarVersionId = other.getCsarVersionId();
}
public ResourceMetadataDataDefinition(JsonPresentationFieldsExtractor extractor) {
this.isAbstract = extractor.isAbstract();
this.resourceType = extractor.getResourceType();
this.toscaResourceName = extractor.getToscaResourceName();
- }
-
- public String getVendorName() {
- return vendorName;
- }
-
- public void setVendorName(String vendorName) {
- this.vendorName = vendorName;
- }
-
- public String getVendorRelease() {
- return vendorRelease;
- }
-
- public void setVendorRelease(String vendorRelease) {
- this.vendorRelease = vendorRelease;
- }
-
- public String getResourceVendorModelNumber() {
- return resourceVendorModelNumber;
- }
-
- public void setResourceVendorModelNumber(String resourceVendorModelNumber) {
- this.resourceVendorModelNumber = resourceVendorModelNumber;
- }
-
- public ResourceTypeEnum getResourceType() {
- return resourceType;
- }
-
- public void setResourceType(ResourceTypeEnum resourceType) {
- this.resourceType = resourceType;
+ this.csarVersionId = extractor.getCsarVersionId();
}
public Boolean isAbstract() {
- return isAbstract;
- }
-
- public void setAbstract(Boolean isAbstract) {
- this.isAbstract = isAbstract;
- }
-
- public String getCost() {
- return cost;
- }
-
- public void setCost(String cost) {
- this.cost = cost;
- }
-
- public String getLicenseType() {
- return licenseType;
- }
-
- public void setLicenseType(String licenseType) {
- this.licenseType = licenseType;
- }
-
- public String getToscaResourceName() {
- return toscaResourceName;
- }
-
- public void setToscaResourceName(String toscaResourceName) {
- this.toscaResourceName = toscaResourceName;
+ return getIsAbstract();
}
- @Override
- public String toString() {
- return "ResourceMetadataDataDefinition [vendorName=" + vendorName + ", vendorRelease=" + vendorRelease + ", resourceVendorModelNumber="
- + resourceVendorModelNumber + ", resourceType=" + resourceType + ", isAbstract=" + isAbstract + super.toString() + "]";
+ public void setAbstract(final Boolean isAbstract) {
+ setIsAbstract(isAbstract);;
}
@Override
INVARIANT_UUID("invariantUuid", GraphPropertyEnum.INVARIANT_UUID),
CSAR_UUID("csarUuid", GraphPropertyEnum.CSAR_UUID),
CSAR_VERSION("csarVersion", null),
+ CSAR_VERSION_ID("csarVersionId", null),
IMPORTED_TOSCA_CHECKSUM("importedToscaChecksum", null),
CONTACT_ID("contactId", null),
PROJECT_CODE("projectCode", null),
return (String) properties.get(JsonPresentationFields.CSAR_VERSION.getPresentation());
}
+ public String getCsarVersionId() {
+ return (String) properties.get(JsonPresentationFields.CSAR_VERSION_ID.getPresentation());
+ }
+
public String getImportedToscaChecksum() {
return (String) properties.get(JsonPresentationFields.IMPORTED_TOSCA_CHECKSUM.getPresentation());
}
public void setRequirements(String path, String fileName, User user, String derivedFromSource) throws IOException, JSONException {
Map<String, Object> requirementsFromFile = getRequirementsMapFromFile(path + File.separator + fileName,
- toscaResourceName, "requirements");
+ getToscaResourceName(), "requirements");
Map<String, Object> reqs = organizeRequirementsMap(requirementsFromFile);
getDerivedReqCap(user, reqs, "requirements", derivedFromSource);
this.requirements = reqs;
public void setCapabilities(String path, String fileName, User user, String derivedFromSource) throws IOException, JSONException {
Map<String, Object> capabilitiesFromFile = getCapabilitiesMapFromFile(path + File.separator + fileName,
- toscaResourceName, CAPS);
+ getToscaResourceName(), CAPS);
Map<String, Object> caps = organizeCapabilitiesMap(capabilitiesFromFile);
getDerivedReqCap(user, caps, CAPS, derivedFromSource);
this.capabilities = caps;
package org.onap.sdc.backend.ci.tests.datatypes;
+import lombok.AccessLevel;
+import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.model.Resource;
import java.util.List;
+@Getter
+@Setter
+@ToString(callSuper = false)
public class ResourceReqDetails extends ComponentReqDetails {
- List<String> derivedFrom;
- String vendorName;
- String vendorRelease;
- String componentType = "RESOURCE";
- public String getComponentType() {
- return componentType;
- }
- // Unsettable/unupdatable fields
-
- Boolean isAbstract;
- Boolean isHighestVersion;
- String cost;
-
- String licenseType;
- String toscaResourceName;
- String resourceVendorModelNumber;
-
- private String resourceType = ResourceTypeEnum.VFC.toString(); // Default
- // value
+ private List<String> derivedFrom;
+ private String vendorName;
+ private String vendorRelease;
+ @Setter(AccessLevel.NONE)
+ private String componentType = "RESOURCE";
+ private String csarVersionId;
+ private Boolean isAbstract;
+ private Boolean isHighestVersion;
+ private String cost;
+ private String licenseType;
+ private String toscaResourceName;
+ private String resourceVendorModelNumber;
+ private String resourceType = ResourceTypeEnum.VFC.toString();
public ResourceReqDetails() {
super();
this.toscaResourceName = resourceName;
}
- public String getResourceVendorModelNumber() {
- return resourceVendorModelNumber;
- }
-
- public void setResourceVendorModelNumber(String resourceVendorModelNumber) {
- this.resourceVendorModelNumber = resourceVendorModelNumber;
- }
- public String getToscaResourceName() {
- return toscaResourceName;
- }
-
- public void setToscaResourceName(String toscaResourceName) {
- this.toscaResourceName = toscaResourceName;
- }
-
- public List<String> getDerivedFrom() {
- return derivedFrom;
- }
-
- public void setDerivedFrom(List<String> derivedFrom) {
- this.derivedFrom = derivedFrom;
- }
-
- public String getVendorName() {
- return vendorName;
- }
-
- public void setVendorName(String vendorName) {
- this.vendorName = vendorName;
- }
-
- public String getVendorRelease() {
- return vendorRelease;
- }
-
- public void setVendorRelease(String vendorRelease) {
- this.vendorRelease = vendorRelease;
- }
-
- public String getCost() {
- return cost;
- }
-
- public void setCost(String cost) {
- this.cost = cost;
- }
-
- public String getLicenseType() {
- return licenseType;
- }
-
- public void setLicenseType(String licenseType) {
- this.licenseType = licenseType;
- }
-
- // Unupdatable fields - to check that they are not updated
- public void setIsAbstract(Boolean isAbstract) {
- this.isAbstract = isAbstract;
- }
-
- public void setIsHighestVersion(Boolean isHighestVersion) {
- this.isHighestVersion = isHighestVersion;
- }
-
- public Boolean getIsAbstract() {
- return isAbstract;
- }
-
- public Boolean getIsHighestVersion() {
- return isHighestVersion;
- }
-
- public String getResourceType() {
- return resourceType;
- }
-
- public void setResourceType(String resourceType) {
- this.resourceType = resourceType;
- }
-
- @Override
- public String toString() {
- return "ResourceReqDetails [name=" + name + ", derivedFrom=" + derivedFrom + ", vendorName=" + vendorName
- + ", vendorRelease=" + vendorRelease + ", version=" + version + ", isAbstract=" + isAbstract
- + ", isHighestVersion=" + isHighestVersion + ", cost=" + cost + ", licenseType=" + licenseType
- + ", resourceType=" + resourceType + "]";
- }
-
-}
+}
\ No newline at end of file
* 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.
package org.onap.sdc.backend.ci.tests.datatypes;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
+import lombok.ToString;
+
+@Getter
+@Setter
+@ToString(callSuper = false)
+@NoArgsConstructor
public class VendorSoftwareProductObject extends VendorSoftwareProductObjectReqDetails {
private String vspId;
private String componentId;
private String attContact;
private String version;
-
- public VendorSoftwareProductObject(){super();}
+ private String versionId;
public VendorSoftwareProductObject(String vspId, String componentId, String attContact, String version) {
this.vspId = vspId;
this.version = version;
}
- public String getVspId() {
- return vspId;
- }
-
- public void setVspId(String vspId) {
- this.vspId = vspId;
- }
-
- public String getComponentId() {
- return componentId;
- }
-
- public void setComponentId(String componentId) {
- this.componentId = componentId;
- }
-
- public String getAttContact() {
- return attContact;
- }
-
- public void setAttContact(String attContact) {
- this.attContact = attContact;
- }
-
- public String getVersion() {
- return version;
- }
-
- public void setVersion(String version) {
- this.version = version;
- }
-
- @Override
- public String toString() {
- return "VendorSoftwareProductObject{" +
- "vspId='" + vspId + '\'' +
- ", componentId='" + componentId + '\'' +
- ", attContact='" + attContact + '\'' +
- ", version='" + version + '\'' +
- '}';
- }
}
}
}
- public static Either<Resource, RestResponse> createResourceByResourceDetails(ResourceReqDetails resourceDetails, UserRoleEnum userRole, Boolean validateState) {
+ public static Either<Resource, RestResponse> createResourceByResourceDetails(final ResourceReqDetails resourceDetails,
+ final UserRoleEnum userRole,
+ final Boolean validateState) {
try {
User defaultUser = ElementFactory.getDefaultUser(userRole);
RestResponse resourceResp = ResourceRestUtils.createResource(resourceDetails, defaultUser);
if (validateState) {
- assertTrue("Create resource failed with error: " + resourceResp.getResponse(),resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED);
+ assertEquals("Create resource failed with error: " + resourceResp.getResponse(),
+ ResourceRestUtils.STATUS_CODE_CREATED, (int) resourceResp.getErrorCode());
}
if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
tags.add(vendorSoftwareProductObject.getName());
resourceDetails.setCsarUUID(vendorSoftwareProductObject.getVspId());
resourceDetails.setCsarVersion(vendorSoftwareProductObject.getVersion());
+ resourceDetails.setCsarVersionId(vendorSoftwareProductObject.getVersionId());
resourceDetails.setName(vendorSoftwareProductObject.getName());
resourceDetails.setTags(tags);
resourceDetails.setDescription(vendorSoftwareProductObject.getDescription());
RestResponse response = http.httpSendPost(url, body, headersMap);
vendorSoftwareProductObject.setVspId(ResponseParser.getValueFromJsonResponse(response.getResponse(), "itemId"));
+ vendorSoftwareProductObject.setVersionId(ResponseParser.getValueFromJsonResponse(response.getResponse(), "version:id"));
vendorSoftwareProductObject.setComponentId(ResponseParser.getValueFromJsonResponse(response.getResponse(), "version:id"));
-// vendorSoftwareProductObject.setVersion(ResponseParser.getValueFromJsonResponse(response.getResponse(), "version:name"));
vendorSoftwareProductObject.setAttContact(user.getUserId());
return new Pair<>(response, vendorSoftwareProductObject);
}
@Override
- public Response getTranslatedFile(String vspId, String versionName, String user) {
- List<Version> versions = versioningManager.list(vspId);
- Version version;
- if (versionName == null) {
+ public Response getTranslatedFile(String vspId, String versionId, String user) {
+ final List<Version> versions = versioningManager.list(vspId);
+ final Version version;
+ if (versionId == null) {
version = versions.stream().filter(ver -> VersionStatus.Certified == ver.getStatus())
.max(Comparator.comparingDouble(o -> Double.parseDouble(o.getName())))
.orElseThrow(() -> new CoreException(new PackageNotFoundErrorBuilder(vspId).build()));
} else {
- version = versions.stream().filter(ver -> versionName.equals(ver.getName())).findFirst()
- .orElseThrow(() -> new CoreException(new PackageNotFoundErrorBuilder(vspId).build()));
+ version = versions.stream()
+ .filter(ver -> versionId.equals(ver.getName()) || versionId.equals(ver.getId()))
+ .findFirst()
+ .orElseThrow(() -> new CoreException(new PackageNotFoundErrorBuilder(vspId, versionId).build()));
if (version.getStatus() != VersionStatus.Certified) {
throw new CoreException(new RequestedVersionInvalidErrorBuilder().build());
}
builder.withMessage(String.format(PACKAGE_VERSION_NOT_FOUND_MSG, vendorSoftwareProductId, version == null ? null : version.toString()));
}
+ public PackageNotFoundErrorBuilder(String vendorSoftwareProductId, String version) {
+ builder.withId(VendorSoftwareProductErrorCodes.PACKAGE_NOT_FOUND);
+ builder.withCategory(ErrorCategory.APPLICATION);
+ builder.withMessage(String.format(PACKAGE_VERSION_NOT_FOUND_MSG, vendorSoftwareProductId, version));
+ }
+
/**
* Instantiates a new Package not found error builder.
*