diff options
Diffstat (limited to 'vid-app-common')
76 files changed, 2163 insertions, 1314 deletions
diff --git a/vid-app-common/pom.xml b/vid-app-common/pom.xml index 9e5f58dd3..f618ec822 100755 --- a/vid-app-common/pom.xml +++ b/vid-app-common/pom.xml @@ -26,16 +26,16 @@ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <epsdk.version>2.5.0</epsdk.version> - <springframework.version>5.1.9.RELEASE</springframework.version> + <springframework.version>5.2.0.RELEASE</springframework.version> <springframework.orm.version>4.3.22.RELEASE</springframework.orm.version> <!-- epsdk-core is importing this class, which is only on spring-orm 4 but not in orm 5: org.springframework.orm.hibernate4.HibernateTransactionManager so following orm.version lets epsdk-core find it --> <hibernate.version>4.3.11.Final</hibernate.version> - <jackson.version>2.9.9</jackson.version> - <jackson.databind.version>2.9.9.3</jackson.databind.version> + <jackson.version>2.10.1</jackson.version> + <jackson.databind.version>2.10.1</jackson.databind.version> <onap.logging.version>1.6.1</onap.logging.version> - <jersey.version>2.29</jersey.version> + <jersey.version>2.29.1</jersey.version> <surefire.version>2.22.1</surefire.version> <selenium.version>3.141.59</selenium.version> <sonar.coverage.exclusions>**/webapp/**/*,**/*.js</sonar.coverage.exclusions> @@ -54,7 +54,7 @@ <sitePath>content/sites/site/org/onap/vid/${project.version}</sitePath> <aspectj.version>1.8.9</aspectj.version> - <kotlin.version>1.3.30</kotlin.version> + <kotlin.version>1.3.60</kotlin.version> <kotlin.compiler.jvmTarget>1.8</kotlin.compiler.jvmTarget> <eirslett.version>1.6</eirslett.version> diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/OperationalEnvironment.java b/vid-app-common/src/main/java/org/onap/vid/aai/OperationalEnvironment.java index be6c6e51f..71ed1713a 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/OperationalEnvironment.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/OperationalEnvironment.java @@ -3,13 +3,14 @@ * VID * ================================================================================ * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nokia. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,37 +21,83 @@ package org.onap.vid.aai; -import org.onap.vid.aai.model.RelationshipList; +import static com.fasterxml.jackson.annotation.JsonProperty.Access.WRITE_ONLY; + +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; +import org.onap.vid.aai.model.RelationshipList; @JsonIgnoreProperties(ignoreUnknown = true) -public class OperationalEnvironment { - - private String operationalEnvironmentId; - private String operationalEnvironmentName; - private String operationalEnvironmentType; - private String operationalEnvironmentStatus; - private String tenantContext; - private String workloadContext; - private String resourceVersion; - private RelationshipList relationshipList; - - public OperationalEnvironment() { +public final class OperationalEnvironment { + + private final String operationalEnvironmentId; + private final String operationalEnvironmentName; + private final String operationalEnvironmentType; + private final String operationalEnvironmentStatus; + private final String tenantContext; + private final String workloadContext; + private final String resourceVersion; + private final RelationshipList relationshipList; + + public static OperationalEnvironmentBuilder builder() { + return new OperationalEnvironmentBuilder(); + } + + @JsonCreator + OperationalEnvironment( + @JsonProperty(value = "operational-environment-id", access = WRITE_ONLY) String operationalEnvironmentId, + @JsonProperty(value = "operational-environment-name", access = WRITE_ONLY) String operationalEnvironmentName, + @JsonProperty(value = "operational-environment-type", access = WRITE_ONLY) String operationalEnvironmentType, + @JsonProperty(value = "operational-environment-status", access = WRITE_ONLY) String operationalEnvironmentStatus, + @JsonProperty(value = "tenant-context", access = WRITE_ONLY) String tenantContext, + @JsonProperty(value = "workload-context", access = WRITE_ONLY) String workloadContext, + @JsonProperty(value = "resource-version", access = WRITE_ONLY) String resourceVersion, + @JsonProperty(value = "relationship-list", access = WRITE_ONLY) RelationshipList relationshipList) { + this.operationalEnvironmentId = operationalEnvironmentId; + this.operationalEnvironmentName = operationalEnvironmentName; + this.operationalEnvironmentType = operationalEnvironmentType; + this.operationalEnvironmentStatus = operationalEnvironmentStatus; + this.tenantContext = tenantContext; + this.workloadContext = workloadContext; + this.resourceVersion = resourceVersion; + this.relationshipList = relationshipList; } - public OperationalEnvironment(OperationalEnvironmentBuilder builder) { - this.operationalEnvironmentId = builder.operationalEnvironmentId; - this.operationalEnvironmentName = builder.operationalEnvironmentName; - this.operationalEnvironmentType = builder.operationalEnvironmentType; - this.operationalEnvironmentStatus = builder.operationalEnvironmentStatus; - this.tenantContext = builder.tenantContext; - this.workloadContext = builder.workloadContext; - this.resourceVersion = builder.resourceVersion; - this.relationshipList = builder.relationshipList; + public String getOperationalEnvironmentId() { + return operationalEnvironmentId; + } + + public String getOperationalEnvironmentName() { + return operationalEnvironmentName; + } + + public String getOperationalEnvironmentType() { + return operationalEnvironmentType; + } + + public String getOperationalEnvironmentStatus() { + return operationalEnvironmentStatus; + } + + public String getTenantContext() { + return tenantContext; + } + + public String getWorkloadContext() { + return workloadContext; + } + + public String getResourceVersion() { + return resourceVersion; + } + + public RelationshipList getRelationshipList() { + return relationshipList; } public static class OperationalEnvironmentBuilder { + private String operationalEnvironmentId; private String operationalEnvironmentName; private String operationalEnvironmentType; @@ -58,127 +105,65 @@ public class OperationalEnvironment { private String tenantContext; private String workloadContext; private String resourceVersion; + private RelationshipList relationshipList; - public OperationalEnvironmentBuilder setOperationalEnvironmentId( - String operationalEnvironmentId) { + public OperationalEnvironmentBuilder withOperationalEnvironmentId( + String operationalEnvironmentId) { this.operationalEnvironmentId = operationalEnvironmentId; return this; } - public OperationalEnvironmentBuilder setOperationalEnvironmentName( - String operationalEnvironmentName) { + public OperationalEnvironmentBuilder withOperationalEnvironmentName( + String operationalEnvironmentName) { this.operationalEnvironmentName = operationalEnvironmentName; return this; } - public OperationalEnvironmentBuilder setOperationalEnvironmentType( - String operationalEnvironmentType) { + public OperationalEnvironmentBuilder withOperationalEnvironmentType( + String operationalEnvironmentType) { this.operationalEnvironmentType = operationalEnvironmentType; return this; } - public OperationalEnvironmentBuilder setOperationalEnvironmentStatus( - String operationalEnvironmentStatus) { + public OperationalEnvironmentBuilder withOperationalEnvironmentStatus( + String operationalEnvironmentStatus) { this.operationalEnvironmentStatus = operationalEnvironmentStatus; return this; } - public OperationalEnvironmentBuilder setTenantContext(String tenantContext) { + public OperationalEnvironmentBuilder withTenantContext(String tenantContext) { this.tenantContext = tenantContext; return this; } - public OperationalEnvironmentBuilder setWorkloadContext(String workloadContext) { + public OperationalEnvironmentBuilder withWorkloadContext(String workloadContext) { this.workloadContext = workloadContext; return this; } - public OperationalEnvironmentBuilder setResourceVersion(String resourceVersion) { + public OperationalEnvironmentBuilder withResourceVersion(String resourceVersion) { this.resourceVersion = resourceVersion; return this; } - public OperationalEnvironmentBuilder setRelationshipList( - RelationshipList relationshipList) { + public OperationalEnvironmentBuilder withRelationshipList( + RelationshipList relationshipList) { this.relationshipList = relationshipList; return this; } - public OperationalEnvironment createOperationalEnvironment() { - return new OperationalEnvironment(this); + public OperationalEnvironment build() { + return new OperationalEnvironment(operationalEnvironmentId, + operationalEnvironmentName, + operationalEnvironmentType, + operationalEnvironmentStatus, + tenantContext, + workloadContext, + resourceVersion, + relationshipList); } - } - - public String getOperationalEnvironmentId() { - return operationalEnvironmentId; - } - @JsonProperty("operational-environment-id") - public void setJsonOperationalEnvironmentId(String operationalEnvironmentId) { - this.operationalEnvironmentId = operationalEnvironmentId; } - public String getOperationalEnvironmentName() { - return operationalEnvironmentName; - } - - @JsonProperty("operational-environment-name") - public void setJsonOperationalEnvironmentName(String operationalEnvironmentName) { - this.operationalEnvironmentName = operationalEnvironmentName; - } - - public String getOperationalEnvironmentType() { - return operationalEnvironmentType; - } - - @JsonProperty("operational-environment-type") - public void setJsonOperationalEnvironmentType(String operationalEnvironmentType) { - this.operationalEnvironmentType = operationalEnvironmentType; - } - - public String getOperationalEnvironmentStatus() { - return operationalEnvironmentStatus; - } - - @JsonProperty("operational-environment-status") - public void setJsonOperationalEnvironmentStatus(String operationalEnvironmentStatus) { - this.operationalEnvironmentStatus = operationalEnvironmentStatus; - } - - public String getTenantContext() { - return tenantContext; - } - - @JsonProperty("tenant-context") - public void setJsonTenantContext(String tenantContext) { - this.tenantContext = tenantContext; - } - - public String getWorkloadContext() { - return workloadContext; - } - - @JsonProperty("workload-context") - public void setJsonWorkloadContext(String workloadContext) { - this.workloadContext = workloadContext; - } - - public String getResourceVersion() { - return resourceVersion; - } - - @JsonProperty("resource-version") - public void setJsonResourceVersion(String resourceVersion) { - this.resourceVersion = resourceVersion; - } - - public RelationshipList getRelationshipList() { - return relationshipList; - } - - @JsonProperty("relationship-list") - public void setJsonRelationshipList(RelationshipList relationshipList) { - this.relationshipList = relationshipList; - } } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetOperationalEnvironments/OperationalEnvironmentList.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetOperationalEnvironments/OperationalEnvironmentList.java index 13c6ada2d..6b3fbbd64 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetOperationalEnvironments/OperationalEnvironmentList.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetOperationalEnvironments/OperationalEnvironmentList.java @@ -3,13 +3,14 @@ * VID * ================================================================================ * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nokia. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,30 +21,27 @@ package org.onap.vid.aai.model.AaiGetOperationalEnvironments; -import com.fasterxml.jackson.annotation.JsonAlias; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.onap.vid.aai.OperationalEnvironment; +import static com.fasterxml.jackson.annotation.JsonProperty.Access.WRITE_ONLY; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Collections; import java.util.List; +import org.onap.vid.aai.OperationalEnvironment; @JsonIgnoreProperties(ignoreUnknown = true) -public class OperationalEnvironmentList { - - public List<OperationalEnvironment> getOperationalEnvironment() { - return operationalEnvironment; - } +public final class OperationalEnvironmentList { - @JsonAlias("operational-environment") - public void setOperationalEnvironment(List<OperationalEnvironment> operationalEnvironment) { - this.operationalEnvironment = operationalEnvironment; - } + private final List<OperationalEnvironment> operationalEnvironment; - public OperationalEnvironmentList() { + @JsonCreator + public OperationalEnvironmentList( + @JsonProperty(value = "operational-environment", access = WRITE_ONLY) List<OperationalEnvironment> operationalEnvironment) { + this.operationalEnvironment = Collections.unmodifiableList(operationalEnvironment); } - public OperationalEnvironmentList(List<OperationalEnvironment> operationalEnvironment) { - this.operationalEnvironment = operationalEnvironment; + public List<OperationalEnvironment> getOperationalEnvironment() { + return operationalEnvironment; } - - private List<OperationalEnvironment> operationalEnvironment; } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/util/AAITreeConverter.java b/vid-app-common/src/main/java/org/onap/vid/aai/util/AAITreeConverter.java index 48736bc01..111a260e1 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/util/AAITreeConverter.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/util/AAITreeConverter.java @@ -20,14 +20,12 @@ package org.onap.vid.aai.util; -import static java.util.function.Function.identity; -import static java.util.stream.Collectors.counting; -import static java.util.stream.Collectors.groupingBy; import static org.onap.vid.asdc.parser.ToscaParserImpl2.Constants.A_LA_CARTE; import java.util.Map; -import java.util.Objects; +import javax.inject.Inject; import org.apache.commons.lang3.StringUtils; +import org.onap.vid.model.ModelUtil; import org.onap.vid.model.aaiTree.AAITreeNode; import org.onap.vid.model.aaiTree.CollectionResource; import org.onap.vid.model.aaiTree.Network; @@ -56,6 +54,13 @@ public class AAITreeConverter { public static final String SERVICE_INSTANCE_SERVICE_INSTANCE_ID = "service-instance.service-instance-id"; public static final String TENANT_TENANT_NAME = "tenant.tenant-name"; + private final ModelUtil modelUtil; + + @Inject + public AAITreeConverter(ModelUtil modelUtil) { + this.modelUtil = modelUtil; + } + public ServiceInstance convertTreeToUIModel(AAITreeNode rootNode, String globalCustomerId, String serviceType, String instantiationType, String instanceRole, String instanceType) { ServiceInstance serviceInstance = new ServiceInstance(); serviceInstance.setInstanceId(rootNode.getId()); @@ -107,13 +112,7 @@ public class AAITreeConverter { } private <T extends Node> Map<String, Long> getExistingCounterMap(Map<String, T> nodeList) { - return nodeList.entrySet().stream() - .map(k -> { - ModelInfo modelInfo = k.getValue().getModelInfo(); - return StringUtils.defaultIfEmpty(modelInfo.getModelCustomizationId(), modelInfo.getModelVersionId()); - }) - .filter(Objects::nonNull) - .collect(groupingBy(identity(), counting())); + return modelUtil.getExistingCounterMap(nodeList, Node::getModelInfo); } private static ModelInfo createModelInfo(AAITreeNode aaiNode) { diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/parser/VidNotionsBuilder.java b/vid-app-common/src/main/java/org/onap/vid/asdc/parser/VidNotionsBuilder.java index d35c8df9c..760eb4251 100644 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/parser/VidNotionsBuilder.java +++ b/vid-app-common/src/main/java/org/onap/vid/asdc/parser/VidNotionsBuilder.java @@ -20,26 +20,39 @@ package org.onap.vid.asdc.parser; +import static java.util.stream.Collectors.toSet; import static org.apache.commons.lang3.StringUtils.equalsAnyIgnoreCase; import static org.apache.commons.lang3.StringUtils.equalsIgnoreCase; import static org.apache.commons.lang3.StringUtils.isEmpty; +import static org.hibernate.annotations.common.util.StringHelper.isNotEmpty; +import static org.onap.vid.utils.KotlinUtilsKt.JACKSON_OBJECT_MAPPER; import com.google.common.collect.ImmutableMap; +import java.io.IOException; import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Stream; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.onap.sdc.tosca.parser.api.ISdcCsarHelper; import org.onap.sdc.toscaparser.api.NodeTemplate; import org.onap.sdc.toscaparser.api.elements.Metadata; +import org.onap.vid.exceptions.GenericUncheckedException; import org.onap.vid.model.ServiceModel; import org.onap.vid.model.VidNotions; +import org.onap.vid.model.VidNotions.InstantiationType; +import org.onap.vid.model.VidNotions.InstantiationUI; +import org.onap.vid.model.VidNotions.ModelCategory; import org.onap.vid.properties.Features; import org.togglz.core.manager.FeatureManager; public class VidNotionsBuilder { private final FeatureManager featureManager; + private final Set<UUID> invariantToMacro; //map of service type that are always macro services, and their relevant featureFlag private static final Map<VidNotions.ModelCategory, Features> macroServicesByModelCategory = ImmutableMap.of( @@ -50,15 +63,30 @@ public class VidNotionsBuilder { public VidNotionsBuilder(FeatureManager featureManager) { this.featureManager = featureManager; + invariantToMacro = loadInvariantMacroUUIDsFromFile(); + } + + @NotNull + private Set<UUID> loadInvariantMacroUUIDsFromFile() { + try { + return Stream.of(JACKSON_OBJECT_MAPPER.readValue( + VidNotionsBuilder.class.getResource("/macro_services_by_invariant_uuid.json"), + String[].class + )).map(UUID::fromString).collect(toSet()); + } catch (IOException e) { + throw new GenericUncheckedException(e); + } } VidNotions buildVidNotions(ISdcCsarHelper csarHelper, ServiceModel serviceModel) { VidNotions.ModelCategory modelCategory = suggestModelCategory(csarHelper, serviceModel); + final InstantiationType instantiationType = suggestInstantiationType(serviceModel, modelCategory); return new VidNotions( - suggestInstantiationUI(csarHelper, serviceModel), + suggestInstantiationUI(csarHelper, serviceModel, modelCategory, instantiationType), modelCategory, - suggestViewEditUI(csarHelper, serviceModel), - suggestInstantiationType(serviceModel, modelCategory)); + suggestViewEditUI(csarHelper, serviceModel, modelCategory, instantiationType), + instantiationType + ); } private boolean isMacroTypeByModelCategory(VidNotions.ModelCategory modelCategory) { @@ -67,31 +95,51 @@ public class VidNotionsBuilder { return (featureOfMacroType!=null && featureManager.isActive(featureOfMacroType)); } - VidNotions.InstantiationType suggestInstantiationType(ServiceModel serviceModel, VidNotions.ModelCategory modelCategory) { + InstantiationType suggestInstantiationType(ServiceModel serviceModel, VidNotions.ModelCategory modelCategory) { if (isMacroTypeByModelCategory(modelCategory)) { - return VidNotions.InstantiationType.Macro; + return InstantiationType.Macro; } - if (serviceModel==null || serviceModel.getService()==null || isEmpty(serviceModel.getService().getInstantiationType())) { - return VidNotions.InstantiationType.ClientConfig; + if (serviceModel==null || serviceModel.getService()==null) { + return defaultInstantiationType(); } - String instantiationType = serviceModel.getService().getInstantiationType(); - if (instantiationType.equals(ToscaParserImpl2.Constants.MACRO)) { - return VidNotions.InstantiationType.Macro; + + if (StringUtils.equals(serviceModel.getService().getInstantiationType(), ToscaParserImpl2.Constants.MACRO)) { + return InstantiationType.Macro; } - if (instantiationType.equals(ToscaParserImpl2.Constants.A_LA_CARTE)) { - return VidNotions.InstantiationType.ALaCarte; + + if (StringUtils.equals(serviceModel.getService().getInstantiationType(), ToscaParserImpl2.Constants.A_LA_CARTE)) { + return InstantiationType.ALaCarte; } - return VidNotions.InstantiationType.ClientConfig; + if (!featureManager.isActive(Features.FLAG_2002_IDENTIFY_INVARIANT_MACRO_UUID_BY_BACKEND)) + return InstantiationType.ClientConfig; + + return isMacroByInvariantUuid(serviceModel.getService().getInvariantUuid()) ? + InstantiationType.Macro : + InstantiationType.ALaCarte; + } + + @NotNull + private InstantiationType defaultInstantiationType() { + return featureManager.isActive(Features.FLAG_2002_IDENTIFY_INVARIANT_MACRO_UUID_BY_BACKEND) ? + InstantiationType.ALaCarte : + InstantiationType.ClientConfig; } //UI route a-la-carte services to old UI only if InstantiationUI is LEGACY //So any other value for InstantiationUI other than LEGACY make UI to route //a-la-carte services to new UI - VidNotions.InstantiationUI suggestInstantiationUI(ISdcCsarHelper csarHelper, ServiceModel serviceModel) { + VidNotions.InstantiationUI suggestInstantiationUI(ISdcCsarHelper csarHelper, ServiceModel serviceModel, ModelCategory modelCategory, InstantiationType instantiationType) { if(featureManager.isActive(Features.FLAG_EXP_ANY_ALACARTE_NEW_INSTANTIATION_UI) && isALaCarte(csarHelper)) { return VidNotions.InstantiationUI.ANY_ALACARTE_NEW_UI; } + + if (featureManager.isActive(Features.FLAG_2002_ANY_ALACARTE_BESIDES_EXCLUDED_NEW_INSTANTIATION_UI) && + !isMacro(instantiationType) && + !isAlacarteExcludedByCategory(modelCategory)) { + return InstantiationUI.ANY_ALACARTE_WHICH_NOT_EXCLUDED; + } + if (featureManager.isActive(Features.FLAG_1902_VNF_GROUPING) && isGrouping(csarHelper)) { return VidNotions.InstantiationUI.SERVICE_WITH_VNF_GROUPING; } @@ -115,6 +163,10 @@ public class VidNotionsBuilder { } + private boolean isAlacarteExcludedByCategory(ModelCategory modelCategory) { + return modelCategory==ModelCategory.PORT_MIRRORING || modelCategory==ModelCategory.VLAN_TAGGING ; + } + private boolean isVnfServiceRole(ISdcCsarHelper csarHelper) { final String serviceRole = csarHelper.getServiceMetadata().getValue(ToscaParserImpl2.Constants.SERVICE_ROLE ); return StringUtils.equalsIgnoreCase("VNF" , serviceRole); @@ -153,6 +205,12 @@ public class VidNotionsBuilder { if(isALaCarte(csarHelper) && hasFabricConfiguration(csarHelper)) { return VidNotions.ModelCategory.IS_5G_FABRIC_CONFIGURATION_MODEL; } + if (isPortMirroringService(serviceModel)) { + return ModelCategory.PORT_MIRRORING; + } + if (isVlanTaggingService(serviceModel)) { + return ModelCategory.VLAN_TAGGING; + } if (isInfraStructureVpn(csarHelper)) { return VidNotions.ModelCategory.INFRASTRUCTURE_VPN; } @@ -165,13 +223,13 @@ public class VidNotionsBuilder { return VidNotions.ModelCategory.OTHER; } - VidNotions.InstantiationUI suggestViewEditUI(ISdcCsarHelper csarHelper, ServiceModel serviceModel) { + VidNotions.InstantiationUI suggestViewEditUI(ISdcCsarHelper csarHelper, ServiceModel serviceModel, ModelCategory modelCategory, InstantiationType instantiationType) { if (featureManager.isActive(Features.FLAG_1902_VNF_GROUPING) && isGrouping(csarHelper)) { return VidNotions.InstantiationUI.SERVICE_WITH_VNF_GROUPING; } if (featureManager.isActive(Features.FLAG_1908_MACRO_NOT_TRANSPORT_NEW_VIEW_EDIT) && - isMacro(serviceModel) && + isMacro(instantiationType) && !isTransportService(csarHelper) && //till new view/edit would support fabric service activation !hasFabricConfiguration(csarHelper)) { @@ -179,7 +237,7 @@ public class VidNotionsBuilder { } if (featureManager.isActive(Features.FLAG_1902_NEW_VIEW_EDIT)) { - VidNotions.InstantiationUI instantiationUISuggestion = suggestInstantiationUI(csarHelper, serviceModel); + VidNotions.InstantiationUI instantiationUISuggestion = suggestInstantiationUI(csarHelper, serviceModel, modelCategory, instantiationType); if (instantiationUISuggestion!=VidNotions.InstantiationUI.LEGACY) { return instantiationUISuggestion; } @@ -188,8 +246,8 @@ public class VidNotionsBuilder { return VidNotions.InstantiationUI.LEGACY; } - private boolean isMacro(ServiceModel serviceModel) { - return ToscaParserImpl2.Constants.MACRO.equals(serviceModel.getService().getInstantiationType()); + private boolean isMacro(InstantiationType instantiationType) { + return instantiationType==InstantiationType.Macro; } private boolean isUuidExactlyHardCoded1ffce89fef3f(ISdcCsarHelper csarHelper) { @@ -232,4 +290,29 @@ public class VidNotionsBuilder { final String serviceRole = csarHelper.getServiceMetadata().getValue(ToscaParserImpl2.Constants.SERVICE_ROLE); return StringUtils.equalsIgnoreCase(serviceRole, ToscaParserImpl2.Constants.GROUPING); } + + private boolean isPortMirroringService(ServiceModel serviceModel) { + return (serviceModel.getService()!=null && + StringUtils.equals(serviceModel.getService().getServiceType(), "PORT-MIRROR")); + } + + private boolean isVlanTaggingService(ServiceModel serviceModel) { + if (serviceModel==null || serviceModel.getVnfs()==null) { + return false; + } + + return serviceModel.getVnfs().values().stream().anyMatch( + vnf-> MapUtils.isNotEmpty(vnf.getVfcInstanceGroups()) + ); + + } + + protected boolean isMacroByInvariantUuid(String uuid) { + try { + return invariantToMacro.contains(UUID.fromString(uuid)); + } + catch (IllegalArgumentException | NullPointerException e) { //not a uuid + return false; + } + } } diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/AsyncInstantiationController.java b/vid-app-common/src/main/java/org/onap/vid/controller/AsyncInstantiationController.java index 6bd98fff6..96e777a13 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controller/AsyncInstantiationController.java +++ b/vid-app-common/src/main/java/org/onap/vid/controller/AsyncInstantiationController.java @@ -26,6 +26,7 @@ import java.util.List; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.vid.dal.AsyncInstantiationRepository; import org.onap.vid.exceptions.AccessDeniedException; import org.onap.vid.model.JobAuditStatus; import org.onap.vid.model.ServiceInfo; @@ -35,8 +36,10 @@ import org.onap.vid.properties.Features; import org.onap.vid.roles.RoleProvider; import org.onap.vid.services.AsyncInstantiationBusinessLogic; import org.onap.vid.services.AuditService; +import org.onap.vid.services.InstantiationTemplatesService; import org.onap.vid.utils.SystemPropertiesWrapper; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; @@ -53,21 +56,29 @@ public class AsyncInstantiationController extends VidRestrictedBaseController { public static final String ASYNC_INSTANTIATION = "asyncInstantiation"; protected final AsyncInstantiationBusinessLogic asyncInstantiationBL; + protected final InstantiationTemplatesService instantiationTemplates; + protected final AsyncInstantiationRepository asyncInstantiationRepository; private final SystemPropertiesWrapper systemPropertiesWrapper; private final RoleProvider roleProvider; private final FeatureManager featureManager; - @Autowired - protected AuditService auditService; + protected final AuditService auditService; @Autowired - public AsyncInstantiationController(AsyncInstantiationBusinessLogic asyncInstantiationBL, RoleProvider roleProvider, FeatureManager featureManager, SystemPropertiesWrapper systemPropertiesWrapper) { + public AsyncInstantiationController(AsyncInstantiationBusinessLogic asyncInstantiationBL, + InstantiationTemplatesService instantiationTemplates, + AsyncInstantiationRepository asyncInstantiationRepository, RoleProvider roleProvider, + FeatureManager featureManager, SystemPropertiesWrapper systemPropertiesWrapper, + AuditService auditService) { this.asyncInstantiationBL = asyncInstantiationBL; + this.instantiationTemplates = instantiationTemplates; + this.asyncInstantiationRepository = asyncInstantiationRepository; this.roleProvider = roleProvider; this.featureManager = featureManager; this.systemPropertiesWrapper = systemPropertiesWrapper; + this.auditService = auditService; } /** @@ -76,8 +87,13 @@ public class AsyncInstantiationController extends VidRestrictedBaseController { * @return the services list */ @RequestMapping(method = RequestMethod.GET) - public List<ServiceInfo> getServicesInfo(HttpServletRequest request) { - return asyncInstantiationBL.getAllServicesInfo(); + public List<ServiceInfo> getServicesInfo(HttpServletRequest request, + @RequestParam(value = "serviceModelId", required = false) UUID serviceModelId) { + if (serviceModelId == null) { + return asyncInstantiationBL.getAllServicesInfo(); + } else { + return asyncInstantiationRepository.listServicesByServiceModelId(serviceModelId); + } } @RequestMapping(value = "bulk", method = RequestMethod.POST) @@ -158,6 +174,11 @@ public class AsyncInstantiationController extends VidRestrictedBaseController { return new MsoResponseWrapper2(200, uuids); } + @GetMapping("templateTopology/{jobId}") + public ServiceInstantiation getTemplateTopology(HttpServletRequest request, @PathVariable(value="jobId") UUID jobId) { + return instantiationTemplates.getJobRequestAsTemplate(jobId); + } + @RequestMapping(value = "/auditStatusForRetry/{trackById}", method = RequestMethod.GET) public JobAuditStatus getResourceAuditStatus(HttpServletRequest request, @PathVariable(value="trackById") String trackById) { return auditService.getResourceAuditStatus(trackById); diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/LoggerController.java b/vid-app-common/src/main/java/org/onap/vid/controller/LoggerController.java index 7233a67e3..f5b325b4a 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controller/LoggerController.java +++ b/vid-app-common/src/main/java/org/onap/vid/controller/LoggerController.java @@ -66,7 +66,7 @@ public class LoggerController extends RestrictedBaseController { this.logfilePathCreator = logfilePathCreator; } - @GetMapping(value = "/{loggerName:audit|audit2019|error|metrics|metrics2019}") + @GetMapping(value = "/{loggerName:audit|audit2019|error|metrics|metrics2019|debug}") public String getLog(@PathVariable String loggerName, HttpServletRequest request, @RequestParam(value="limit", defaultValue = "5000") Integer limit) throws IOException { diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/OperationalEnvironmentController.java b/vid-app-common/src/main/java/org/onap/vid/controller/OperationalEnvironmentController.java index 44bdc813b..d291f9925 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controller/OperationalEnvironmentController.java +++ b/vid-app-common/src/main/java/org/onap/vid/controller/OperationalEnvironmentController.java @@ -20,10 +20,21 @@ */ package org.onap.vid.controller; +import static org.onap.vid.utils.Logging.getMethodCallerName; +import static org.onap.vid.utils.Logging.getMethodName; + import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.MoreObjects; import io.joshworks.restclient.http.HttpResponse; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; @@ -42,19 +53,13 @@ import org.onap.vid.utils.SystemPropertiesWrapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.MissingServletRequestParameterException; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import static org.onap.vid.utils.Logging.getMethodCallerName; -import static org.onap.vid.utils.Logging.getMethodName; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("operationalEnvironment") @@ -64,7 +69,7 @@ public class OperationalEnvironmentController extends VidRestrictedBaseControlle private final MsoBusinessLogic msoBusinessLogic; private final SystemPropertiesWrapper systemPropertiesWrapper; - private static final Pattern RECOVERY_ACTION_MESSAGE_PATTERN = Pattern.compile("from String \"(.*)\": value not"); + private static final Pattern RECOVERY_ACTION_MESSAGE_PATTERN = Pattern.compile("from String \"(.*)\": not one"); @Autowired diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/WebConfig.java b/vid-app-common/src/main/java/org/onap/vid/controller/WebConfig.java index 91fb94231..cfb848007 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controller/WebConfig.java +++ b/vid-app-common/src/main/java/org/onap/vid/controller/WebConfig.java @@ -58,7 +58,6 @@ import org.onap.vid.properties.VidProperties; import org.onap.vid.scheduler.SchedulerService; import org.onap.vid.scheduler.SchedulerServiceImpl; import org.onap.vid.services.AAIServiceTree; -import org.onap.vid.services.AAITreeNodeBuilder; import org.onap.vid.services.AaiService; import org.onap.vid.services.AaiServiceImpl; import org.onap.vid.services.ChangeManagementService; @@ -66,9 +65,11 @@ import org.onap.vid.services.PombaService; import org.onap.vid.services.PombaServiceImpl; import org.onap.vid.utils.JoshworksJacksonObjectMapper; import org.onap.vid.utils.Logging; +import org.onap.vid.utils.SystemPropertiesWrapper; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.core.Ordered; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.togglz.core.manager.FeatureManager; @@ -100,8 +101,8 @@ public class WebConfig implements WebMvcConfigurer { @Bean public AaiService getAaiService(AaiClientInterface aaiClient, AaiResponseTranslator aaiResponseTranslator, - AAITreeNodeBuilder aaiTreeNode, AAIServiceTree aaiServiceTree, ExecutorService executorService) { - return new AaiServiceImpl(aaiClient, aaiResponseTranslator, aaiServiceTree, executorService); + AAIServiceTree aaiServiceTree, Logging logging, ExecutorService executorService) { + return new AaiServiceImpl(aaiClient, aaiResponseTranslator, aaiServiceTree, executorService, logging); } @Bean @@ -222,6 +223,8 @@ public class WebConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { - registry.addInterceptor(new VidLoggingInterceptor()); + registry.addInterceptor( + new VidLoggingInterceptor(new ControllersUtils(new SystemPropertiesWrapper())) + ).order(Ordered.HIGHEST_PRECEDENCE); } } diff --git a/vid-app-common/src/main/java/org/onap/vid/dal/AsyncInstantiationRepository.kt b/vid-app-common/src/main/java/org/onap/vid/dal/AsyncInstantiationRepository.kt index 79c7297a3..c26b88a5e 100644 --- a/vid-app-common/src/main/java/org/onap/vid/dal/AsyncInstantiationRepository.kt +++ b/vid-app-common/src/main/java/org/onap/vid/dal/AsyncInstantiationRepository.kt @@ -86,13 +86,22 @@ class AsyncInstantiationRepository @Autowired constructor(val dataAccessService: private fun filterByCreationDateAndNotDeleted(): String { val minus3Months = LocalDateTime.now().minusMonths(3) val filterDate = Timestamp.valueOf(minus3Months) + return filterServicesByNotHiddenAndNotDeleted() + + " and created >= '" + filterDate + "' " + } + + private fun filterByServiceModelId(serviceModelUuid: UUID): String { + return filterServicesByNotHiddenAndNotDeleted() + + " and SERVICE_MODEL_ID = '$serviceModelUuid'" + } + + private fun filterServicesByNotHiddenAndNotDeleted(): String { return " WHERE" + " hidden = false" + - " and deleted_at is null" + // don't fetch deleted - - " and created >= '" + filterDate + "' " + " and deleted_at is null" // don't fetch deleted } + private fun orderByCreatedDateAndStatus(): String { return " createdBulkDate DESC ,\n" + " (CASE jobStatus\n" + @@ -144,4 +153,7 @@ class AsyncInstantiationRepository @Autowired constructor(val dataAccessService: .joinToString(" $conditionType ") return dataAccessService.getList(className, " WHERE $condition", orderBy, null) as List<T> } + + fun listServicesByServiceModelId(serviceModelId: UUID): List<ServiceInfo> = + dataAccessService.getList(ServiceInfo::class.java, filterByServiceModelId(serviceModelId), orderByCreatedDateAndStatus(), null) as List<ServiceInfo>; } diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/MacroServiceCommand.kt b/vid-app-common/src/main/java/org/onap/vid/job/command/MacroServiceCommand.kt index 8ce73d713..2fdd19100 100644 --- a/vid-app-common/src/main/java/org/onap/vid/job/command/MacroServiceCommand.kt +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/MacroServiceCommand.kt @@ -62,13 +62,13 @@ class MacroServiceCommand @Autowired constructor( //Aai return bad response while checking names uniqueness catch (exception : ExceptionWithRequestInfo) { - Logger.error("Failed to check name uniqueness in AAI. VID will try again later", exception) + Logger.error(EELFLoggerDelegate.errorLogger, "Failed to check name uniqueness in AAI. VID will try again later", exception) throw TryAgainException(exception); } //Vid reached to max retries while trying to find unique name in AAI catch (exception : MaxRetriesException) { - Logger.error("Failed to find unused name in AAI", exception) + Logger.error(EELFLoggerDelegate.errorLogger, "Failed to find unused name in AAI", exception) throw AbortingException(exception); } } diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/MsoRequestBuilder.kt b/vid-app-common/src/main/java/org/onap/vid/job/command/MsoRequestBuilder.kt index b35deb892..e46a24f78 100644 --- a/vid-app-common/src/main/java/org/onap/vid/job/command/MsoRequestBuilder.kt +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/MsoRequestBuilder.kt @@ -11,7 +11,6 @@ import org.onap.vid.changeManagement.RequestDetailsWrapper import org.onap.vid.model.serviceInstantiation.* import org.onap.vid.mso.model.* import org.onap.vid.mso.model.BaseResourceInstantiationRequestDetails.* -import org.onap.vid.mso.model.VfModuleInstantiationRequestDetails.UserParamMap import org.onap.vid.mso.rest.SubscriberInfo import org.onap.vid.properties.Features import org.onap.vid.services.AsyncInstantiationBusinessLogic @@ -99,15 +98,17 @@ class MsoRequestBuilder return RequestDetailsWrapper(VnfInstantiationRequestDetails(vnfDetails.modelInfo, cloudConfiguration, requestInfo, null, null, null, null)) } - fun generateVfModuleInstantiationRequest(vfModuleDetails: VfModule, serviceModelInfo: ModelInfo, serviceInstanceId: String, vnfModelInfo: ModelInfo, vnfInstanceId: String, vgInstanceId: String?, userId: String, testApi: String?): RequestDetailsWrapper<VfModuleInstantiationRequestDetails> { + protected fun generateVfModuleRequestWithRequestParams( + vfModuleDetails: VfModule, serviceModelInfo: ModelInfo, + serviceInstanceId: String, vnfModelInfo: ModelInfo, vnfInstanceId: String, vgInstanceId: String?, userId: String, + requestParameters: (userParams: List<UserParamTypes>) -> RequestParametersVfModuleOrVolumeGroup + ): RequestDetailsWrapper<VfModuleOrVolumeGroupRequestDetails> { val requestInfo = generateRequestInfo(vfModuleDetails.instanceName, ResourceType.VF_MODULE, vfModuleDetails.isRollbackOnFailure, null, userId) //cloud configuration val cloudConfiguration = generateCloudConfiguration(vfModuleDetails.lcpCloudRegionId, vfModuleDetails.tenantId) - //request parameters val userParams = aggregateAllInstanceParams(extractActualInstanceParams(vfModuleDetails.instanceParams), vfModuleDetails.supplementaryParams) - val requestParameters = VfModuleInstantiationRequestDetails.RequestParametersVfModule(userParams, vfModuleDetails.isUsePreload, testApi) //related instance list val relatedInstanceList = generateRelatedInstances(mapOf(serviceInstanceId to serviceModelInfo, vnfInstanceId to vnfModelInfo)) @@ -116,14 +117,44 @@ class MsoRequestBuilder volumeGroupModel.modelType = "volumeGroup" relatedInstanceList.add(RelatedInstance(volumeGroupModel, vgInstanceId, vfModuleDetails.volumeGroupInstanceName)) } - return RequestDetailsWrapper(VfModuleInstantiationRequestDetails(vfModuleDetails.modelInfo, cloudConfiguration, requestInfo, relatedInstanceList, requestParameters)) + + return RequestDetailsWrapper(VfModuleOrVolumeGroupRequestDetails(vfModuleDetails.modelInfo, cloudConfiguration, requestInfo, relatedInstanceList, requestParameters(userParams))) + } + + fun generateVfModuleInstantiationRequest( + vfModuleDetails: VfModule, serviceModelInfo: ModelInfo, + serviceInstanceId: String, vnfModelInfo: ModelInfo, vnfInstanceId: String, + vgInstanceId: String?, userId: String, testApi: String? + ): RequestDetailsWrapper<VfModuleOrVolumeGroupRequestDetails> { + val requestParameters = { userParams: List<UserParamTypes> -> + RequestParametersVfModuleOrVolumeGroupInstantiation(userParams, vfModuleDetails.isUsePreload, testApi) + } + + return generateVfModuleRequestWithRequestParams(vfModuleDetails, serviceModelInfo, serviceInstanceId, + vnfModelInfo, vnfInstanceId, vgInstanceId, userId, requestParameters) } + fun generateVfModuleReplaceRequest( + vfModuleDetails: VfModule, serviceModelInfo: ModelInfo, + serviceInstanceId: String, vnfModelInfo: ModelInfo, vnfInstanceId: String, + vgInstanceId: String?, userId: String, testApi: String? + ): RequestDetailsWrapper<VfModuleOrVolumeGroupRequestDetails> { + val requestParameters = { userParams: List<UserParamTypes> -> + RequestParametersVfModuleUpgrade(userParams, vfModuleDetails.isUsePreload, testApi, + vfModuleDetails.isRetainAssignments, nullSafeNegate(vfModuleDetails.isRetainVolumeGroups)) + } + + return generateVfModuleRequestWithRequestParams(vfModuleDetails, serviceModelInfo, serviceInstanceId, + vnfModelInfo, vnfInstanceId, vgInstanceId, userId, requestParameters) + } + + private fun nullSafeNegate(booleanValue: Boolean?): Boolean? = booleanValue?.not() + fun generateVolumeGroupInstantiationRequest(vfModuleDetails: VfModule, serviceModelInfo: ModelInfo, serviceInstanceId: String, vnfModelInfo: ModelInfo, vnfInstanceId: String, userId: String, testApi: String?): RequestDetailsWrapper<VolumeGroupRequestDetails> { val requestInfo = generateRequestInfo(vfModuleDetails.volumeGroupInstanceName, ResourceType.VOLUME_GROUP, vfModuleDetails.isRollbackOnFailure, null, userId) val cloudConfiguration = generateCloudConfiguration(vfModuleDetails.lcpCloudRegionId, vfModuleDetails.tenantId) val userParams = aggregateAllInstanceParams(extractActualInstanceParams(vfModuleDetails.instanceParams), vfModuleDetails.supplementaryParams) - val requestParameters = VfModuleInstantiationRequestDetails.RequestParametersVfModule(userParams, vfModuleDetails.isUsePreload, testApi) + val requestParameters = RequestParametersVfModuleOrVolumeGroupInstantiation(userParams, vfModuleDetails.isUsePreload, testApi) val relatedInstances = generateRelatedInstances(mapOf(serviceInstanceId to serviceModelInfo, vnfInstanceId to vnfModelInfo)) vfModuleDetails.modelInfo.modelType = "volumeGroup" @@ -151,10 +182,10 @@ class MsoRequestBuilder return RequestDetailsWrapper(NetworkInstantiationRequestDetails(networkDetails.modelInfo, cloudConfiguration, requestInfo, null, null, null, null)) } - fun generateDeleteVfModuleRequest(vfModuleDetails: VfModule, userId: String): RequestDetailsWrapper<VfModuleInstantiationRequestDetails> { + fun generateDeleteVfModuleRequest(vfModuleDetails: VfModule, userId: String): RequestDetailsWrapper<VfModuleOrVolumeGroupRequestDetails> { val requestInfo = generateRequestInfo(null, null, null, null, userId) val cloudConfiguration = generateCloudConfiguration(vfModuleDetails.lcpCloudRegionId, vfModuleDetails.tenantId) - return RequestDetailsWrapper(VfModuleInstantiationRequestDetails(vfModuleDetails.modelInfo, cloudConfiguration, requestInfo, null, null)) + return RequestDetailsWrapper(VfModuleOrVolumeGroupRequestDetails(vfModuleDetails.modelInfo, cloudConfiguration, requestInfo, null, null)) } private fun generateServiceName(jobId: UUID?, payload: ServiceInstantiation, optimisticUniqueServiceInstanceName: String): String? { @@ -178,7 +209,7 @@ class MsoRequestBuilder try { asyncInstantiationBL.updateServiceInfo(jobId) { x -> x.serviceInstanceName = serviceInstanceName } } catch (e: Exception) { - LOGGER.error("Failed updating service name {} in serviceInfo", serviceInstanceName, e) + LOGGER.error(EELFLoggerDelegate.errorLogger, "Failed updating service name {} in serviceInfo", serviceInstanceName, e) } return serviceInstanceName @@ -264,7 +295,7 @@ class MsoRequestBuilder }.collect(Collectors.toList<VfModuleMacro>()) } - fun aggregateAllInstanceParams(instanceParams: Map<String, String>?, supplementaryParams: Map<String, String>?): List<VfModuleInstantiationRequestDetails.UserParamMap<String, String>> { + fun aggregateAllInstanceParams(instanceParams: Map<String, String>?, supplementaryParams: Map<String, String>?): List<UserParamMap<String, String>> { var instanceParamsFinal: Map<String, String> = instanceParams ?: emptyMap() val supplementaryParamsFinal: Map<String, String> = supplementaryParams ?: emptyMap() diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/MsoResultHandlerService.kt b/vid-app-common/src/main/java/org/onap/vid/job/command/MsoResultHandlerService.kt index 50eada64f..e60919a34 100644 --- a/vid-app-common/src/main/java/org/onap/vid/job/command/MsoResultHandlerService.kt +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/MsoResultHandlerService.kt @@ -68,11 +68,11 @@ class MsoResultHandlerService fun handleResponse(sharedData: JobSharedData, msoResponse: RestObject<RequestReferencesContainer>, actionDescription: String): MsoResult { return if (msoResponse.statusCode in 200..399) { val msoResourceIds = MsoResourceIds(msoResponse.get().requestReferences.requestId, msoResponse.get().requestReferences.instanceId) - LOGGER.debug("Successfully sent $actionDescription. Request id: ${msoResourceIds.requestId}") + LOGGER.debug(EELFLoggerDelegate.debugLogger, "Successfully sent $actionDescription. Request id: ${msoResourceIds.requestId}") asyncInstantiationBL.addResourceInfo(sharedData, Job.JobStatus.IN_PROGRESS, msoResourceIds.instanceId) MsoResult(Job.JobStatus.COMPLETED_WITH_NO_ACTION, msoResourceIds) } else { - LOGGER.debug("Failed to $actionDescription. Details: ${msoResponse.raw}") + LOGGER.debug(EELFLoggerDelegate.debugLogger, "Failed to $actionDescription. Details: ${msoResponse.raw}") asyncInstantiationBL.addFailedResourceInfo(sharedData, msoResponse) MsoResult(Job.JobStatus.FAILED) } diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/ResourceCommand.kt b/vid-app-common/src/main/java/org/onap/vid/job/command/ResourceCommand.kt index a266dd002..4477a9f24 100644 --- a/vid-app-common/src/main/java/org/onap/vid/job/command/ResourceCommand.kt +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/ResourceCommand.kt @@ -23,7 +23,6 @@ package org.onap.vid.job.command import com.fasterxml.jackson.module.kotlin.convertValue import org.apache.commons.lang3.ObjectUtils.defaultIfNull -import org.onap.logging.ref.slf4j.ONAPLogConstants import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate import org.onap.vid.changeManagement.RequestDetailsWrapper import org.onap.vid.exceptions.AbortingException @@ -38,7 +37,6 @@ import org.onap.vid.mso.RestMsoImplementation import org.onap.vid.mso.model.ModelInfo import org.onap.vid.utils.JACKSON_OBJECT_MAPPER import org.onap.vid.utils.getEnumFromMapOfStrings -import org.slf4j.MDC import org.springframework.http.HttpMethod import java.util.* @@ -114,7 +112,7 @@ abstract class ResourceCommand( jobStatus = comulateStatusAndUpdatePropertyIfFinal(jobStatus) try { - Logger.debug("job: ${this.javaClass.simpleName} ${sharedData.jobUuid} $actionPhase ${getActionType()} $internalState $jobStatus $childJobs") + Logger.debug(EELFLoggerDelegate.debugLogger, "job: ${this.javaClass.simpleName} ${sharedData.jobUuid} $actionPhase ${getActionType()} $internalState $jobStatus $childJobs") } catch (e:Exception) { /* do nothing. Just failed to log...*/} if (shallStopJob(jobStatus)) { @@ -123,7 +121,7 @@ abstract class ResourceCommand( } val (nextActionPhase, nextInternalState) = calcNextInternalState(jobStatus, internalState, actionPhase) - Logger.debug("next state for job ${sharedData.jobUuid} is $nextInternalState") + Logger.debug(EELFLoggerDelegate.debugLogger, "next state for job ${sharedData.jobUuid} is $nextInternalState") actionPhase = nextActionPhase internalState = nextInternalState @@ -133,7 +131,7 @@ abstract class ResourceCommand( } jobStatus = getExternalInProgressStatus() - Logger.debug("next status for job ${sharedData.jobUuid} is $jobStatus") + Logger.debug(EELFLoggerDelegate.debugLogger, "next status for job ${sharedData.jobUuid} is $jobStatus") // if (internalState.immediate) return call() //shortcut instead of execute another command return NextCommand(jobStatus, this) } @@ -155,7 +153,7 @@ abstract class ResourceCommand( JobStatus.IN_PROGRESS } catch (exception: AbortingException) { - Logger.error("caught AbortingException. Set job status to FAILED") + Logger.error(EELFLoggerDelegate.errorLogger, "caught AbortingException. Set job status to FAILED") JobStatus.FAILED; } } @@ -362,8 +360,6 @@ abstract class ResourceCommand( } protected fun executeAndHandleMsoInstanceRequest(restCallPlan: MsoRestCallPlan): JobStatus { - //make sure requestIds are unique - MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, UUID.randomUUID().toString()) val msoResponse = restMso.restCall( restCallPlan.httpMethod, RequestReferencesContainer::class.java, diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/RootServiceCommand.kt b/vid-app-common/src/main/java/org/onap/vid/job/command/RootServiceCommand.kt index c4680b2bd..875de66d6 100644 --- a/vid-app-common/src/main/java/org/onap/vid/job/command/RootServiceCommand.kt +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/RootServiceCommand.kt @@ -71,13 +71,13 @@ abstract class RootServiceCommand @Autowired constructor( try { val requests = auditService.retrieveRequestsFromMsoByServiceIdAndRequestTypeAndScope(serviceInstanceId, requestType, scope) if (requests.isEmpty() || requests[0].requestId == null) { - LOGGER.error("Failed to retrieve requestId with type: $type, scope: $scope for service instanceId $serviceInstanceId ") + LOGGER.error(EELFLoggerDelegate.errorLogger, "Failed to retrieve requestId with type: $type, scope: $scope for service instanceId $serviceInstanceId ") return Job.JobStatus.FAILED } val createMyselfCommand = planResumeMyselfRestCall(requests[0].requestId, sharedData.userId) return executeAndHandleMsoInstanceRequest(createMyselfCommand) } catch (exception: Exception) { - LOGGER.error("Failed to resume instanceId $serviceInstanceId ", exception) + LOGGER.error(EELFLoggerDelegate.errorLogger, "Failed to resume instanceId $serviceInstanceId ", exception) return Job.JobStatus.FAILED } } diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/VfmoduleCommand.kt b/vid-app-common/src/main/java/org/onap/vid/job/command/VfmoduleCommand.kt index bee42fbd4..731625c53 100644 --- a/vid-app-common/src/main/java/org/onap/vid/job/command/VfmoduleCommand.kt +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/VfmoduleCommand.kt @@ -90,7 +90,7 @@ class VfmoduleCommand @Autowired constructor( val originalRequestWithNewestVfmModelInfo = getRequest().cloneWith(vfmModelInfo) - val requestDetailsWrapper = msoRequestBuilder.generateVfModuleInstantiationRequest( + val requestDetailsWrapper = msoRequestBuilder.generateVfModuleReplaceRequest( originalRequestWithNewestVfmModelInfo, serviceModelInfo, serviceInstanceId, vnfModelInfo, vnfInstanceId, null, sharedData.userId, sharedData.testApi) @@ -193,7 +193,7 @@ class VfmoduleCommand @Autowired constructor( val replaceMyselfCommand = planReplaceMyselfRestCall(commandParentData) return executeAndHandleMsoInstanceRequest(replaceMyselfCommand) } catch (exception: Exception) { - LOGGER.error("Failed to replace instanceId ${getRequest().instanceId} ", exception) + LOGGER.error(EELFLoggerDelegate.errorLogger, "Failed to replace instanceId ${getRequest().instanceId} ", exception) return Job.JobStatus.FAILED } } diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/VnfCommand.kt b/vid-app-common/src/main/java/org/onap/vid/job/command/VnfCommand.kt index 6f00f9ae6..48ff7b7ac 100644 --- a/vid-app-common/src/main/java/org/onap/vid/job/command/VnfCommand.kt +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/VnfCommand.kt @@ -61,7 +61,7 @@ class VnfCommand @Autowired constructor( try { childJobs = pushChildrenJobsToBroker(vfModules.filter { filterModuleByNeedToCreateBase(it) }, dataForChild, JobType.VolumeGroupInstantiation) } catch (e: AsdcCatalogException) { - LOGGER.error("Failed to retrieve service definitions from SDC, for VfModule is BaseModule.. Error: " + e.message , e) + LOGGER.error(EELFLoggerDelegate.errorLogger, "Failed to retrieve service definitions from SDC, for VfModule is BaseModule.. Error: " + e.message , e) //return Job.JobStatus.FAILED throw e; } diff --git a/vid-app-common/src/main/java/org/onap/vid/job/impl/DeleteOldJobsSchedulerInitializer.java b/vid-app-common/src/main/java/org/onap/vid/job/impl/DeleteOldJobsSchedulerInitializer.java index ad4b8c95a..114c20105 100644 --- a/vid-app-common/src/main/java/org/onap/vid/job/impl/DeleteOldJobsSchedulerInitializer.java +++ b/vid-app-common/src/main/java/org/onap/vid/job/impl/DeleteOldJobsSchedulerInitializer.java @@ -85,7 +85,7 @@ public class DeleteOldJobsSchedulerInitializer { Trigger createTrigger() { int minutes = new Random(System.nanoTime()).nextInt(59); int hours = 6; - logger.info("trigger for DeleteOldJobs is {}:{} ", hours, minutes); + logger.info(EELFLoggerDelegate.debugLogger, "trigger for DeleteOldJobs is {}:{} ", hours, minutes); return TriggerBuilder.newTrigger() .withIdentity("DeleteOldJobsTrigger") diff --git a/vid-app-common/src/main/java/org/onap/vid/job/impl/DeleteOldJobsWorker.java b/vid-app-common/src/main/java/org/onap/vid/job/impl/DeleteOldJobsWorker.java index d60ddab8d..ba0a9981e 100644 --- a/vid-app-common/src/main/java/org/onap/vid/job/impl/DeleteOldJobsWorker.java +++ b/vid-app-common/src/main/java/org/onap/vid/job/impl/DeleteOldJobsWorker.java @@ -34,7 +34,7 @@ public class DeleteOldJobsWorker extends QuartzJobBean { @Override protected void executeInternal(JobExecutionContext context) { - LOGGER.info("delete old final jobs that has finished before {} seconds", secondsAgo); + LOGGER.info(EELFLoggerDelegate.debugLogger, "delete old final jobs that has finished before {} seconds", secondsAgo); jobsBrokerService.deleteOldFinalJobs(secondsAgo); } diff --git a/vid-app-common/src/main/java/org/onap/vid/job/impl/JobWorker.java b/vid-app-common/src/main/java/org/onap/vid/job/impl/JobWorker.java index 0b277b4d2..c629a665c 100644 --- a/vid-app-common/src/main/java/org/onap/vid/job/impl/JobWorker.java +++ b/vid-app-common/src/main/java/org/onap/vid/job/impl/JobWorker.java @@ -20,23 +20,28 @@ package org.onap.vid.job.impl; +import static org.onap.vid.job.Job.JobStatus.FAILED; +import static org.onap.vid.job.Job.JobStatus.STOPPED; +import static org.onap.vid.job.command.ResourceCommandKt.ACTION_PHASE; +import static org.onap.vid.job.command.ResourceCommandKt.INTERNAL_STATE; + +import java.util.Optional; +import java.util.UUID; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; +import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.vid.job.*; +import org.onap.vid.job.Job; +import org.onap.vid.job.JobCommand; +import org.onap.vid.job.JobException; +import org.onap.vid.job.JobsBrokerService; +import org.onap.vid.job.NextCommand; import org.onap.vid.job.command.JobCommandFactory; import org.quartz.JobExecutionContext; +import org.slf4j.MDC; import org.springframework.scheduling.quartz.QuartzJobBean; import org.springframework.stereotype.Component; -import java.util.Optional; -import java.util.UUID; - -import static org.onap.vid.job.Job.JobStatus.FAILED; -import static org.onap.vid.job.Job.JobStatus.STOPPED; -import static org.onap.vid.job.command.ResourceCommandKt.ACTION_PHASE; -import static org.onap.vid.job.command.ResourceCommandKt.INTERNAL_STATE; - @Component public class JobWorker extends QuartzJobBean { @@ -80,6 +85,8 @@ public class JobWorker extends QuartzJobBean { } protected Job executeJobAndGetNext(Job job) { + setThreadWithRandomRequestId(); + Object internalState = job.getData().get(INTERNAL_STATE); Object actionPhase = job.getData().get(ACTION_PHASE); LOGGER.debug(EELFLoggerDelegate.debugLogger, "going to execute job {} of {}: {}/{} {}/{}", @@ -96,13 +103,18 @@ public class JobWorker extends QuartzJobBean { return setNextCommandInJob(nextCommand, job); } + private void setThreadWithRandomRequestId() { + //make sure requestIds in outgoing requests are not reused + MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, UUID.randomUUID().toString()); + } + private NextCommand executeCommandAndGetNext(Job job) { NextCommand nextCommand; try { final JobCommand jobCommand = jobCommandFactory.toCommand(job); nextCommand = jobCommand.call(); } catch (Exception e) { - LOGGER.error("error while executing job from queue: {}", e); + LOGGER.error(EELFLoggerDelegate.errorLogger, "error while executing job from queue: {}", e); nextCommand = new NextCommand(FAILED); } diff --git a/vid-app-common/src/main/java/org/onap/vid/job/impl/JobsBrokerServiceInDatabaseImpl.java b/vid-app-common/src/main/java/org/onap/vid/job/impl/JobsBrokerServiceInDatabaseImpl.java index 74a729494..51803891a 100644 --- a/vid-app-common/src/main/java/org/onap/vid/job/impl/JobsBrokerServiceInDatabaseImpl.java +++ b/vid-app-common/src/main/java/org/onap/vid/job/impl/JobsBrokerServiceInDatabaseImpl.java @@ -20,6 +20,21 @@ package org.onap.vid.job.impl; +import static org.onap.vid.job.Job.JobStatus.CREATING; +import static org.onap.vid.job.Job.JobStatus.FINAL_STATUS; +import static org.onap.vid.job.Job.JobStatus.IN_PROGRESS; +import static org.onap.vid.job.Job.JobStatus.PENDING_RESOURCE; +import static org.onap.vid.job.Job.JobStatus.RESOURCE_IN_PROGRESS; + +import java.sql.Timestamp; +import java.time.LocalDateTime; +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.stream.Collectors; +import javax.annotation.PostConstruct; import org.apache.commons.lang3.StringUtils; import org.hibernate.SessionFactory; import org.jetbrains.annotations.NotNull; @@ -37,14 +52,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; -import javax.annotation.PostConstruct; -import java.sql.Timestamp; -import java.time.LocalDateTime; -import java.util.*; -import java.util.stream.Collectors; - -import static org.onap.vid.job.Job.JobStatus.*; - @Service public class JobsBrokerServiceInDatabaseImpl implements JobsBrokerService { @@ -252,7 +259,10 @@ public class JobsBrokerServiceInDatabaseImpl implements JobsBrokerService { Integer age = jobDao.getAge(); jobDao.setAge(age + 1); - logger.debug(EELFLoggerDelegate.debugLogger, "{}/{}", jobDao.getStatus(), jobDao.getType()); + logger.debug(EELFLoggerDelegate.debugLogger, "pushing back jobDao {} of {}: {}/{}", + StringUtils.substring(String.valueOf(jobDao.getUuid()), 0, 8), + StringUtils.substring(String.valueOf(jobDao.getTemplateId()), 0, 8), + jobDao.getStatus(), jobDao.getType()); dataAccessService.saveDomainObject(jobDao, DaoUtils.getPropsMap()); } diff --git a/vid-app-common/src/main/java/org/onap/vid/logging/VidLoggingInterceptor.java b/vid-app-common/src/main/java/org/onap/vid/logging/VidLoggingInterceptor.java index abc7048da..fe8b470ec 100644 --- a/vid-app-common/src/main/java/org/onap/vid/logging/VidLoggingInterceptor.java +++ b/vid-app-common/src/main/java/org/onap/vid/logging/VidLoggingInterceptor.java @@ -24,8 +24,12 @@ import java.net.InetAddress; import java.net.UnknownHostException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.apache.commons.lang3.StringUtils; +import org.onap.logging.filter.base.MDCSetup; +import org.onap.logging.filter.base.SimpleMap; import org.onap.logging.filter.spring.LoggingInterceptor; import org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs; +import org.onap.vid.controller.ControllersUtils; import org.slf4j.MDC; import org.springframework.web.servlet.ModelAndView; @@ -34,6 +38,11 @@ public class VidLoggingInterceptor extends LoggingInterceptor { static final String INBOUND_INVO_ID = "InboundInvoId"; private static final String canonicalHostName = getCanonicalName(); + private final ControllersUtils controllersUtils; + + public VidLoggingInterceptor(ControllersUtils controllersUtils) { + this.controllersUtils = controllersUtils; + } private static String getCanonicalName() { try { @@ -45,9 +54,30 @@ public class VidLoggingInterceptor extends LoggingInterceptor { } @Override - protected void additionalPreHandling(HttpServletRequest request) { + protected void additionalPreHandling(HttpServletRequest request) { super.additionalPreHandling(request); storeInboundInvocationId(); + fillPartnerNameWithUserId(request); + } + + void fillPartnerNameWithUserId(HttpServletRequest request) { + String userId = controllersUtils.extractUserId(request); + if (StringUtils.isNotEmpty(userId)) { + MDC.put(MDCs.PARTNER_NAME, userId); + } + } + + @Override + //this method override fix bug in logging library + //that may throw some exceptions, e.g. StringIndexOutOfBoundsException + protected String getBasicAuthUserName(SimpleMap headers) { + try { + return super.getBasicAuthUserName(headers); + } catch (Exception e) { + MDCSetup.logger.error("failed to getBasicAuthUserName", e); + } + + return null; } /* @@ -61,6 +91,7 @@ public class VidLoggingInterceptor extends LoggingInterceptor { public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { restoreInvocationId(); fixServerFQDN(); + fillPartnerNameWithUserId(request); super.postHandle(request, response, handler, modelAndView); } diff --git a/vid-app-common/src/main/java/org/onap/vid/model/ModelUtil.java b/vid-app-common/src/main/java/org/onap/vid/model/ModelUtil.java index 45e100fb1..6c56a464b 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/ModelUtil.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/ModelUtil.java @@ -20,39 +20,26 @@ package org.onap.vid.model; +import static java.util.function.Function.identity; +import static java.util.stream.Collectors.counting; +import static java.util.stream.Collectors.groupingBy; + +import java.util.Map; +import java.util.Objects; +import java.util.function.Function; +import org.apache.commons.lang3.StringUtils; +import org.onap.vid.mso.model.ModelInfo; +import org.springframework.stereotype.Component; + +@Component public class ModelUtil { - /** - * Gets the tags for the given element according to the configured namespace - * @param namespaces the namespace list from the configuration - * @param constantValue the constant portion of the tag name, i.e. resource.vf... - * @return the tags - */ - public static String[] getTags ( String[] namespaces, String constantValue ) { - String[] tags; - if ( namespaces == null || namespaces.length == 0 ) { - return null; - } - int le = namespaces.length; - tags = new String[le]; - for ( int i = 0; i < le; i++ ) { - tags[i] = namespaces[i] + constantValue; - } - return (tags); - } - /** - * Determine if a note template type matches a set of configurable tags - * @param type the node template type - * @param tags the model configurable namespaces - * @return true if type starts with a tag in the array, false otherwise - */ - public static boolean isType ( String type, String[] tags ) { - if ( (tags != null) && (tags.length > 0) ) { - for ( int i = 0; i < tags.length; i++ ) { - if ( type.startsWith (tags[i]) ) { - return (true); - } - } - } - return (false); + public <T> Map<String, Long> getExistingCounterMap(Map<String, T> nodeList, Function<T, ModelInfo> modelInfoExtractor) { + return nodeList.values().stream() + .map(it -> { + ModelInfo modelInfo = modelInfoExtractor.apply(it); + return StringUtils.defaultIfEmpty(modelInfo.getModelCustomizationId(), modelInfo.getModelVersionId()); + }) + .filter(Objects::nonNull) + .collect(groupingBy(identity(), counting())); } } diff --git a/vid-app-common/src/main/java/org/onap/vid/model/VidNotions.kt b/vid-app-common/src/main/java/org/onap/vid/model/VidNotions.kt index f67d8fbd9..c6de51c1a 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/VidNotions.kt +++ b/vid-app-common/src/main/java/org/onap/vid/model/VidNotions.kt @@ -25,7 +25,7 @@ import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.annotation.JsonValue import com.google.common.base.CaseFormat -class VidNotions(@get:JsonInclude(JsonInclude.Include.NON_NULL) +data class VidNotions(@get:JsonInclude(JsonInclude.Include.NON_NULL) val instantiationUI: InstantiationUI, val modelCategory: ModelCategory, val viewEditUI: InstantiationUI, @@ -41,7 +41,8 @@ class VidNotions(@get:JsonInclude(JsonInclude.Include.NON_NULL) TRANSPORT_SERVICE, SERVICE_WITH_COLLECTION_RESOURCE, A_LA_CARTE_VNF_SERVICE_ROLE, - INFRASTRUCTURE_VPN + INFRASTRUCTURE_VPN, + ANY_ALACARTE_WHICH_NOT_EXCLUDED, ; @JsonValue @@ -59,6 +60,8 @@ class VidNotions(@get:JsonInclude(JsonInclude.Include.NON_NULL) Transport, SERVICE_WITH_COLLECTION_RESOURCE, INFRASTRUCTURE_VPN, + PORT_MIRRORING, + VLAN_TAGGING, @JsonProperty("other") OTHER } diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/model/AaiGetOperationalEnvironments/OperationalEnvironmentListTest.java b/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/ExistingElementsCounterMaps.java index fb79634a5..de63c2c94 100644 --- a/vid-app-common/src/test/java/org/onap/vid/aai/model/AaiGetOperationalEnvironments/OperationalEnvironmentListTest.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/ExistingElementsCounterMaps.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,17 +18,17 @@ * ============LICENSE_END========================================================= */ -package org.onap.vid.aai.model.AaiGetOperationalEnvironments; +package org.onap.vid.model.aaiTree; -import static com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSetters; -import static org.hamcrest.MatcherAssert.assertThat; -import org.junit.Test; +import java.util.Map; -public class OperationalEnvironmentListTest { +public interface ExistingElementsCounterMaps { - @Test - public void shouldHaveValidGettersAndSetters(){ - assertThat(OperationalEnvironmentList.class, hasValidGettersAndSetters()); - } + Map<String, Long> getExistingVNFCounterMap(); + Map<String, Long> getExistingNetworksCounterMap(); + + Map<String, Long> getExistingVnfGroupCounterMap(); + + Map<String, Long> getExistingVRFCounterMap(); } diff --git a/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/ServiceInstance.java b/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/ServiceInstance.java index 923be132f..78afe1d45 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/ServiceInstance.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/ServiceInstance.java @@ -24,7 +24,7 @@ import java.util.HashMap; import java.util.Map; import org.onap.vid.mso.model.ModelInfo; -public class ServiceInstance extends AbstractNode { +public class ServiceInstance extends AbstractNode implements ExistingElementsCounterMaps { private String globalSubscriberId; private String subscriptionServiceType; @@ -198,6 +198,7 @@ public class ServiceInstance extends AbstractNode { this.validationCounter = validationCounter; } + @Override public Map<String, Long> getExistingVNFCounterMap() { return existingVNFCounterMap; } @@ -206,6 +207,7 @@ public class ServiceInstance extends AbstractNode { this.existingVNFCounterMap = existingVNFCounterMap; } + @Override public Map<String, Long> getExistingNetworksCounterMap() { return existingNetworksCounterMap; } @@ -214,6 +216,7 @@ public class ServiceInstance extends AbstractNode { this.existingNetworksCounterMap = existingNetworksCounterMap; } + @Override public Map<String, Long> getExistingVnfGroupCounterMap() { return existingVnfGroupCounterMap; } @@ -230,6 +233,7 @@ public class ServiceInstance extends AbstractNode { this.vrfs = vrfs; } + @Override public Map<String, Long> getExistingVRFCounterMap() { return existingVRFCounterMap; } diff --git a/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/ServiceInstantiation.java b/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/ServiceInstantiation.java index 8828faf1d..e7e5783c4 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/ServiceInstantiation.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/ServiceInstantiation.java @@ -21,18 +21,19 @@ package org.onap.vid.model.serviceInstantiation; import com.fasterxml.jackson.annotation.JsonProperty; -import org.apache.commons.lang3.ObjectUtils; -import org.onap.vid.job.JobAdapter; -import org.onap.vid.job.JobType; -import org.onap.vid.model.VidNotions; -import org.onap.vid.mso.model.ModelInfo; - +import com.fasterxml.jackson.databind.annotation.JsonSerialize; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; +import org.apache.commons.lang3.ObjectUtils; +import org.onap.vid.job.JobAdapter; +import org.onap.vid.job.JobType; +import org.onap.vid.model.VidNotions; +import org.onap.vid.mso.model.ModelInfo; +import org.onap.vid.utils.jackson.BooleanAsStringSerializer; public class ServiceInstantiation extends BaseResource implements JobAdapter.AsyncJobRequest { @@ -127,6 +128,13 @@ public class ServiceInstantiation extends BaseResource implements JobAdapter.Asy this.vidNotions = vidNotions; } + @Override + @JsonSerialize(using=BooleanAsStringSerializer.class) + public boolean isRollbackOnFailure() { + // this override is for the BooleanAsStringSerializer annotation, + // but for Service-Instance level only + return super.isRollbackOnFailure(); + } public String getOwningEntityId() { return owningEntityId; diff --git a/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/ServiceInstantiationTemplate.java b/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/ServiceInstantiationTemplate.java new file mode 100644 index 000000000..17ce1bcc3 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/ServiceInstantiationTemplate.java @@ -0,0 +1,81 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 - 2019 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.onap.vid.model.serviceInstantiation; + +import java.util.Map; +import java.util.Objects; +import org.onap.vid.model.aaiTree.ExistingElementsCounterMaps; + +public class ServiceInstantiationTemplate extends ServiceInstantiation implements ExistingElementsCounterMaps { + + private final Map<String, Long> existingVNFCounterMap; + private final Map<String, Long> existingNetworksCounterMap; + private final Map<String, Long> existingVnfGroupCounterMap; + private final Map<String, Long> existingVRFCounterMap; + + public ServiceInstantiationTemplate( + ServiceInstantiation baseService, + Map<String, Long> vnfCounterMap, + Map<String, Long> networksCounterMap, + Map<String, Long> vnfGroupCounterMap, + Map<String, Long> VRFCounterMap + ) { + super( + baseService.getModelInfo(), baseService.getOwningEntityId(), baseService.getOwningEntityName(), + baseService.getProjectName(), baseService.getGlobalSubscriberId(), baseService.getSubscriberName(), + baseService.getProductFamilyId(), baseService.getInstanceName(), baseService.getSubscriptionServiceType(), + baseService.getLcpCloudRegionId(), baseService.getLcpCloudRegionId(), baseService.getTenantId(), + baseService.getTenantName(), baseService.getAicZoneId(), baseService.getAicZoneName(), + baseService.getVnfs(), baseService.getNetworks(), baseService.getVnfGroups(), baseService.getVrfs(), + baseService.getInstanceParams(), baseService.isPause(), baseService.getBulkSize(), + baseService.isRollbackOnFailure(), baseService.isALaCarte(), baseService.getTestApi(), + baseService.getInstanceId(), Objects.toString(baseService.getAction(), null), + baseService.getTrackById(), baseService.getIsFailed(), baseService.getStatusMessage(), + baseService.getVidNotions() + ); + + this.existingVNFCounterMap = vnfCounterMap; + this.existingNetworksCounterMap = networksCounterMap; + this.existingVnfGroupCounterMap = vnfGroupCounterMap; + this.existingVRFCounterMap = VRFCounterMap; + } + + @Override + public Map<String, Long> getExistingVNFCounterMap() { + return existingVNFCounterMap; + } + + @Override + public Map<String, Long> getExistingNetworksCounterMap() { + return existingNetworksCounterMap; + } + + @Override + public Map<String, Long> getExistingVnfGroupCounterMap() { + return existingVnfGroupCounterMap; + } + + @Override + public Map<String, Long> getExistingVRFCounterMap() { + return existingVRFCounterMap; + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/VfModule.java b/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/VfModule.java index 41da85e35..ad5b39e28 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/VfModule.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/VfModule.java @@ -28,6 +28,7 @@ import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; +import javax.annotation.Nullable; import org.onap.vid.job.JobAdapter; import org.onap.vid.job.JobType; import org.onap.vid.mso.model.ModelInfo; @@ -42,6 +43,12 @@ public class VfModule extends BaseResource implements JobAdapter.AsyncJobRequest @JsonInclude(NON_NULL) private Boolean usePreload; private Map<String, String> supplementaryParams; + @JsonInclude(NON_NULL) + private final Boolean retainVolumeGroups; + + @JsonInclude(NON_NULL) + private Boolean retainAssignments; + public VfModule(@JsonProperty("modelInfo") ModelInfo modelInfo, @JsonProperty("instanceName") String instanceName, @JsonProperty("volumeGroupName") String volumeGroupInstanceName, @@ -57,12 +64,16 @@ public class VfModule extends BaseResource implements JobAdapter.AsyncJobRequest @JsonProperty("trackById") String trackById, @JsonProperty("isFailed") Boolean isFailed, @JsonProperty("statusMessage") String statusMessage, + @Nullable @JsonProperty("retainAssignments") Boolean retainAssignments, + @Nullable @JsonProperty("retainVolumeGroups") Boolean retainVolumeGroups, @JsonProperty("position") Integer position) { super(modelInfo, instanceName, action, lcpCloudRegionId, legacyRegion, tenantId, instanceParams, rollbackOnFailure, instanceId, trackById, isFailed, statusMessage, position); this.volumeGroupInstanceName = volumeGroupInstanceName; this.usePreload = usePreload; this.supplementaryParams = supplementaryParams; + this.retainAssignments = retainAssignments; + this.retainVolumeGroups = retainVolumeGroups; } public String getVolumeGroupInstanceName() { @@ -93,6 +104,16 @@ public class VfModule extends BaseResource implements JobAdapter.AsyncJobRequest return JobType.VfmoduleInstantiation; } + @Nullable + public Boolean isRetainAssignments() { + return retainAssignments; + } + + @Nullable + public Boolean isRetainVolumeGroups() { + return retainVolumeGroups; + } + public VfModule cloneWith(ModelInfo modelInfo) { return new VfModule( modelInfo, @@ -110,6 +131,8 @@ public class VfModule extends BaseResource implements JobAdapter.AsyncJobRequest this.getTrackById(), this.getIsFailed(), this.getStatusMessage(), + this.isRetainAssignments(), + this.isRetainVolumeGroups(), this.getPosition()); } }
\ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/model/VfModuleInstantiationRequestDetails.java b/vid-app-common/src/main/java/org/onap/vid/mso/model/VfModuleOrVolumeGroupRequestDetails.kt index 3b6cd1d3d..bba4081dd 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/model/VfModuleInstantiationRequestDetails.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/model/VfModuleOrVolumeGroupRequestDetails.kt @@ -17,16 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ +package org.onap.vid.mso.model -package org.onap.vid.mso.model; - -import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import com.fasterxml.jackson.annotation.JsonInclude +import com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL +import java.util.* /* Based on this model: @@ -98,36 +93,33 @@ import java.util.Map; */ -public class VfModuleInstantiationRequestDetails extends BaseResourceInstantiationRequestDetails { - - public VfModuleInstantiationRequestDetails( - @JsonProperty(value = "modelInfo", required = true) ModelInfo modelInfo, - @JsonProperty(value = "cloudConfiguration", required = true) CloudConfiguration cloudConfiguration, - @JsonProperty(value = "requestInfo", required = true) RequestInfo requestInfo, - @JsonProperty(value = "relatedInstanceList", required = true) List<RelatedInstance> relatedInstanceList, - @JsonProperty(value = "requestParameters", required = true) RequestParametersVfModule requestParameters) - { - super(modelInfo, cloudConfiguration, requestInfo, relatedInstanceList, requestParameters); - } +data class VfModuleOrVolumeGroupRequestDetails( + val modelInfo: ModelInfo, + val cloudConfiguration: CloudConfiguration, + val requestInfo: RequestInfo, + val relatedInstanceList: List<RelatedInstance>?, + val requestParameters: RequestParametersVfModuleOrVolumeGroup?) + : BaseResourceInstantiationRequestDetails(modelInfo, cloudConfiguration, requestInfo, relatedInstanceList, requestParameters) - public static class RequestParametersVfModule extends BaseResourceInstantiationRequestDetails.RequestParameters { - @JsonInclude(NON_NULL) private final Boolean usePreload; +open class RequestParametersVfModuleOrVolumeGroup internal constructor( + userParams: List<UserParamTypes>, + @get:JsonInclude(NON_NULL) val isUsePreload: Boolean?, + testApi: String? +) : BaseResourceInstantiationRequestDetails.RequestParameters(userParams, testApi) - public RequestParametersVfModule(List<? extends UserParamTypes> userParams, Boolean usePreload, String testApi) { - super(userParams, testApi); - this.usePreload = usePreload; - } +class RequestParametersVfModuleOrVolumeGroupInstantiation( + userParams: List<UserParamTypes>, + usePreload: Boolean?, + testApi: String? +) : RequestParametersVfModuleOrVolumeGroup(userParams, usePreload, testApi) - public Boolean isUsePreload() { - return usePreload; - } - } +class RequestParametersVfModuleUpgrade( + userParams: List<UserParamTypes>, + usePreload: Boolean?, + testApi: String?, + @get:JsonInclude(NON_NULL) val retainAssignments: Boolean?, + @get:JsonInclude(NON_NULL) val rebuildVolumeGroups: Boolean? +) : RequestParametersVfModuleOrVolumeGroup(userParams, usePreload, testApi) - public static class UserParamMap<K,V> extends HashMap<K,V> implements UserParamTypes, Map<K,V> { - - public UserParamMap() { - super(); - } - } -} +class UserParamMap<K, V> : HashMap<K, V>(), UserParamTypes, MutableMap<K, V> diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/model/VolumeGroupRequestDetails.java b/vid-app-common/src/main/java/org/onap/vid/mso/model/VolumeGroupRequestDetails.java index e1a5e56dd..a637f85dc 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/model/VolumeGroupRequestDetails.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/model/VolumeGroupRequestDetails.java @@ -21,7 +21,6 @@ package org.onap.vid.mso.model; import com.fasterxml.jackson.annotation.JsonProperty; - import java.util.List; public class VolumeGroupRequestDetails extends BaseResourceInstantiationRequestDetails { @@ -31,7 +30,7 @@ public class VolumeGroupRequestDetails extends BaseResourceInstantiationRequestD @JsonProperty(value = "cloudConfiguration", required = true) CloudConfiguration cloudConfiguration, @JsonProperty(value = "requestInfo", required = true) RequestInfo requestInfo, @JsonProperty(value = "relatedInstanceList", required = true) List<RelatedInstance> relatedInstanceList, - @JsonProperty(value = "requestParameters", required = true) VfModuleInstantiationRequestDetails.RequestParametersVfModule requestParameters) + @JsonProperty(value = "requestParameters", required = true) RequestParametersVfModuleOrVolumeGroup requestParameters) { super(modelInfo, cloudConfiguration, requestInfo, relatedInstanceList, requestParameters); } diff --git a/vid-app-common/src/main/java/org/onap/vid/properties/Features.java b/vid-app-common/src/main/java/org/onap/vid/properties/Features.java index abee30025..990ec60c9 100644 --- a/vid-app-common/src/main/java/org/onap/vid/properties/Features.java +++ b/vid-app-common/src/main/java/org/onap/vid/properties/Features.java @@ -29,8 +29,6 @@ public enum Features implements Feature { * Use /docs/feature-flags.md for details */ - CREATE_INSTANCE_TEST, - EMPTY_DRAWING_BOARD_TEST, FLAG_ADD_MSO_TESTAPI_FIELD, FLAG_SERVICE_MODEL_CACHE, FLAG_NETWORK_TO_ASYNC_INSTANTIATION, @@ -38,8 +36,6 @@ public enum Features implements Feature { FLAG_UNASSIGN_SERVICE, FLAG_FABRIC_CONFIGURATION_ASSIGNMENTS, FLAG_SHOW_VERIFY_SERVICE, // AKA POMBA - FLAG_DEFAULT_VNF, - FLAG_SETTING_DEFAULTS_IN_DRAWING_BOARD, FLAG_RESTRICTED_SELECT, FLAG_5G_IN_NEW_INSTANTIATION_UI, FLAG_ASYNC_ALACARTE_VNF, @@ -51,7 +47,6 @@ public enum Features implements Feature { FLAG_ENABLE_WEBPACK_MODERN_UI, FLAG_1810_CR_LET_SELECTING_COLLECTOR_TYPE_UNCONDITIONALLY, FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST, - FLAG_1810_CR_SOFT_DELETE_ALACARTE_VF_MODULE, FLAG_1810_AAI_LOCAL_CACHE, FLAG_1810_IDENTIFY_SERVICE_FOR_NEW_UI, FLAG_1902_NEW_VIEW_EDIT, @@ -80,7 +75,14 @@ public enum Features implements Feature { FLAG_FLASH_MORE_ACTIONS_BUTTON_IN_OLD_VIEW_EDIT, FLAG_FLASH_CLOUD_REGION_AND_NF_ROLE_OPTIONAL_SEARCH, FLAG_1911_INSTANTIATION_ORDER_IN_ASYNC_ALACARTE, - FLAG_1911_INSTANTIATION_ORDER_BUTTON_IN_ASYNC_ALACARTE + FLAG_2002_ANY_ALACARTE_BESIDES_EXCLUDED_NEW_INSTANTIATION_UI, + FLAG_2002_VNF_PLATFORM_MULTI_SELECT, + FLAG_2002_VFM_UPGRADE_ADDITIONAL_OPTIONS, + FLAG_2002_IDENTIFY_INVARIANT_MACRO_UUID_BY_BACKEND, + FLAG_2004_INSTANTIATION_STATUS_FILTER, + FLAG_2004_CREATE_ANOTHER_INSTANCE_FROM_TEMPLATE, + FLAG_2004_TEMP_BUTTON_TO_INSTANTIATION_STATUS_FILTER, + FLAG_2002_UNLIMITED_MAX, ; diff --git a/vid-app-common/src/main/java/org/onap/vid/services/AAIServiceTree.java b/vid-app-common/src/main/java/org/onap/vid/services/AAIServiceTree.java index d62d5d5d4..7b0e5f56f 100644 --- a/vid-app-common/src/main/java/org/onap/vid/services/AAIServiceTree.java +++ b/vid-app-common/src/main/java/org/onap/vid/services/AAIServiceTree.java @@ -20,8 +20,25 @@ package org.onap.vid.services; +import static java.util.Comparator.comparing; +import static java.util.stream.Collectors.toSet; +import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; +import static org.onap.vid.utils.KotlinUtilsKt.JACKSON_OBJECT_MAPPER; + import com.fasterxml.jackson.databind.JsonNode; import com.google.common.collect.ImmutableList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.ConcurrentSkipListSet; +import java.util.concurrent.ExecutorService; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import javax.inject.Inject; +import javax.ws.rs.core.Response; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.vid.aai.AaiClientInterface; import org.onap.vid.aai.util.AAITreeConverter; @@ -36,19 +53,6 @@ import org.onap.vid.utils.Tree; import org.springframework.http.HttpMethod; import org.springframework.stereotype.Component; -import javax.inject.Inject; -import javax.ws.rs.core.Response; -import java.util.*; -import java.util.concurrent.ConcurrentSkipListSet; -import java.util.concurrent.ExecutorService; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import static java.util.Comparator.comparing; -import static java.util.stream.Collectors.toSet; -import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; -import static org.onap.vid.utils.KotlinUtilsKt.JACKSON_OBJECT_MAPPER; - @Component public class AAIServiceTree { @@ -207,12 +211,14 @@ public class AAIServiceTree { Map<String, String> modelNameByModelVersionId = new HashMap<>(); JsonNode models = getModels(aaiClient, invariantIDs); - for (JsonNode model: models) { - JsonNode modelVersions = model.get("model-vers").get("model-ver"); - for (JsonNode modelVersion: modelVersions) { - final String modelVersionId = modelVersion.get("model-version-id").asText(); - modelVersionByModelVersionId.put(modelVersionId, modelVersion.get("model-version").asText()); - modelNameByModelVersionId.put(modelVersionId, modelVersion.get("model-name").asText()); + if (models!=null) { + for (JsonNode model : models) { + JsonNode modelVersions = model.get("model-vers").get("model-ver"); + for (JsonNode modelVersion : modelVersions) { + final String modelVersionId = modelVersion.get("model-version-id").asText(); + modelVersionByModelVersionId.put(modelVersionId, modelVersion.get("model-version").asText()); + modelNameByModelVersionId.put(modelVersionId, modelVersion.get("model-name").asText()); + } } } diff --git a/vid-app-common/src/main/java/org/onap/vid/services/AAITreeNodeBuilder.java b/vid-app-common/src/main/java/org/onap/vid/services/AAITreeNodeBuilder.java index c8434609e..209f37025 100644 --- a/vid-app-common/src/main/java/org/onap/vid/services/AAITreeNodeBuilder.java +++ b/vid-app-common/src/main/java/org/onap/vid/services/AAITreeNodeBuilder.java @@ -59,6 +59,7 @@ import org.onap.vid.model.aaiTree.FailureAAITreeNode; import org.onap.vid.model.aaiTree.NodeType; import org.onap.vid.mso.model.CloudConfiguration; import org.onap.vid.properties.VidProperties; +import org.onap.vid.utils.Logging; import org.onap.vid.utils.Streams; import org.onap.vid.utils.Tree; import org.onap.vid.utils.Unchecked; @@ -71,7 +72,8 @@ import org.springframework.stereotype.Component; public class AAITreeNodeBuilder { private static final String RESULTS = "results"; - private AaiClientInterface aaiClient; + private final AaiClientInterface aaiClient; + private final Logging logging; private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(AAITreeNodeBuilder.class); @@ -97,8 +99,9 @@ public class AAITreeNodeBuilder { } @Inject - public AAITreeNodeBuilder(AaiClientInterface aaiClient) { + public AAITreeNodeBuilder(AaiClientInterface aaiClient, Logging logging) { this.aaiClient = aaiClient; + this.logging = logging; } List<AAITreeNode> buildNode(NodeType nodeType, @@ -296,13 +299,7 @@ public class AAITreeNodeBuilder { } private <V> Callable<V> withCopyOfMDC(Callable<V> callable) { - //in order to be able to write the correct data while creating the node on a new thread - // save a copy of the current thread's context map, with keys and values of type String. - final Map<String, String> copyOfParentMDC = MDC.getCopyOfContextMap(); - return () -> { - MDC.setContextMap(copyOfParentMDC); - return callable.call(); - }; + return logging.withMDC(MDC.getCopyOfContextMap(), callable); } private List<AAITreeNode> getChildNode(ExecutorService threadPool, ConcurrentSkipListSet<AAITreeNode> nodesAccumulator, diff --git a/vid-app-common/src/main/java/org/onap/vid/services/AaiServiceImpl.java b/vid-app-common/src/main/java/org/onap/vid/services/AaiServiceImpl.java index b64a233c7..b3ac16884 100644 --- a/vid-app-common/src/main/java/org/onap/vid/services/AaiServiceImpl.java +++ b/vid-app-common/src/main/java/org/onap/vid/services/AaiServiceImpl.java @@ -87,7 +87,9 @@ import org.onap.vid.model.aaiTree.VpnBinding; import org.onap.vid.model.aaiTree.VpnBindingKt; import org.onap.vid.roles.RoleValidator; import org.onap.vid.utils.Intersection; +import org.onap.vid.utils.Logging; import org.onap.vid.utils.Tree; +import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpMethod; @@ -104,6 +106,7 @@ public class AaiServiceImpl implements AaiService { private AaiResponseTranslator aaiResponseTranslator; private AAIServiceTree aaiServiceTree; private ExecutorService executorService; + private final Logging logging; private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(AaiServiceImpl.class); @@ -113,12 +116,13 @@ public class AaiServiceImpl implements AaiService { AaiClientInterface aaiClient, AaiResponseTranslator aaiResponseTranslator, AAIServiceTree aaiServiceTree, - ExecutorService executorService) + ExecutorService executorService, Logging logging) { this.aaiClient = aaiClient; this.aaiResponseTranslator = aaiResponseTranslator; this.aaiServiceTree = aaiServiceTree; this.executorService = executorService; + this.logging = logging; } private List<Service> convertModelToService(Model model) { @@ -523,10 +527,12 @@ public class AaiServiceImpl implements AaiService { .map(RelatedVnf::from) .collect(Collectors.toList()); + final Map<String, String> copyOfParentMDC = MDC.getCopyOfContextMap(); + try { return executorService.submit(() -> convertedVnfs.parallelStream() - .map(this::enrichRelatedVnfWithCloudRegionAndTenant) + .map(logging.withMDC(copyOfParentMDC, this::enrichRelatedVnfWithCloudRegionAndTenant)) .collect(Collectors.toList()) ).get(); } catch (Exception e) { diff --git a/vid-app-common/src/main/java/org/onap/vid/services/AsyncInstantiationBusinessLogic.java b/vid-app-common/src/main/java/org/onap/vid/services/AsyncInstantiationBusinessLogic.java index 1202fc9e3..bb1121339 100644 --- a/vid-app-common/src/main/java/org/onap/vid/services/AsyncInstantiationBusinessLogic.java +++ b/vid-app-common/src/main/java/org/onap/vid/services/AsyncInstantiationBusinessLogic.java @@ -20,6 +20,10 @@ package org.onap.vid.services; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import java.util.function.Consumer; import org.onap.vid.aai.model.ResourceType; import org.onap.vid.job.Job; import org.onap.vid.job.impl.JobSharedData; @@ -28,11 +32,6 @@ import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; import org.onap.vid.mso.RestObject; import org.onap.vid.mso.rest.AsyncRequestStatus; -import java.util.Arrays; -import java.util.List; -import java.util.UUID; -import java.util.function.Consumer; - public interface AsyncInstantiationBusinessLogic { List<String> PARAMS_TO_IGNORE = Arrays.asList("vnf_name", "vf_module_name"); diff --git a/vid-app-common/src/main/java/org/onap/vid/services/InstantiationTemplatesService.java b/vid-app-common/src/main/java/org/onap/vid/services/InstantiationTemplatesService.java new file mode 100644 index 000000000..aa0031104 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/services/InstantiationTemplatesService.java @@ -0,0 +1,67 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 - 2019 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.onap.vid.services; + +import static java.util.Collections.emptyMap; +import static java.util.Objects.requireNonNull; + +import java.util.Map; +import java.util.UUID; +import javax.inject.Inject; +import org.onap.vid.dal.AsyncInstantiationRepository; +import org.onap.vid.model.ModelUtil; +import org.onap.vid.model.serviceInstantiation.BaseResource; +import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; +import org.onap.vid.model.serviceInstantiation.ServiceInstantiationTemplate; +import org.springframework.stereotype.Component; + +@Component +public class InstantiationTemplatesService { + + private final ModelUtil modelUtil; + private final AsyncInstantiationRepository asyncInstantiationRepository; + + @Inject + public InstantiationTemplatesService(ModelUtil modelUtil, + AsyncInstantiationRepository asyncInstantiationRepository) { + this.modelUtil = modelUtil; + this.asyncInstantiationRepository = asyncInstantiationRepository; + } + + public ServiceInstantiationTemplate getJobRequestAsTemplate(UUID jobId) { + ServiceInstantiation jobRequest = requireNonNull(asyncInstantiationRepository.getJobRequest(jobId)); + + return new ServiceInstantiationTemplate( + jobRequest, + counterMap(jobRequest.getVnfs()), + counterMap(jobRequest.getNetworks()), + counterMap(jobRequest.getVnfGroups()), + emptyMap() // model info for VRF is not stored + ); + } + + private <T extends BaseResource> Map<String, Long> counterMap(Map<String, T> nodesToCount) { + return modelUtil.getExistingCounterMap( + nodesToCount, BaseResource::getModelInfo + ); + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/utils/Logging.java b/vid-app-common/src/main/java/org/onap/vid/utils/Logging.java index 0d8e58878..43f059d54 100644 --- a/vid-app-common/src/main/java/org/onap/vid/utils/Logging.java +++ b/vid-app-common/src/main/java/org/onap/vid/utils/Logging.java @@ -33,8 +33,11 @@ import com.google.common.collect.ImmutableList; import io.joshworks.restclient.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.util.Arrays; +import java.util.Map; import java.util.Optional; import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.function.Function; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.Response; import org.apache.commons.io.IOUtils; @@ -42,6 +45,8 @@ import org.apache.commons.lang3.StringUtils; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.vid.utils.Unchecked.UncheckedThrowingSupplier; +import org.slf4j.MDC; import org.springframework.http.HttpMethod; import org.springframework.stereotype.Service; import org.springframework.web.context.request.RequestContextHolder; @@ -197,5 +202,29 @@ public class Logging { } } + /** + * in order to be able to write the correct data while creating the node on a new thread save a copy of the current + * thread's context map, with keys and values of type String. + */ + public <T> Callable<T> withMDC(Map<String, String> copyOfParentMDC, Callable<T> callable) { + return () -> withMDCInternal(copyOfParentMDC, callable::call); + } + + /** + * in order to be able to write the correct data while creating the node on a new thread save a copy of the current + * thread's context map, with keys and values of type String. + */ + public <T, U> Function<T, U> withMDC(Map<String, String> copyOfParentMDC, Function<T, U> function) { + return t -> withMDCInternal(copyOfParentMDC, () -> function.apply(t)); + } + + <T> T withMDCInternal(Map<String, String> copyOfParentMDC, UncheckedThrowingSupplier<T> supplier) { + try { + MDC.setContextMap(copyOfParentMDC); + return supplier.get(); + } finally { + MDC.clear(); + } + } } diff --git a/vid-app-common/src/main/java/org/onap/vid/utils/Unchecked.java b/vid-app-common/src/main/java/org/onap/vid/utils/Unchecked.java index 23127b61a..9fb15f690 100644 --- a/vid-app-common/src/main/java/org/onap/vid/utils/Unchecked.java +++ b/vid-app-common/src/main/java/org/onap/vid/utils/Unchecked.java @@ -20,10 +20,11 @@ package org.onap.vid.utils; -import org.onap.vid.exceptions.GenericUncheckedException; - import java.net.URI; import java.net.URISyntaxException; +import java.util.function.Supplier; +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.onap.vid.exceptions.GenericUncheckedException; public class Unchecked { private Unchecked() { @@ -39,5 +40,19 @@ public class Unchecked { } } + @FunctionalInterface + public interface UncheckedThrowingSupplier<T> extends Supplier<T> { + + @Override + default T get() { + try { + return getThrows(); + } catch (Exception e) { + return ExceptionUtils.rethrow(e); + } + } + + T getThrows() throws Exception; + } } diff --git a/vid-app-common/src/test/java/org/onap/vid/utils/LoggingTest.java b/vid-app-common/src/main/java/org/onap/vid/utils/jackson/BooleanAsStringSerializer.java index 87fe36372..a61044294 100644 --- a/vid-app-common/src/test/java/org/onap/vid/utils/LoggingTest.java +++ b/vid-app-common/src/main/java/org/onap/vid/utils/jackson/BooleanAsStringSerializer.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,37 +18,22 @@ * ============LICENSE_END========================================================= */ -package org.onap.vid.utils; +package org.onap.vid.utils.jackson; -import com.att.eelf.configuration.EELFLogger; -import org.junit.Test; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import java.io.IOException; -public class LoggingTest { +public class BooleanAsStringSerializer extends JsonSerializer<Boolean> { - @Test - public void testGetMethodName() throws Exception { - String result; - - // default test - result = Logging.getMethodName(); + /** + * Annotate a Jackson getter with <code>@JsonSerialize(using=BooleanAsStringSerializer.class)</code> + * to get a boolean value be serialized as quoted string. + */ + @Override + public void serialize(Boolean bool, JsonGenerator generator, SerializerProvider provider) throws IOException { + // bool is guaranteed not to be null + generator.writeString(bool.toString()); } - - @Test - public void testGetMethodCallerName() throws Exception { - String result; - - // default test - result = Logging.getMethodCallerName(); - } - - @Test - public void testGetRequestsLogger() throws Exception { - String serverName = ""; - EELFLogger result; - - // default test - result = Logging.getRequestsLogger(serverName); - } - - } diff --git a/vid-app-common/src/main/resources/catalog.json b/vid-app-common/src/main/resources/catalog.json deleted file mode 100644 index 20c7d5769..000000000 --- a/vid-app-common/src/main/resources/catalog.json +++ /dev/null @@ -1,174 +0,0 @@ -{ - "services": { - "0346aa9f-57b7-458a-9681-daf5b19d52b0": { - "uuid": "0346aa9f-57b7-458a-9681-daf5b19d52b0", - "name": "The Worst Service", - "version": "1.0", - "toscaModelURL": "sampleTosca.csar", - "category": "Bad Services", - "lifecycleState": "NOT_CERTIFIED_CHECKOUT", - "lastUpdaterUserId": "example@example.org", - "lastUpdaterFullName": "Example User", - "distributionStatus": "DISTRIBUTION_REJECTED", - "artifacts": [], - "resources": [] - }, - "1346aa9f-57b7-458a-9681-daf5b19d52b1": { - "uuid": "1346aa9f-57b7-458a-9681-daf5b19d52b1", - "name": "The Worst Service", - "version": "1.1", - "toscaModelURL": "sampleTosca.csar", - "category": "Bad Services", - "lifecycleState": "CERTIFIED", - "lastUpdaterUserId": "example@example.org", - "lastUpdaterFullName": "Example User", - "distributionStatus": "DISTRIBUTED", - "artifacts": [], - "resources": [] - }, - "3346aa9f-57b7-458a-9681-daf5b19d52b3": { - "uuid": "3346aa9f-57b7-458a-9681-daf5b19d52b3", - "name": "Bland Service", - "version": "1.9", - "toscaModelURL": "sampleTosca.csar", - "category": "Neutral Services", - "lifecycleState": "CERTIFIED", - "lastUpdaterUserId": "example@example.org", - "lastUpdaterFullName": "Example User", - "distributionStatus": "DISTRIBUTION_NOT_APPROVED", - "artifacts": [], - "resources": [] - }, - "2346aa9f-57b7-458a-9681-daf5b19d52b2": { - "uuid": "2346aa9f-57b7-458a-9681-daf5b19d52b2", - "name": "The Best Service", - "version": "1.3", - "toscaModelURL": "sampleTosca.csar", - "category": "Good Services", - "lifecycleState": "CERTIFIED", - "lastUpdaterUserId": "example@example.org", - "lastUpdaterFullName": "Example User", - "distributionStatus": "DISTRIBUTION_APPROVED", - "artifacts": [ - { - "artifactUUID": "0cf78c81-1246-45e7-a190-eaa309ee5680", - "generatedFromUUID": "3cf78c81-1246-45e7-a190-eaa309ee5680", - "artifactName": "The Worst Artifact", - "artifactType": "HEAT", - "artifactDescription": "This is the worst artifact", - "artifactURL": "http://www.openecomp.org/", - "artifactTimeout": "60", - "artifactChecksum": "A worthy checksum", - "artifactVersion": "0.1" - }, - { - "artifactUUID": "1cf78c81-1246-45e7-a190-eaa309ee5681", - "generatedFromUUID": "3cf78c81-1246-45e7-a190-eaa309ee5680", - "artifactName": "The Worst Artifact", - "artifactType": "HEAT", - "artifactDescription": "This is the worst artifact", - "artifactURL": "http://www.openecomp.org/", - "artifactTimeout": "60", - "artifactChecksum": "A worthy checksum", - "artifactVersion": "0.1" - }, - { - "artifactUUID": "2cf78c81-1246-45e7-a190-eaa309ee5682", - "generatedFromUUID": "3cf78c81-1246-45e7-a190-eaa309ee5680", - "artifactName": "The Worst Artifact", - "artifactType": "HEAT", - "artifactDescription": "This is the worst artifact", - "artifactURL": "http://www.openecomp.org/", - "artifactTimeout": "60", - "artifactChecksum": "A worthy checksum", - "artifactVersion": "0.1" - } - ], - "resources": [] - } - }, - "resources": { - "2f92b5b0-10ff-4cf4-9531-88546fe88a42": { - "uuid": "2f92b5b0-10ff-4cf4-9531-88546fe88a42", - "invariantUUID": "df92b5b0-10ff-4cf4-9531-88546fe88a4d", - "name": "The Worst Resource", - "version": "0.1", - "toscaModelURL": "sampleTosca.csar", - "toscaModel": "http://www.openecomp.org/", - "toscaResourceName": "The Worst Resource (TOSCA)", - "category": "Bad Resources", - "subCategory": "Really Bad Resources", - "resourceType": "VF", - "lifecycleState": "CERTIFIED", - "lastUpdaterUserId": "example@example.org", - "lastUpdaterFullName": "Example User", - "artifacts": [ - { - "artifactUUID": "0cf78c81-1246-45e7-a190-eaa309ee5680", - "generatedFromUUID": "3cf78c81-1246-45e7-a190-eaa309ee5680", - "artifactName": "The Worst Artifact", - "artifactType": "HEAT", - "artifactDescription": "This is the worst artifact", - "artifactURL": "http://www.openecomp.org/", - "artifactTimeout": "60", - "artifactChecksum": "A worthy checksum", - "artifactVersion": "0.1" - }, - { - "artifactUUID": "1cf78c81-1246-45e7-a190-eaa309ee5681", - "generatedFromUUID": "3cf78c81-1246-45e7-a190-eaa309ee5680", - "artifactName": "The Worst Artifact", - "artifactType": "HEAT", - "artifactDescription": "This is the worst artifact", - "artifactURL": "http://www.openecomp.org/", - "artifactTimeout": "60", - "artifactChecksum": "A worthy checksum", - "artifactVersion": "0.1" - }, - { - "artifactUUID": "2cf78c81-1246-45e7-a190-eaa309ee5682", - "generatedFromUUID": "3cf78c81-1246-45e7-a190-eaa309ee5680", - "artifactName": "The Worst Artifact", - "artifactType": "HEAT", - "artifactDescription": "This is the worst artifact", - "artifactURL": "http://www.openecomp.org/", - "artifactTimeout": "60", - "artifactChecksum": "A worthy checksum", - "artifactVersion": "0.1" - } - ] - }, - "0f92b5b0-10ff-4cf4-9531-88546fe88a40": { - "uuid": "0f92b5b0-10ff-4cf4-9531-88546fe88a40", - "invariantUUID": "df92b5b0-10ff-4cf4-9531-88546fe88a4d", - "name": "The Worst Resource", - "version": "0.1", - "toscaModelURL": "sampleTosca.csar", - "toscaModel": "http://www.openecomp.org/", - "toscaResourceName": "The Worst Resource (TOSCA)", - "category": "Bad Resources", - "subCategory": "Really Bad Resources", - "resourceType": "VF", - "lifecycleState": "CERTIFIED", - "lastUpdaterUserId": "example@example.org", - "lastUpdaterFullName": "Example User", - "artifacts": [] - }, - "1f92b5b0-10ff-4cf4-9531-88546fe88a41": { - "uuid": "1f92b5b0-10ff-4cf4-9531-88546fe88a41", - "invariantUUID": "df92b5b0-10ff-4cf4-9531-88546fe88a4d", - "name": "The Worst Resource", - "version": "0.1", - "toscaModelURL": "sampleTosca.csar", - "toscaModel": "http://www.openecomp.org/", - "toscaResourceName": "The Worst Resource (TOSCA)", - "category": "Bad Resources", - "subCategory": "Really Bad Resources", - "resourceType": "VF", - "lifecycleState": "CERTIFIED", - "lastUpdaterUserId": "example@example.org", - "lastUpdaterFullName": "Example User", - "artifacts": [] - } - } -}
\ No newline at end of file diff --git a/vid-app-common/src/main/resources/macro_services_by_invariant_uuid.json b/vid-app-common/src/main/resources/macro_services_by_invariant_uuid.json new file mode 100644 index 000000000..fe51488c7 --- /dev/null +++ b/vid-app-common/src/main/resources/macro_services_by_invariant_uuid.json @@ -0,0 +1 @@ +[] diff --git a/vid-app-common/src/main/webapp/WEB-INF/conf/dev.features.properties b/vid-app-common/src/main/webapp/WEB-INF/conf/dev.features.properties index 0815accbb..2a0cb5b88 100644 --- a/vid-app-common/src/main/webapp/WEB-INF/conf/dev.features.properties +++ b/vid-app-common/src/main/webapp/WEB-INF/conf/dev.features.properties @@ -1,7 +1,5 @@ FLAG_ENABLE_WEBPACK_MODERN_UI = true FLAG_ASYNC_JOBS = true -CREATE_INSTANCE_TEST = false -EMPTY_DRAWING_BOARD_TEST = false FLAG_ADD_MSO_TESTAPI_FIELD = true FLAG_UNASSIGN_SERVICE = true FLAG_COLLECTION_RESOURCE_SUPPORT = true @@ -10,11 +8,8 @@ FLAG_SERVICE_MODEL_CACHE = true FLAG_SHOW_ASSIGNMENTS = true FLAG_HANDLE_SO_WORKFLOWS = true FLAG_CREATE_ERROR_REPORTS = true - FLAG_SHOW_VERIFY_SERVICE = true FLAG_DUPLICATE_VNF = true -FLAG_DEFAULT_VNF = true -FLAG_SETTING_DEFAULTS_IN_DRAWING_BOARD = true FLAG_RESTRICTED_SELECT = false FLAG_FABRIC_CONFIGURATION_ASSIGNMENTS = true FLAG_A_LA_CARTE_AUDIT_INFO=true @@ -27,7 +22,6 @@ FLAG_SHIFT_VFMODULE_PARAMS_TO_VNF = true FLAG_EXP_ANY_ALACARTE_NEW_INSTANTIATION_UI=false FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST=true FLAG_1810_CR_LET_SELECTING_COLLECTOR_TYPE_UNCONDITIONALLY=true -FLAG_1810_CR_SOFT_DELETE_ALACARTE_VF_MODULE = false FLAG_1810_AAI_LOCAL_CACHE = true FLAG_1902_NEW_VIEW_EDIT= false FLAG_EXP_USE_DEFAULT_HOST_NAME_VERIFIER = false @@ -38,3 +32,4 @@ FLAG_FLASH_REDUCED_RESPONSE_CHANGEMG = false FLAG_1911_INSTANTIATION_ORDER_IN_ASYNC_ALACARTE = false FLAG_SHOW_ORCHESTRATION_TYPE = false FLAG_1911_INSTANTIATION_ORDER_BUTTON_IN_ASYNC_ALACARTE = false +FLAG_2002_ANY_ALACARTE_BESIDES_EXCLUDED_NEW_INSTANTIATION_UI = false diff --git a/vid-app-common/src/main/webapp/WEB-INF/conf/onap.features.properties b/vid-app-common/src/main/webapp/WEB-INF/conf/onap.features.properties index 709de9566..58f677abc 100644 --- a/vid-app-common/src/main/webapp/WEB-INF/conf/onap.features.properties +++ b/vid-app-common/src/main/webapp/WEB-INF/conf/onap.features.properties @@ -1,6 +1,5 @@ FLAG_PNP_INSTANTIATION = true -CREATE_INSTANCE_TEST = false FLAG_ADD_MSO_TESTAPI_FIELD = true FLAG_UNASSIGN_SERVICE = true FLAG_SERVICE_MODEL_CACHE = true @@ -10,7 +9,6 @@ FLAG_FABRIC_CONFIGURATION_ASSIGNMENTS = true FLAG_PRESENT_PROVIDER_NETWORKS_ASSOCIATIONS = true FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST = true FLAG_1810_CR_LET_SELECTING_COLLECTOR_TYPE_UNCONDITIONALLY = true -FLAG_1810_CR_SOFT_DELETE_ALACARTE_VF_MODULE = false FLAG_1810_AAI_LOCAL_CACHE = true FLAG_EXP_USE_DEFAULT_HOST_NAME_VERIFIER = false FLAG_HANDLE_SO_WORKFLOWS = true @@ -22,11 +20,8 @@ FLAG_SHOW_ORCHESTRATION_TYPE = false FLAG_COLLECTION_RESOURCE_SUPPORT = false FLAG_ENABLE_WEBPACK_MODERN_UI = false FLAG_ASYNC_JOBS = false -EMPTY_DRAWING_BOARD_TEST = false FLAG_NETWORK_TO_ASYNC_INSTANTIATION = false FLAG_DUPLICATE_VNF = false -FLAG_DEFAULT_VNF = false -FLAG_SETTING_DEFAULTS_IN_DRAWING_BOARD = false FLAG_SHIFT_VFMODULE_PARAMS_TO_VNF = false FLAG_A_LA_CARTE_AUDIT_INFO = false FLAG_5G_IN_NEW_INSTANTIATION_UI = false diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/constants/componentConstants.js b/vid-app-common/src/main/webapp/app/vid/scripts/constants/componentConstants.js index 3575c382d..9cdd5ceb9 100755 --- a/vid-app-common/src/main/webapp/app/vid/scripts/constants/componentConstants.js +++ b/vid-app-common/src/main/webapp/app/vid/scripts/constants/componentConstants.js @@ -197,6 +197,7 @@ appDS2 WELCOME_PATH: "welcome.htm", IS_PERMITTED_SUB_PATH: "&isPermitted=", SERVICE_POPUP_IFRAME_URL: "app/ui/#/servicePopup?serviceModelId=", + INSTANTIATION_TEMPLATES_IFRAME_URL: "app/ui/#/instantiationTemplatesPopup?serviceModelId=", SUB_INTERFACE_POPUP_IFRAME_URL: "app/ui/#/vlan?", VERIFY_SERVICE_URL: "rest/models/services/verifyService", @@ -256,7 +257,6 @@ appDS2 FLAG_PRESENT_PROVIDER_NETWORKS_ASSOCIATIONS: "FLAG_PRESENT_PROVIDER_NETWORKS_ASSOCIATIONS", FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST: "FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST", FLAG_1810_CR_LET_SELECTING_COLLECTOR_TYPE_UNCONDITIONALLY: "FLAG_1810_CR_LET_SELECTING_COLLECTOR_TYPE_UNCONDITIONALLY", - FLAG_1810_CR_SOFT_DELETE_ALACARTE_VF_MODULE: "FLAG_1810_CR_SOFT_DELETE_ALACARTE_VF_MODULE", FLAG_HANDLE_SO_WORKFLOWS: "FLAG_HANDLE_SO_WORKFLOWS", FLAG_CREATE_ERROR_REPORTS: "FLAG_CREATE_ERROR_REPORTS", FLAG_FLASH_CLOUD_REGION_AND_NF_ROLE_OPTIONAL_SEARCH: "FLAG_FLASH_CLOUD_REGION_AND_NF_ROLE_OPTIONAL_SEARCH", @@ -265,6 +265,7 @@ appDS2 FLAG_FLASH_REPLACE_VF_MODULE: "FLAG_FLASH_REPLACE_VF_MODULE", FLAG_FLASH_MORE_ACTIONS_BUTTON_IN_OLD_VIEW_EDIT: "FLAG_FLASH_MORE_ACTIONS_BUTTON_IN_OLD_VIEW_EDIT", FLAG_SHOW_ORCHESTRATION_TYPE: "FLAG_SHOW_ORCHESTRATION_TYPE", + FLAG_2004_INSTANTIATION_TEMPLATES_POPUP : "FLAG_2004_INSTANTIATION_TEMPLATES_POPUP" } }; diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/controller/InstantiationController.js b/vid-app-common/src/main/webapp/app/vid/scripts/controller/InstantiationController.js index 9037b99f4..673d2f6c4 100755 --- a/vid-app-common/src/main/webapp/app/vid/scripts/controller/InstantiationController.js +++ b/vid-app-common/src/main/webapp/app/vid/scripts/controller/InstantiationController.js @@ -358,24 +358,14 @@ populate_popup_vfModule(serviceObject, vfModule, vnf);
- if (featureFlags.isOn(COMPONENT.FEATURE_FLAGS.FLAG_1810_CR_SOFT_DELETE_ALACARTE_VF_MODULE)) {
-
- if (DataService.getLoggedInUserId()) {
- openVfModuleWithHomingDataModal(COMPONENT.DELETE, vfModule);
- }
- else {
- AaiService.getLoggedInUserID(function (response) {
- var userID = response.data;
- DataService.setLoggedInUserId(userID);
- openVfModuleWithHomingDataModal(COMPONENT.DELETE, vfModule);
- });
- }
+ if (DataService.getLoggedInUserId()) {
+ openVfModuleWithHomingDataModal(COMPONENT.DELETE, vfModule);
}
else {
- $scope.$broadcast(COMPONENT.DELETE_RESUME_COMPONENT, {
- componentId: COMPONENT.VF_MODULE,
- callbackFunction: deleteOrResumeCallback,
- dialogMethod: COMPONENT.DELETE
+ AaiService.getLoggedInUserID(function (response) {
+ var userID = response.data;
+ DataService.setLoggedInUserId(userID);
+ openVfModuleWithHomingDataModal(COMPONENT.DELETE, vfModule);
});
}
console.log("Removing VF-Module", vfModule);
@@ -1013,8 +1003,7 @@ var isVfc = false;
_.map($scope.service.model.vnfs, function (value, key) {
- if (value.uuid == vnf.uuid) {
- if (!_.isEmpty(value.vfcInstanceGroups)) {
+ if (value.uuid == vnf.uuid && !_.isEmpty(value.vfcInstanceGroups)) {
isVfc = true;
var queryData = {
serviceModelId: $scope.service.model.service.uuid,
@@ -1030,7 +1019,6 @@ $scope.$broadcast(COMPONENT.IFRAME_DIALOG, queryData);
return;
}
- }
});
DataService.setSubscriberName($scope.service.instance.subscriberName);
@@ -1244,25 +1232,14 @@ DataService.setVfModuleInstanceName(vfModule.object[FIELD.ID.VF_MODULE_NAME]);
setCurrentServiceModelInfoFromScope();
- if (featureFlags.isOn(COMPONENT.FEATURE_FLAGS.FLAG_1810_CR_SOFT_DELETE_ALACARTE_VF_MODULE)) {
-
- if (DataService.getLoggedInUserId()) {
- openVfModuleWithHomingDataModal(COMPONENT.RESUME, vfModule);
- }
- else {
- AaiService.getLoggedInUserID(function (response) {
- var userID = response.data;
- DataService.setLoggedInUserId(userID);
- openVfModuleWithHomingDataModal(COMPONENT.RESUME, vfModule);
- });
- }
+ if (DataService.getLoggedInUserId()) {
+ openVfModuleWithHomingDataModal(COMPONENT.RESUME, vfModule);
}
else {
- $scope.$broadcast(COMPONENT.DELETE_RESUME_COMPONENT, {
- componentId: COMPONENT.VF_MODULE,
- volumeGroups: vfModule.volumeGroups,
- callbackFunction: deleteOrResumeCallback,
- dialogMethod: COMPONENT.RESUME
+ AaiService.getLoggedInUserID(function (response) {
+ var userID = response.data;
+ DataService.setLoggedInUserId(userID);
+ openVfModuleWithHomingDataModal(COMPONENT.RESUME, vfModule);
});
}
};
diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/controller/aaiSubscriberController.js b/vid-app-common/src/main/webapp/app/vid/scripts/controller/aaiSubscriberController.js index bf3d54af0..110f24ec6 100755 --- a/vid-app-common/src/main/webapp/app/vid/scripts/controller/aaiSubscriberController.js +++ b/vid-app-common/src/main/webapp/app/vid/scripts/controller/aaiSubscriberController.js @@ -489,8 +489,7 @@ appDS2.controller("aaiSubscriberController", ["COMPONENT", "FIELD", "PARAMETER", if (model && model.vnfs && !_.isEmpty(model.vnfs)) {
Object.keys(model.vnfs).forEach(function (key) {
var vnf = model.vnfs[key];
- if (vnf.vfcInstanceGroups && !_.isEmpty(vnf.vfcInstanceGroups)) {
- if (vnf.uuid === genericVnf.modelVersionId) {
+ if (vnf.vfcInstanceGroups && !_.isEmpty(vnf.vfcInstanceGroups) && vnf.uuid === genericVnf.modelVersionId) {
AaiService.getInstanceGroupsByVNFInstanceId(genericVnf.nodeId,
function (response) { //success
handleGetRelatedInstanceGroupsResponseForVnf(response, genericVnf);
@@ -502,7 +501,6 @@ appDS2.controller("aaiSubscriberController", ["COMPONENT", "FIELD", "PARAMETER", }
)
}
- }
});
}
}
@@ -797,11 +795,9 @@ appDS2.controller("aaiSubscriberController", ["COMPONENT", "FIELD", "PARAMETER", };
$scope.isShowAssignmentsEnabled = function () {
- if (featureFlags.isOn(COMPONENT.FEATURE_FLAGS.FLAG_SHOW_ASSIGNMENTS)) {
- if ($scope.serviceOrchestrationStatus) {
+ if (featureFlags.isOn(COMPONENT.FEATURE_FLAGS.FLAG_SHOW_ASSIGNMENTS) && $scope.serviceOrchestrationStatus) {
return $scope.serviceOrchestrationStatus.toLowerCase() === 'assigned';
}
- }
return false;
};
diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/controller/creationDialogController.js b/vid-app-common/src/main/webapp/app/vid/scripts/controller/creationDialogController.js index 15627835e..a35411dd1 100755 --- a/vid-app-common/src/main/webapp/app/vid/scripts/controller/creationDialogController.js +++ b/vid-app-common/src/main/webapp/app/vid/scripts/controller/creationDialogController.js @@ -1,409 +1,413 @@ -/*-
- * ============LICENSE_START=======================================================
- * VID
- * ================================================================================
- * Copyright (C) 2017 - 2019 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=========================================================
- */
-
-"use strict";
-
-var creationDialogController = function (COMPONENT, FIELD, PARAMETER, $scope, $http, $timeout, $log,
- CreationService, UtilityService, DataService, VIDCONFIGURATION, $location, $uibModal, featureFlags) {
-
- $scope.isDialogVisible = false;
- $scope.isServiceError = false;
- $scope.summaryControl = {};
- $scope.userProvidedControl = {};
-
-
- var callbackFunction = undefined;
- var componentId = undefined;
-
- $scope.showReportWindow = function() {
-
- let errorMsg;
-
- if($scope.error !== undefined && $scope.error != null) {
- errorMsg = $scope.error;
- } else {
- errorMsg = "";
- }
-
- const modalWindow = $uibModal.open({
- templateUrl: 'app/vid/scripts/modals/report-modal/report-modal.html',
- controller: 'reportModalController',
- controllerAs: 'vm',
- resolve: {
- errorMsg: function () {
- return errorMsg;
- }
- }
- });
-
- $scope.isDialogVisible = false;
- $scope.popup.isVisible = false;
- };
-
- $scope.isShowErrorReport = function() {
- return featureFlags.isOn(COMPONENT.FEATURE_FLAGS.FLAG_CREATE_ERROR_REPORTS);
- };
-
- $scope.shouldShowOldPopup = function () {
- return !DataService.getShouldIncludeInAsyncInstantiationFlow();
- };
-
- function receiveMessage(event) {
- if (event.data == 'closeIframe') {
- window.removeEventListener("message", receiveMessage, false);
-
- $scope.cancel();
- }
- else if (event.data.eventId == 'submitIframe') {
- {
- $location.path('/servicePlanning').search({serviceModelId: event.data.data.serviceModelId});
- }
- }
- $scope.$apply();
- }
-
- $scope.$on(COMPONENT.CREATE_COMPONENT, function (event, request) {
- $scope.isSpinnerVisible = true;
- $scope.isErrorVisible = false;
- $scope.isDataVisible = false;
- $scope.isConfirmEnabled = false;
- $scope.isDialogVisible = true;
- $scope.popup.isVisible = true;
-
-
- if (!$scope.shouldShowOldPopup()) {
- $scope.url = COMPONENT.SERVICE_POPUP_IFRAME_URL + request.modelNameVersionId + "&isCreate=true&r=" + Math.random();
- window.addEventListener("message", receiveMessage, false);
-
- }
- else {
- callbackFunction = request.callbackFunction;
- componentId = request.componentId;
- CreationService.initializeComponent(request.componentId);
-
- CreationService.setHttpErrorHandler(function (response) {
- $scope.isServiceError = true;
- showError(FIELD.ERROR.SYSTEM_FAILURE, UtilityService
- .getHttpErrorMessage(response));
- });
-
- $scope.componentName = CreationService.getComponentDisplayName();
-
- CreationService.getParameters(handleGetParametersResponse);
- }
-
- });
-
- var handleGetParametersResponse = function (parameters) {
- $scope.summaryControl.setList(parameters.summaryList);
- $scope.userProvidedControl.setList(parameters.userProvidedList);
-
- $scope.isSpinnerVisible = false;
- $scope.isDataVisible = true;
- $scope.isConfirmEnabled = true;
- };
-
- var validateInstanceName = function (iname) {
- var patt1 = /^([a-z])+([0-9a-z\-_\.]*)$/i;
-
- if (iname == null) {
- return false;
- }
- if (!iname.match(patt1)) {
- return false;
- }
- return true;
- };
- var validateMap = function (mname) {
- var patt1 = /^{(\s*\w+\s*:\s*\w+\s*)(\s*,\s*\w+\s*:\s*\w+\s*)*}$/im;
- if (mname == null) {
- return true;
- }
- if (!mname.match(patt1)) {
- return false;
- }
- return true;
- };
-
- var validateList = function (lname) {
- var patt1 = /^\[(\s*\w+\s*)(\s*,\s*\w+\s*)*\]$/i;
- if (lname == null) {
- return true;
- }
- if (!lname.match(patt1)) {
- return false;
- }
- return true;
- };
-
- $scope.userParameterChanged = function (id) {
- CreationService.updateUserParameterList(id, $scope.userProvidedControl);
- };
-
- $scope.confirm = function () {
-
- var requiredFields = $scope.userProvidedControl.getRequiredFields();
- if (requiredFields !== "") {
- showError(FIELD.ERROR.MISSING_DATA, requiredFields);
- return;
- }
-
- var isUploadAvailable = false;
- var uploadIndex = 0;
- var paramList = $scope.userProvidedControl.getList();
- var isAnyError = false;
- for (var i = 0; i < paramList.length; i++) {
- if (paramList[i].id === FIELD.ID.SUPPLEMENTORY_DATA_FILE) {
- isUploadAvailable = true;
- uploadIndex = i;
- }
- if (paramList[i].id === FIELD.ID.UPLOAD_SUPPLEMENTORY_DATA_FILE && paramList[i].value && document.getElementById(FIELD.ID.SUPPLEMENTORY_DATA_FILE).value == '') {
- isAnyError = true;
- }
- }
-
- if (isUploadAvailable && isAnyError) {
- showError(FIELD.ERROR.MISSING_DATA, FIELD.ERROR.MISSING_FILE);
-
- } else if (isUploadAvailable && document.getElementById(FIELD.ID.SUPPLEMENTORY_DATA_FILE).value != '') {
- var errorMsg = "";
- var fileInput = document.getElementById(FIELD.ID.SUPPLEMENTORY_DATA_FILE);
- var file = fileInput.files[0];
- var reader = new FileReader();
- reader.onload = function (e) {
- try {
- paramList[uploadIndex].value = JSON.parse(reader.result);
- FIELD.PARAMETER.SUPPLEMENTORY_DATA_FILE['value'] = paramList[uploadIndex].value;
-
- var instanceName = "";
-
- if (DataService.getALaCarte()) {
- if (paramList != null) {
- for (var i = 0; i < paramList.length; i++) {
- if (paramList[i].id === FIELD.ID.INSTANCE_NAME) {
- instanceName = paramList[i].value;
- break;
- }
- }
- }
- var isValid = validateInstanceName(instanceName);
- if (isValid) {
- $scope.isErrorVisible = false;
- } else {
- showError(FIELD.ERROR.INVALID_INSTANCE_NAME + instanceName,
- FIELD.ERROR.INSTANCE_NAME_VALIDATE);
- return;
- }
- }
- var arbitraryParametersList = DataService.getArbitraryParameters();
- var p = null;
- if (UtilityService.hasContents(arbitraryParametersList)) {
- for (var i = 0; i < arbitraryParametersList.length; i++) {
- p = arbitraryParametersList[i];
- if (p.type === PARAMETER.MAP) {
- //validate a map: { <entry_key_1>: <entry_value_1>, ... , <entry_key_n>: <entry_value_n> }
- // need to find the value in paramList
- for (var j = 0; j < paramList.length; j++) {
- if (paramList[j].id === p.id) {
- p.value = paramList[j].value;
- var isValid = validateMap(p.value);
- if (isValid) {
- $scope.isErrorVisible = false;
- break;
- }
- else {
- showError(FIELD.ERROR.INVALID_MAP + p.id,
- FIELD.ERROR.MAP_VALIDATE);
- return;
- }
- }
- }
- } else if (p.type === PARAMETER.LIST) {
- //validate a list: { value or a list of comma separated values }
- // need to find the value in paramList
- for (var j = 0; j < paramList.length; j++) {
- if (paramList[j].id === p.id) {
- p.value = paramList[j].value;
- var isValid = validateList(p.value);
- if (isValid) {
- $scope.isErrorVisible = false;
- break;
- }
- else {
- showError(FIELD.ERROR.INVALID_LIST + p.id,
- FIELD.ERROR.LIST_VALIDATE);
- return;
- }
- }
- }
- }
- }
- }
- var requestDetails = CreationService
- .getMsoRequestDetails($scope.userProvidedControl.getList());
-
- $scope.isDialogVisible = false;
-
- $scope.$broadcast(COMPONENT.MSO_CREATE_REQ, {
- url: CreationService.getMsoUrl(),
- requestDetails: requestDetails,
- componentId: componentId,
- callbackFunction: function (response) {
- if (response.isSuccessful) {
- $scope.popup.isVisible = false;
- runCallback(response);
- } else {
- $scope.isDialogVisible = false;
- $scope.popup.isVisible = false;
- }
- }
- });
-
- } catch (e) {
- errorMsg = errorMsg + FIELD.ERROR.INVALID_DATA_FORMAT;
- }
- if (errorMsg !== "") {
- showError(FIELD.ERROR.SYSTEM_FAILURE, errorMsg);
-
- }
- };
- reader.readAsText(file);
- } else {
-
- var paramList = $scope.userProvidedControl.getList();
- var instanceName = "";
-
- if (DataService.getALaCarte()) {
- if (paramList != null) {
- for (var i = 0; i < paramList.length; i++) {
- if (paramList[i].id === FIELD.ID.INSTANCE_NAME) {
- instanceName = paramList[i].value;
- break;
- }
- }
- }
- var isValid = validateInstanceName(instanceName);
- if (isValid) {
- $scope.isErrorVisible = false;
- } else {
- showError(FIELD.ERROR.INVALID_INSTANCE_NAME + instanceName,
- FIELD.ERROR.INSTANCE_NAME_VALIDATE);
- return;
- }
- }
- var arbitraryParametersList = DataService.getArbitraryParameters();
- var p = null;
- if (UtilityService.hasContents(arbitraryParametersList)) {
- for (var i = 0; i < arbitraryParametersList.length; i++) {
- p = arbitraryParametersList[i];
- if (p.type === PARAMETER.MAP) {
- //validate a map: { <entry_key_1>: <entry_value_1>, ... , <entry_key_n>: <entry_value_n> }
- // need to find the value in paramList
- for (var j = 0; j < paramList.length; j++) {
- if (paramList[j].id === p.id) {
- p.value = paramList[j].value;
- var isValid = validateMap(p.value);
- if (isValid) {
- $scope.isErrorVisible = false;
- break;
- }
- else {
- showError(FIELD.ERROR.INVALID_MAP + p.id,
- FIELD.ERROR.MAP_VALIDATE);
- return;
- }
- }
- }
- } else if (p.type === PARAMETER.LIST) {
- //validate a list: { value or a list of comma separated values }
- // need to find the value in paramList
- for (var j = 0; j < paramList.length; j++) {
- if (paramList[j].id === p.id) {
- p.value = paramList[j].value;
- var isValid = validateList(p.value);
- if (isValid) {
- $scope.isErrorVisible = false;
- break;
- }
- else {
- showError(FIELD.ERROR.INVALID_LIST + p.id,
- FIELD.ERROR.LIST_VALIDATE);
- return;
- }
- }
- }
- }
- }
- }
- var requestDetails = CreationService
- .getMsoRequestDetails($scope.userProvidedControl.getList());
-
- $scope.isDialogVisible = false;
-
- $scope.$broadcast(COMPONENT.MSO_CREATE_REQ, {
- url: CreationService.getMsoUrl(),
- requestDetails: requestDetails,
- componentId: componentId,
- callbackFunction: function (response) {
- if (response.isSuccessful) {
- $scope.popup.isVisible = false;
- runCallback(response);
- } else {
- $scope.isDialogVisible = false;
- $scope.popup.isVisible = false;
- }
- }
- });
- }
- };
-
- $scope.cancel = function () {
- $scope.isDialogVisible = false;
- $scope.popup.isVisible = false;
- runCallback(false);
- };
-
-
- var runCallback = function (response) {
- if (angular.isFunction(callbackFunction)) {
- callbackFunction({
- isSuccessful: response.isSuccessful,
- control: $scope.userProvidedControl.getList(),
- instanceId: response.instanceId
- });
- }
- };
-
- var showError = function (summary, details) {
- var message = summary;
- if (UtilityService.hasContents(details)) {
- message += " (" + details + ")";
- }
- $scope.isSpinnerVisible = false;
- $scope.isErrorVisible = true;
- $scope.error = message;
- }
-
-};
-
-appDS2.controller("creationDialogController", ["COMPONENT", "FIELD", "PARAMETER", "$scope", "$http",
- "$timeout", "$log", "CreationService", "UtilityService", "DataService", "VIDCONFIGURATION", "$location",
- "$uibModal", "featureFlags",
- creationDialogController]);
+/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 - 2019 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========================================================= + */ + +"use strict"; + +var creationDialogController = function (COMPONENT, FIELD, PARAMETER, $scope, $http, $timeout, $log, + CreationService, UtilityService, DataService, VIDCONFIGURATION, $location, $uibModal, featureFlags) { + + $scope.isDialogVisible = false; + $scope.isServiceError = false; + $scope.summaryControl = {}; + $scope.userProvidedControl = {}; + + + var callbackFunction = undefined; + var componentId = undefined; + + $scope.showReportWindow = function() { + + let errorMsg; + + if($scope.error !== undefined && $scope.error != null) { + errorMsg = $scope.error; + } else { + errorMsg = ""; + } + + const modalWindow = $uibModal.open({ + templateUrl: 'app/vid/scripts/modals/report-modal/report-modal.html', + controller: 'reportModalController', + controllerAs: 'vm', + resolve: { + errorMsg: function () { + return errorMsg; + } + } + }); + + $scope.isDialogVisible = false; + $scope.popup.isVisible = false; + }; + + $scope.isShowErrorReport = function() { + return featureFlags.isOn(COMPONENT.FEATURE_FLAGS.FLAG_CREATE_ERROR_REPORTS); + }; + + $scope.shouldShowOldPopup = function () { + return !DataService.getShouldIncludeInAsyncInstantiationFlow(); + }; + + function receiveMessage(event) { + if (event.data == 'closeIframe') { + window.removeEventListener("message", receiveMessage, false); + + $scope.cancel(); + } + else if (event.data.eventId == 'submitIframe') { + { + $location.path('/servicePlanning').search({serviceModelId: event.data.data.serviceModelId}); + } + } else if (event.data.eventId == 'showPreviousInstantiations') { + { + $location.path('/instantiationStatus').search({filterText: event.data.data.serviceModelId}); + } + } + $scope.$apply(); + } + + $scope.$on(COMPONENT.CREATE_COMPONENT, function (event, request) { + $scope.isSpinnerVisible = true; + $scope.isErrorVisible = false; + $scope.isDataVisible = false; + $scope.isConfirmEnabled = false; + $scope.isDialogVisible = true; + $scope.popup.isVisible = true; + + + if (!$scope.shouldShowOldPopup()) { + $scope.url = COMPONENT.SERVICE_POPUP_IFRAME_URL + request.modelNameVersionId + "&isCreate=true&r=" + Math.random(); + window.addEventListener("message", receiveMessage, false); + + } + else { + callbackFunction = request.callbackFunction; + componentId = request.componentId; + CreationService.initializeComponent(request.componentId); + + CreationService.setHttpErrorHandler(function (response) { + $scope.isServiceError = true; + showError(FIELD.ERROR.SYSTEM_FAILURE, UtilityService + .getHttpErrorMessage(response)); + }); + + $scope.componentName = CreationService.getComponentDisplayName(); + + CreationService.getParameters(handleGetParametersResponse); + } + + }); + + var handleGetParametersResponse = function (parameters) { + $scope.summaryControl.setList(parameters.summaryList); + $scope.userProvidedControl.setList(parameters.userProvidedList); + + $scope.isSpinnerVisible = false; + $scope.isDataVisible = true; + $scope.isConfirmEnabled = true; + }; + + var validateInstanceName = function (iname) { + var patt1 = /^([a-z])+([0-9a-z\-_\.]*)$/i; + + if (iname == null) { + return false; + } + if (!iname.match(patt1)) { + return false; + } + return true; + }; + var validateMap = function (mname) { + var patt1 = /^{(\s*\w+\s*:\s*\w+\s*)(\s*,\s*\w+\s*:\s*\w+\s*)*}$/im; + if (mname == null) { + return true; + } + if (!mname.match(patt1)) { + return false; + } + return true; + }; + + var validateList = function (lname) { + var patt1 = /^\[(\s*\w+\s*)(\s*,\s*\w+\s*)*\]$/i; + if (lname == null) { + return true; + } + if (!lname.match(patt1)) { + return false; + } + return true; + }; + + $scope.userParameterChanged = function (id) { + CreationService.updateUserParameterList(id, $scope.userProvidedControl); + }; + + $scope.confirm = function () { + + var requiredFields = $scope.userProvidedControl.getRequiredFields(); + if (requiredFields !== "") { + showError(FIELD.ERROR.MISSING_DATA, requiredFields); + return; + } + + var isUploadAvailable = false; + var uploadIndex = 0; + var paramList = $scope.userProvidedControl.getList(); + var isAnyError = false; + for (var i = 0; i < paramList.length; i++) { + if (paramList[i].id === FIELD.ID.SUPPLEMENTORY_DATA_FILE) { + isUploadAvailable = true; + uploadIndex = i; + } + if (paramList[i].id === FIELD.ID.UPLOAD_SUPPLEMENTORY_DATA_FILE && paramList[i].value && document.getElementById(FIELD.ID.SUPPLEMENTORY_DATA_FILE).value == '') { + isAnyError = true; + } + } + + if (isUploadAvailable && isAnyError) { + showError(FIELD.ERROR.MISSING_DATA, FIELD.ERROR.MISSING_FILE); + + } else if (isUploadAvailable && document.getElementById(FIELD.ID.SUPPLEMENTORY_DATA_FILE).value != '') { + var errorMsg = ""; + var fileInput = document.getElementById(FIELD.ID.SUPPLEMENTORY_DATA_FILE); + var file = fileInput.files[0]; + var reader = new FileReader(); + reader.onload = function (e) { + try { + paramList[uploadIndex].value = JSON.parse(reader.result); + FIELD.PARAMETER.SUPPLEMENTORY_DATA_FILE['value'] = paramList[uploadIndex].value; + + var instanceName = ""; + + if (DataService.getALaCarte()) { + if (paramList != null) { + for (var i = 0; i < paramList.length; i++) { + if (paramList[i].id === FIELD.ID.INSTANCE_NAME) { + instanceName = paramList[i].value; + break; + } + } + } + var isValid = validateInstanceName(instanceName); + if (isValid) { + $scope.isErrorVisible = false; + } else { + showError(FIELD.ERROR.INVALID_INSTANCE_NAME + instanceName, + FIELD.ERROR.INSTANCE_NAME_VALIDATE); + return; + } + } + var arbitraryParametersList = DataService.getArbitraryParameters(); + var p = null; + if (UtilityService.hasContents(arbitraryParametersList)) { + for (var i = 0; i < arbitraryParametersList.length; i++) { + p = arbitraryParametersList[i]; + if (p.type === PARAMETER.MAP) { + //validate a map: { <entry_key_1>: <entry_value_1>, ... , <entry_key_n>: <entry_value_n> } + // need to find the value in paramList + for (var j = 0; j < paramList.length; j++) { + if (paramList[j].id === p.id) { + p.value = paramList[j].value; + var isValid = validateMap(p.value); + if (isValid) { + $scope.isErrorVisible = false; + break; + } + else { + showError(FIELD.ERROR.INVALID_MAP + p.id, + FIELD.ERROR.MAP_VALIDATE); + return; + } + } + } + } else if (p.type === PARAMETER.LIST) { + //validate a list: { value or a list of comma separated values } + // need to find the value in paramList + for (var j = 0; j < paramList.length; j++) { + if (paramList[j].id === p.id) { + p.value = paramList[j].value; + var isValid = validateList(p.value); + if (isValid) { + $scope.isErrorVisible = false; + break; + } + else { + showError(FIELD.ERROR.INVALID_LIST + p.id, + FIELD.ERROR.LIST_VALIDATE); + return; + } + } + } + } + } + } + var requestDetails = CreationService + .getMsoRequestDetails($scope.userProvidedControl.getList()); + + $scope.isDialogVisible = false; + + $scope.$broadcast(COMPONENT.MSO_CREATE_REQ, { + url: CreationService.getMsoUrl(), + requestDetails: requestDetails, + componentId: componentId, + callbackFunction: function (response) { + if (response.isSuccessful) { + $scope.popup.isVisible = false; + runCallback(response); + } else { + $scope.isDialogVisible = false; + $scope.popup.isVisible = false; + } + } + }); + + } catch (e) { + errorMsg = errorMsg + FIELD.ERROR.INVALID_DATA_FORMAT; + } + if (errorMsg !== "") { + showError(FIELD.ERROR.SYSTEM_FAILURE, errorMsg); + + } + }; + reader.readAsText(file); + } else { + + var paramList = $scope.userProvidedControl.getList(); + var instanceName = ""; + + if (DataService.getALaCarte()) { + if (paramList != null) { + for (var i = 0; i < paramList.length; i++) { + if (paramList[i].id === FIELD.ID.INSTANCE_NAME) { + instanceName = paramList[i].value; + break; + } + } + } + var isValid = validateInstanceName(instanceName); + if (isValid) { + $scope.isErrorVisible = false; + } else { + showError(FIELD.ERROR.INVALID_INSTANCE_NAME + instanceName, + FIELD.ERROR.INSTANCE_NAME_VALIDATE); + return; + } + } + var arbitraryParametersList = DataService.getArbitraryParameters(); + var p = null; + if (UtilityService.hasContents(arbitraryParametersList)) { + for (var i = 0; i < arbitraryParametersList.length; i++) { + p = arbitraryParametersList[i]; + if (p.type === PARAMETER.MAP) { + //validate a map: { <entry_key_1>: <entry_value_1>, ... , <entry_key_n>: <entry_value_n> } + // need to find the value in paramList + for (var j = 0; j < paramList.length; j++) { + if (paramList[j].id === p.id) { + p.value = paramList[j].value; + var isValid = validateMap(p.value); + if (isValid) { + $scope.isErrorVisible = false; + break; + } + else { + showError(FIELD.ERROR.INVALID_MAP + p.id, + FIELD.ERROR.MAP_VALIDATE); + return; + } + } + } + } else if (p.type === PARAMETER.LIST) { + //validate a list: { value or a list of comma separated values } + // need to find the value in paramList + for (var j = 0; j < paramList.length; j++) { + if (paramList[j].id === p.id) { + p.value = paramList[j].value; + var isValid = validateList(p.value); + if (isValid) { + $scope.isErrorVisible = false; + break; + } + else { + showError(FIELD.ERROR.INVALID_LIST + p.id, + FIELD.ERROR.LIST_VALIDATE); + return; + } + } + } + } + } + } + var requestDetails = CreationService + .getMsoRequestDetails($scope.userProvidedControl.getList()); + + $scope.isDialogVisible = false; + + $scope.$broadcast(COMPONENT.MSO_CREATE_REQ, { + url: CreationService.getMsoUrl(), + requestDetails: requestDetails, + componentId: componentId, + callbackFunction: function (response) { + if (response.isSuccessful) { + $scope.popup.isVisible = false; + runCallback(response); + } else { + $scope.isDialogVisible = false; + $scope.popup.isVisible = false; + } + } + }); + } + }; + + $scope.cancel = function () { + $scope.isDialogVisible = false; + $scope.popup.isVisible = false; + runCallback(false); + }; + + + var runCallback = function (response) { + if (angular.isFunction(callbackFunction)) { + callbackFunction({ + isSuccessful: response.isSuccessful, + control: $scope.userProvidedControl.getList(), + instanceId: response.instanceId + }); + } + }; + + var showError = function (summary, details) { + var message = summary; + if (UtilityService.hasContents(details)) { + message += " (" + details + ")"; + } + $scope.isSpinnerVisible = false; + $scope.isErrorVisible = true; + $scope.error = message; + } + +}; + +appDS2.controller("creationDialogController", ["COMPONENT", "FIELD", "PARAMETER", "$scope", "$http", + "$timeout", "$log", "CreationService", "UtilityService", "DataService", "VIDCONFIGURATION", "$location", + "$uibModal", "featureFlags", + creationDialogController]); diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/AAITreeConverterTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/AAITreeConverterTest.java index 560e6cb5f..7bfc8a68a 100644 --- a/vid-app-common/src/test/java/org/onap/vid/aai/AAITreeConverterTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/aai/AAITreeConverterTest.java @@ -20,32 +20,41 @@ */ package org.onap.vid.aai; +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.startsWith; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.onap.vid.asdc.parser.ToscaParserImpl2.Constants.A_LA_CARTE; +import static org.testng.Assert.assertNull; + import com.google.common.collect.ImmutableList; +import java.util.List; import org.mockito.InjectMocks; import org.mockito.MockitoAnnotations; +import org.mockito.Spy; import org.onap.vid.aai.util.AAITreeConverter; import org.onap.vid.model.Action; -import org.onap.vid.model.aaiTree.*; +import org.onap.vid.model.ModelUtil; +import org.onap.vid.model.aaiTree.AAITreeNode; +import org.onap.vid.model.aaiTree.CollectionResource; +import org.onap.vid.model.aaiTree.Network; +import org.onap.vid.model.aaiTree.NodeType; import org.onap.vid.model.aaiTree.ServiceInstance; +import org.onap.vid.model.aaiTree.VfModule; +import org.onap.vid.model.aaiTree.Vnf; import org.onap.vid.mso.model.CloudConfiguration; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; -import java.util.List; - -import static org.hamcrest.CoreMatchers.*; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.emptyOrNullString; -import static org.hamcrest.Matchers.hasKey; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.onap.vid.asdc.parser.ToscaParserImpl2.Constants.A_LA_CARTE; -import static org.testng.Assert.assertNull; - public class AAITreeConverterTest { + @Spy + private ModelUtil modelUtil; + @InjectMocks private AAITreeConverter aaiTreeConverter; diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/OperationalEnvironmentTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/OperationalEnvironmentTest.java index 076c46284..063b2220c 100644 --- a/vid-app-common/src/test/java/org/onap/vid/aai/OperationalEnvironmentTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/aai/OperationalEnvironmentTest.java @@ -22,73 +22,94 @@ package org.onap.vid.aai; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Assert; -import org.onap.vid.aai.model.RelationshipList; -import org.testng.annotations.Test; +import static org.assertj.core.api.Assertions.assertThat; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.ArrayList; - -import static com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSetters; -import static org.assertj.core.api.Assertions.assertThat; +import org.onap.vid.aai.model.RelationshipList; +import org.testng.annotations.Test; public class OperationalEnvironmentTest { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); - private static final String OPERATIONAL_ENVIRONMENT_TEST = "{\n" + - "\"operational-environment-id\": \"environmentId\",\n" + - "\"operational-environment-name\": \"environmentName\",\n" + - "\"operational-environment-type\": \"environmentType\",\n" + - "\"operational-environment-status\": \"environmentStatus\",\n" + - "\"tenant-context\": \"tenantContext\",\n" + - "\"workload-context\": \"workloadContext\",\n" + - "\"resource-version\": \"resourceVersion\",\n" + - "\"relationship-list\": {\n" + - "\"relationship\": []\n" + - "}\n" + - "}"; + private static final String OPERATIONAL_ENVIRONMENT_JSON_DASHES = "{\n" + + "\"operational-environment-id\": \"testEnvironmentId\",\n" + + "\"operational-environment-name\": \"testEnvironmentName\",\n" + + "\"operational-environment-type\": \"testEnvironmentType\",\n" + + "\"operational-environment-status\": \"testEnvironmentStatus\",\n" + + "\"tenant-context\": \"testTenantContext\",\n" + + "\"workload-context\": \"testWorkloadContext\",\n" + + "\"resource-version\": \"testResourceVersion\",\n" + + "\"relationship-list\": {\n" + + "\"relationship\": []\n" + + "}\n" + + "}"; + + private static final String OPERATIONAL_ENVIRONMENT_JSON_CAMELCASE = "{\n" + + "\"operationalEnvironmentId\": \"testEnvironmentId\",\n" + + "\"operationalEnvironmentName\": \"testEnvironmentName\",\n" + + "\"operationalEnvironmentType\": \"testEnvironmentType\",\n" + + "\"operationalEnvironmentStatus\": \"testEnvironmentStatus\",\n" + + "\"tenantContext\": \"testTenantContext\",\n" + + "\"workloadContext\": \"testWorkloadContext\",\n" + + "\"resourceVersion\": \"testResourceVersion\",\n" + + "\"relationshipList\": {\n" + + "\"relationship\": []\n" + + "}\n" + + "}"; @Test - public void shouldCreateProperOperationalEnvironmentWithConstructor(){ - RelationshipList relationshipList = new RelationshipList(); - relationshipList.relationship = new ArrayList<>(); + public void shouldProperlyConvertJsonToOperationalEnvironment_whenJsonPropertyNamesContainDashSeparators() + throws IOException { + assertOperationalEnvironmentDeserialization(OPERATIONAL_ENVIRONMENT_JSON_DASHES); + } + + @Test + public void shouldProperlyConvertJsonToOperationalEnvironment_whenJsonPropertyNamesAreCamelCase() + throws IOException { + assertOperationalEnvironmentDeserialization(OPERATIONAL_ENVIRONMENT_JSON_CAMELCASE); + } + private void assertOperationalEnvironmentDeserialization(String operationalEnvironmentTestDashes) + throws IOException { OperationalEnvironment operationalEnvironment = - new OperationalEnvironment.OperationalEnvironmentBuilder() - .setOperationalEnvironmentId("testId") - .setOperationalEnvironmentName("testEnvName") - .setOperationalEnvironmentType("testEnvType") - .setOperationalEnvironmentStatus("testEnvStatus") - .setTenantContext("testTenant").setWorkloadContext("testWorkload") - .setResourceVersion("testResource").setRelationshipList(relationshipList) - .createOperationalEnvironment(); - - assertThat(operationalEnvironment.getOperationalEnvironmentId()).isEqualTo("testId"); - assertThat(operationalEnvironment.getWorkloadContext()).isEqualTo("testWorkload"); + OBJECT_MAPPER.readValue(operationalEnvironmentTestDashes, OperationalEnvironment.class); + + assertThat(operationalEnvironment.getOperationalEnvironmentId()).isEqualTo("testEnvironmentId"); + assertThat(operationalEnvironment.getOperationalEnvironmentName()).isEqualTo("testEnvironmentName"); + assertThat(operationalEnvironment.getOperationalEnvironmentType()).isEqualTo("testEnvironmentType"); + assertThat(operationalEnvironment.getOperationalEnvironmentStatus()).isEqualTo("testEnvironmentStatus"); + assertThat(operationalEnvironment.getTenantContext()).isEqualTo("testTenantContext"); + assertThat(operationalEnvironment.getWorkloadContext()).isEqualTo("testWorkloadContext"); + assertThat(operationalEnvironment.getResourceVersion()).isEqualTo("testResourceVersion"); assertThat(operationalEnvironment.getRelationshipList().getRelationship()).hasSize(0); - assertThat(operationalEnvironment.getResourceVersion()).isEqualTo("testResource"); - assertThat(operationalEnvironment.getTenantContext()).isEqualTo("testTenant"); - assertThat(operationalEnvironment.getOperationalEnvironmentType()).isEqualTo("testEnvType"); - assertThat(operationalEnvironment.getOperationalEnvironmentStatus()).isEqualTo("testEnvStatus"); - assertThat(operationalEnvironment.getOperationalEnvironmentName()).isEqualTo("testEnvName"); } @Test - public void shouldProperlyConvertJsonToOperationalEnvironment() throws IOException { - OperationalEnvironment operationalEnvironment = - OBJECT_MAPPER.readValue(OPERATIONAL_ENVIRONMENT_TEST, OperationalEnvironment.class); + public void shouldSerializeToJson_usingActualPropertyNameAsJsonLogicalProperty() throws JsonProcessingException { + RelationshipList relationshipList = new RelationshipList(); + relationshipList.relationship = new ArrayList<>(); - assertThat(operationalEnvironment.getOperationalEnvironmentId()).isEqualTo("environmentId"); - assertThat(operationalEnvironment.getWorkloadContext()).isEqualTo("workloadContext"); - assertThat(operationalEnvironment.getRelationshipList().getRelationship()).hasSize(0); - assertThat(operationalEnvironment.getResourceVersion()).isEqualTo("resourceVersion"); - assertThat(operationalEnvironment.getTenantContext()).isEqualTo("tenantContext"); - assertThat(operationalEnvironment.getOperationalEnvironmentType()).isEqualTo("environmentType"); - assertThat(operationalEnvironment.getOperationalEnvironmentStatus()).isEqualTo("environmentStatus"); - assertThat(operationalEnvironment.getOperationalEnvironmentName()).isEqualTo("environmentName"); + OperationalEnvironment operationalEnvironment = createOperationalEnvironment(relationshipList); + + assertThat(OPERATIONAL_ENVIRONMENT_JSON_CAMELCASE) + .isEqualToIgnoringWhitespace(OBJECT_MAPPER.writeValueAsString(operationalEnvironment)); } + private OperationalEnvironment createOperationalEnvironment(RelationshipList relationshipList) { + return new OperationalEnvironment.OperationalEnvironmentBuilder() + .withOperationalEnvironmentId("testEnvironmentId") + .withOperationalEnvironmentName("testEnvironmentName") + .withOperationalEnvironmentType("testEnvironmentType") + .withOperationalEnvironmentStatus("testEnvironmentStatus") + .withTenantContext("testTenantContext") + .withWorkloadContext("testWorkloadContext") + .withResourceVersion("testResourceVersion") + .withRelationshipList(relationshipList) + .build(); + } } diff --git a/vid-app-common/src/test/java/org/onap/vid/asdc/parser/VidNotionsBuilderTest.java b/vid-app-common/src/test/java/org/onap/vid/asdc/parser/VidNotionsBuilderTest.java index edf7d0862..0f6f25c7b 100644 --- a/vid-app-common/src/test/java/org/onap/vid/asdc/parser/VidNotionsBuilderTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/asdc/parser/VidNotionsBuilderTest.java @@ -23,6 +23,7 @@ package org.onap.vid.asdc.parser; import static java.util.Collections.emptyList; import static java.util.Collections.emptyMap; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasProperty; import static org.hamcrest.Matchers.is; import static org.mockito.ArgumentMatchers.any; @@ -56,6 +57,7 @@ import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException; import org.onap.sdc.toscaparser.api.NodeTemplate; import org.onap.sdc.toscaparser.api.Property; import org.onap.sdc.toscaparser.api.elements.Metadata; +import org.onap.vid.asdc.parser.ToscaParserImpl2.Constants; import org.onap.vid.model.CR; import org.onap.vid.model.Network; import org.onap.vid.model.Node; @@ -72,6 +74,9 @@ import org.togglz.core.manager.FeatureManager; public class VidNotionsBuilderTest { + private static final String MACRO_SERVICE_INVARIANT_UUID = "2efab359-cdd4-4da2-9b79-61df990796c2"; + private static final String NOT_MACRO_SERVICE_INVARIANT_UUID = "5d854f6b-759c-4aa6-b472-7e4bb1c003d4"; + @InjectMocks VidNotionsBuilder vidNotionsBuilder; @@ -96,7 +101,7 @@ public class VidNotionsBuilderTest { public void VLNetworkWithPropertyNetworkTechnologyOVS_UIHintIsPositive() { ISdcCsarHelper csarHelper = mockForNonLegacyInstantiationUI(); - assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper, serviceModel), is(InstantiationUI.NETWORK_WITH_PROPERTY_NETWORK_TECHNOLOGY_EQUALS_STANDARD_SRIOV_OR_OVS)); + assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper, serviceModel, ModelCategory.OTHER, InstantiationType.ALaCarte), is(InstantiationUI.NETWORK_WITH_PROPERTY_NETWORK_TECHNOLOGY_EQUALS_STANDARD_SRIOV_OR_OVS)); assertThat(vidNotionsBuilder.suggestModelCategory(csarHelper, serviceModel) , is(ModelCategory.IS_5G_PROVIDER_NETWORK_MODEL)); } @@ -117,20 +122,87 @@ public class VidNotionsBuilderTest { } @DataProvider + public static Object[][] identifyInvariantFeatureFlagDataProvider() { + return new Object[][] { + {false, null, InstantiationType.ClientConfig}, + {false, mock(ServiceModel.class), InstantiationType.ClientConfig}, + {true, null, InstantiationType.ALaCarte}, + {true, mock(ServiceModel.class), InstantiationType.ALaCarte}, + }; + } + + @Test(dataProvider = "identifyInvariantFeatureFlagDataProvider") + public void whenCsarIsEmpty_suggestInstantiationType_byFeatureFlag( + boolean isFlagActive, ServiceModel serviceModel, InstantiationType expectedType) { + when(featureManagerMock.isActive(Features.FLAG_2002_IDENTIFY_INVARIANT_MACRO_UUID_BY_BACKEND)).thenReturn(isFlagActive); + if (serviceModel!=null) { + when(serviceModel.getService()).thenReturn(null); + } + assertEquals(expectedType, vidNotionsBuilder.suggestInstantiationType(serviceModel, null)); + } + + @DataProvider + public static Object[][] noMacroNoAlaCarteDataProvider() { + return new Object[][] { + {Constants.CLIENT_CONFIG}, + {"don't know you"}, + {null}, + }; + } + + @Test(dataProvider = "noMacroNoAlaCarteDataProvider") + public void givenNoMacroNorALaCarte_when_FLAG_2002_IDENTIFY_INVARIANT_MACRO_UUID_BY_BACKEND_isOff_then_suggestInstantiationType_ClientConfig(String instantiationType) { + ServiceModel serviceModel = mockServiceModelInstantiationTypeAndInvariant(MACRO_SERVICE_INVARIANT_UUID, instantiationType); + when(featureManagerMock.isActive(Features.FLAG_2002_IDENTIFY_INVARIANT_MACRO_UUID_BY_BACKEND)).thenReturn(false); + assertEquals(InstantiationType.ClientConfig , vidNotionsBuilder.suggestInstantiationType(serviceModel, null)); + } + + @NotNull + private ServiceModel mockServiceModelInstantiationTypeAndInvariant(String invariantUUID, String instantiationType) { + ServiceModel serviceModel = mock(ServiceModel.class); + Service service = mock(Service.class); + when(serviceModel.getService()).thenReturn(service); + when(service.getInstantiationType()).thenReturn(instantiationType); + when(service.getInvariantUuid()).thenReturn(invariantUUID); + return serviceModel; + } + + @DataProvider + public static Object[][] instantiationTypeByInvariantDataProvider() { + return new Object[][] { + {null, MACRO_SERVICE_INVARIANT_UUID, InstantiationType.Macro}, + {null, NOT_MACRO_SERVICE_INVARIANT_UUID, InstantiationType.ALaCarte}, + {Constants.CLIENT_CONFIG, MACRO_SERVICE_INVARIANT_UUID, InstantiationType.Macro}, + {Constants.BOTH, NOT_MACRO_SERVICE_INVARIANT_UUID, InstantiationType.ALaCarte}, + }; + } + + @Test(dataProvider = "instantiationTypeByInvariantDataProvider") + public void givenNoMacroNorALaCarte_givenFlagIsOn_suggestInstantiationTypeByInvariant( + String givenInstantiationType, String invariantUUID, InstantiationType expectedType + ) { + when(featureManagerMock.isActive(Features.FLAG_2002_IDENTIFY_INVARIANT_MACRO_UUID_BY_BACKEND)).thenReturn(true); + ServiceModel serviceModel = mockServiceModelInstantiationTypeAndInvariant(invariantUUID, givenInstantiationType); + assertEquals(expectedType, vidNotionsBuilder.suggestInstantiationType(serviceModel, null)); + } + + @DataProvider public static Object[][] anyAlacarteDataProvider() { return new Object[][] { - {"A-La-Carte", InstantiationUI.ANY_ALACARTE_NEW_UI}, - {"Macro", InstantiationUI.LEGACY}, + {InstantiationType.ALaCarte, InstantiationUI.ANY_ALACARTE_NEW_UI}, + {InstantiationType.Macro, InstantiationUI.LEGACY}, }; } @Test(dataProvider = "anyAlacarteDataProvider") - public void FLAG_EXP_ANY_ALACARTE_NEW_INSTANTIATION_UI_is_active_UIHintIsPositive(String instantiationType, InstantiationUI expectedInstantiationUI) { + public void FLAG_EXP_ANY_ALACARTE_NEW_INSTANTIATION_UI_is_active_UIHintIsPositive(InstantiationType instantiationType, InstantiationUI expectedInstantiationUI) { initServiceModelAndscarHelperWithMocks(); + String instantiationTypeAsString = instantiationType==InstantiationType.ALaCarte ? "A-La-Carte" : "Macro"; + when(featureManagerMock.isActive(Features.FLAG_EXP_ANY_ALACARTE_NEW_INSTANTIATION_UI)).thenReturn(true); when(csarHelper.getServiceMetadata()).thenReturn(new Metadata(ImmutableMap.of( - "instantiationType", instantiationType + "instantiationType", instantiationTypeAsString ))); NodeTemplate nodeTemplate = mock(NodeTemplate.class); @@ -141,7 +213,7 @@ public class VidNotionsBuilderTest { when(csarHelper.getServiceVlList()).thenReturn(ImmutableList.of(nodeTemplate)); - assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper, serviceModel), is(expectedInstantiationUI)); + assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper, serviceModel, ModelCategory.OTHER, instantiationType), is(expectedInstantiationUI)); } @Test @@ -157,7 +229,7 @@ public class VidNotionsBuilderTest { when(csarHelper.getServiceVlList()).thenReturn(ImmutableList.of(nodeTemplate)); - assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper, serviceModel), is(InstantiationUI.LEGACY)); + assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper, serviceModel, ModelCategory.OTHER, InstantiationType.ALaCarte), is(InstantiationUI.LEGACY)); assertThat(vidNotionsBuilder.suggestModelCategory(csarHelper, serviceModel) , is(ModelCategory.OTHER)); } @@ -167,7 +239,7 @@ public class VidNotionsBuilderTest { assertThat(vidNotionsBuilder.isALaCarte(csarHelper), is(false)); assertThat(vidNotionsBuilder.hasAnyNetworkWithPropertyEqualsToAnyOf(csarHelper, "unexpected_property_name"), is(false)); assertThat(vidNotionsBuilder.hasAnyNetworkWithPropertyEqualsToAnyOf(csarHelper, "network_technology","Standard-SR-IOV"), is(true)); - assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper, serviceModel), is(InstantiationUI.LEGACY)); + assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper, serviceModel, ModelCategory.OTHER, InstantiationType.ClientConfig), is(InstantiationUI.LEGACY)); } @Test @@ -175,7 +247,7 @@ public class VidNotionsBuilderTest { initServiceModelAndscarHelperWithRealCsar("/csars/service-fabric-configuration.zip"); assertThat(vidNotionsBuilder.isALaCarte(csarHelper), is(false)); assertThat(vidNotionsBuilder.hasFabricConfiguration(csarHelper), is(true)); - assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper, serviceModel), is(InstantiationUI.LEGACY)); + assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper, serviceModel, ModelCategory.OTHER, InstantiationType.ClientConfig), is(InstantiationUI.LEGACY)); } @Test(dataProvider = "trueAndFalse", dataProviderClass = TestUtils.class) @@ -185,7 +257,7 @@ public class VidNotionsBuilderTest { when(featureManagerMock.isActive(Features.FLAG_1908_TRANSPORT_SERVICE_NEW_INSTANTIATION_UI)).thenReturn(flagValue); assertThat(vidNotionsBuilder.isALaCarte(csarHelper), is(false)); - assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper, serviceModel), is(flagValue ? InstantiationUI.TRANSPORT_SERVICE : InstantiationUI.LEGACY)); + assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper, serviceModel, ModelCategory.OTHER, InstantiationType.ClientConfig), is(flagValue ? InstantiationUI.TRANSPORT_SERVICE : InstantiationUI.LEGACY)); assertThat(vidNotionsBuilder.suggestModelCategory(csarHelper, serviceModel), is(ModelCategory.Transport)); } @@ -193,10 +265,59 @@ public class VidNotionsBuilderTest { public void withoutMocks_givenZippedToscaFileOfInfraStructureVpn_InstantiationUIIsRight(boolean flagValue) throws SdcToscaParserException, IOException { initServiceModelAndscarHelperWithRealCsar("/csars/service-Infravpn-csar.zip"); when(featureManagerMock.isActive(Features.FLAG_1908_INFRASTRUCTURE_VPN)).thenReturn(flagValue); - assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper, serviceModel), is(flagValue ? InstantiationUI.INFRASTRUCTURE_VPN : InstantiationUI.LEGACY)); + assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper, serviceModel, ModelCategory.OTHER, InstantiationType.ClientConfig), is(flagValue ? InstantiationUI.INFRASTRUCTURE_VPN : InstantiationUI.LEGACY)); assertThat(vidNotionsBuilder.suggestModelCategory(csarHelper, serviceModel), is(ModelCategory.INFRASTRUCTURE_VPN)); } + @Test() + public void withoutMocks_givenToscaOfPortMirroring_InstantiationUIIsLegacyAndCategoryIsPortMirroring() throws SdcToscaParserException, IOException { + initServiceModelAndscarHelperWithRealCsar("/csars/portMirroringService.zip"); + when(featureManagerMock.isActive(Features.FLAG_2002_ANY_ALACARTE_BESIDES_EXCLUDED_NEW_INSTANTIATION_UI)).thenReturn(true); + assertThat(vidNotionsBuilder.buildVidNotions(csarHelper, serviceModel), + equalTo(new VidNotions(InstantiationUI.LEGACY, ModelCategory.PORT_MIRRORING, InstantiationUI.LEGACY, InstantiationType.ClientConfig))); + + } + + @Test() + public void withoutMocks_givenToscaOfVLanTagging_InstantiationUIIsLegacyAndCategoryIsVlanTagging() throws SdcToscaParserException, IOException { + initServiceModelAndscarHelperWithRealCsar("/csars/service-VdorotheaSrv-csar.zip"); + when(featureManagerMock.isActive(Features.FLAG_2002_ANY_ALACARTE_BESIDES_EXCLUDED_NEW_INSTANTIATION_UI)).thenReturn(true); + assertThat(vidNotionsBuilder.buildVidNotions(csarHelper, serviceModel), + equalTo(new VidNotions(InstantiationUI.LEGACY, ModelCategory.VLAN_TAGGING, InstantiationUI.LEGACY, InstantiationType.ALaCarte))); + } + + @Test + public void withoutMocks_givenToscaWithoutTypeAndFlagOn_InstantiationUIisAlacarte() + throws SdcToscaParserException, IOException { + initServiceModelAndscarHelperWithRealCsar("/csars/service-Vocg1804Svc.zip"); + when(featureManagerMock.isActive(Features.FLAG_2002_ANY_ALACARTE_BESIDES_EXCLUDED_NEW_INSTANTIATION_UI)).thenReturn(true); + assertThat(vidNotionsBuilder.buildVidNotions(csarHelper, serviceModel), + equalTo(new VidNotions( + InstantiationUI.ANY_ALACARTE_WHICH_NOT_EXCLUDED, + ModelCategory.OTHER, + InstantiationUI.LEGACY, + InstantiationType.ClientConfig))); + } + + @DataProvider + public static Object[][] anyAlaCarteDataProvider() { + return new Object[][] { + {true, InstantiationType.ALaCarte, InstantiationUI.ANY_ALACARTE_WHICH_NOT_EXCLUDED}, + {false, InstantiationType.ALaCarte, InstantiationUI.LEGACY}, + {true, InstantiationType.Macro, InstantiationUI.LEGACY}, + {true, InstantiationType.ClientConfig, InstantiationUI.ANY_ALACARTE_WHICH_NOT_EXCLUDED}, + {true, null, InstantiationUI.ANY_ALACARTE_WHICH_NOT_EXCLUDED}, + }; + } + + @Test(dataProvider = "anyAlaCarteDataProvider") + public void testAnyAlaCarteNewUI_byInstantiationTypeAndFeatureFlag(boolean flag, InstantiationType instantiationType, InstantiationUI expected) { + initServiceModelAndscarHelperWithMocks(); + //mockInstantiationType(serviceModel, instantiationType); + when(featureManagerMock.isActive(Features.FLAG_2002_ANY_ALACARTE_BESIDES_EXCLUDED_NEW_INSTANTIATION_UI)).thenReturn(flag); + assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper, serviceModel, ModelCategory.OTHER, instantiationType), is(expected)); + } + @Test public void uuidIsExactly1ffce89fEtc_UIHintIsPositive() { initServiceModelAndscarHelperWithMocks(); @@ -205,7 +326,7 @@ public class VidNotionsBuilderTest { "UUID", "95eb2c44-bff2-4e8b-ad5d-8266870b7717" ))); when(featureManagerMock.isActive(Features.FLAG_5G_IN_NEW_INSTANTIATION_UI)).thenReturn(true); - assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper, serviceModel), is(InstantiationUI.SERVICE_UUID_IS_1ffce89f_ef3f_4cbb_8b37_82134590c5de)); + assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper, serviceModel, ModelCategory.OTHER, InstantiationType.ClientConfig), is(InstantiationUI.SERVICE_UUID_IS_1ffce89f_ef3f_4cbb_8b37_82134590c5de)); } @Test(dataProvider = "trueAndFalse", dataProviderClass = TestUtils.class) @@ -216,6 +337,12 @@ public class VidNotionsBuilderTest { assertThat(vidNotionsBuilder.buildVidNotions(csarHelper, serviceModel), hasProperty("instantiationUI", is(InstantiationUI.LEGACY))); } + private void mockInstantiationType(ServiceModel serviceModel, String instantiationType) { + Service mockService = mock(Service.class); + when(serviceModel.getService()).thenReturn(mockService); + when(mockService.getInstantiationType()).thenReturn(instantiationType); + } + @DataProvider public static Object[][] ServiceRoleTypesDataProvider() { return new Object[][] { @@ -232,7 +359,7 @@ public class VidNotionsBuilderTest { "serviceRole", serviceRole ))); - assertThat(vidNotionsBuilder.suggestViewEditUI(csarHelper, serviceModel), is(expectedViewEditUI)); + assertThat(vidNotionsBuilder.suggestViewEditUI(csarHelper, serviceModel, ModelCategory.OTHER, InstantiationType.ClientConfig), is(expectedViewEditUI)); } @DataProvider @@ -256,11 +383,9 @@ public class VidNotionsBuilderTest { when(featureManagerMock.isActive(Features.FLAG_1902_NEW_VIEW_EDIT)).thenReturn(isFlag1902NewViewEdit); ServiceModel serviceModel = mock(ServiceModel.class); - Service service = mock(Service.class); - when(serviceModel.getService()).thenReturn(service); - when(service.getInstantiationType()).thenReturn(ToscaParserImpl2.Constants.A_LA_CARTE); + mockInstantiationType(serviceModel, Constants.A_LA_CARTE); - InstantiationUI result = vidNotionsBuilder.suggestViewEditUI(csarHelper, serviceModel); + InstantiationUI result = vidNotionsBuilder.suggestViewEditUI(csarHelper, serviceModel, ModelCategory.OTHER, InstantiationType.ClientConfig); assertEquals(expectedViewEditUi, result); } @@ -302,9 +427,7 @@ public class VidNotionsBuilderTest { @Test(dataProvider="toscaParserInstantiationTypeToVidNotion") public void testSuggestInstantiationTypeWhenInstantiationUiLegacy(String toscaParserInstantiationType, InstantiationType expectedInstantiationType) { ServiceModel serviceModel = mock(ServiceModel.class); - Service service = mock(Service.class); - when(serviceModel.getService()).thenReturn(service); - when(service.getInstantiationType()).thenReturn(toscaParserInstantiationType); + mockInstantiationType(serviceModel, toscaParserInstantiationType); assertEquals(expectedInstantiationType, vidNotionsBuilder.suggestInstantiationType(serviceModel, ModelCategory.OTHER)); } @@ -326,9 +449,7 @@ public class VidNotionsBuilderTest { boolean isFeatureOn, InstantiationType expectedInstantiationType) { ServiceModel serviceModel = mock(ServiceModel.class); - Service service = mock(Service.class); - when(serviceModel.getService()).thenReturn(service); - when(service.getInstantiationType()).thenReturn(ToscaParserImpl2.Constants.A_LA_CARTE); + mockInstantiationType(serviceModel, Constants.A_LA_CARTE); when(featureManagerMock.isActive(featureFlag)).thenReturn(isFeatureOn); assertEquals(expectedInstantiationType, vidNotionsBuilder.suggestInstantiationType(serviceModel, instantiationUI)); } @@ -378,9 +499,7 @@ public class VidNotionsBuilderTest { @Test public void whenInstantiationTypeInServiceModelIsNull_thenInstantiationTypeIsClientConfig() { initServiceModelAndscarHelperWithMocks(); - Service service = mock(Service.class); - when(serviceModel.getService()).thenReturn(service); - when(service.getInstantiationType()).thenReturn(null); + mockInstantiationType(serviceModel, null); assertEquals( InstantiationType.ClientConfig, vidNotionsBuilder.suggestInstantiationType(serviceModel, ModelCategory.OTHER)); } @@ -420,7 +539,7 @@ public class VidNotionsBuilderTest { emptyMap() : ImmutableMap.of(ToscaParserImpl2.Constants.SERVICE_ROLE, serviceRole) )); - assertEquals(expectedViewEditUi, vidNotionsBuilder.suggestInstantiationUI(csarHelper, serviceModel)); + assertEquals(expectedViewEditUi, vidNotionsBuilder.suggestInstantiationUI(csarHelper, serviceModel, ModelCategory.OTHER, InstantiationType.ALaCarte)); } private static NodeTemplate mockNodeTemplateChild(boolean withFabricConfiguration) { @@ -474,14 +593,32 @@ public class VidNotionsBuilderTest { initServiceModelAndscarHelperWithMocks(); Service service = mock(Service.class); - String instantiationType = isMacro ? ToscaParserImpl2.Constants.MACRO : ToscaParserImpl2.Constants.A_LA_CARTE; + InstantiationType instantiationType = isMacro ? InstantiationType.Macro : InstantiationType.ALaCarte; when(serviceModel.getService()).thenReturn(service); - when(service.getInstantiationType()).thenReturn(instantiationType); when(featureManagerMock.isActive(Features.FLAG_1908_MACRO_NOT_TRANSPORT_NEW_VIEW_EDIT)).thenReturn(flagActive); when(featureManagerMock.isActive(Features.FLAG_1902_NEW_VIEW_EDIT)).thenReturn(false); when(csarHelper.getServiceMetadata()).thenReturn(new Metadata(isTransport ? ImmutableMap.of(ToscaParserImpl2.Constants.SERVICE_TYPE, "TRANSPORT") : emptyMap() )); - assertEquals(expectedViewEditUi, vidNotionsBuilder.suggestViewEditUI(csarHelper, serviceModel)); + assertEquals(expectedViewEditUi, vidNotionsBuilder.suggestViewEditUI(csarHelper, serviceModel, ModelCategory.OTHER, instantiationType)); + } + + @DataProvider + public static Object[][] invariantUuidToMacroDataProvider() { + return new Object[][]{ + {"117f5f1a-1b47-4ae1-ae04-489c9a7ada28", true}, + {"117F5f1a-1b47-4AE1-ae04-489C9A7ada28", true}, + {MACRO_SERVICE_INVARIANT_UUID, true}, + {"67e09a1f-9e42-4b63-8dee-bc60bae50de1", false}, + {"67e09A1F-9E42-4b63-8Dee-bc60bae50de1", false}, + {NOT_MACRO_SERVICE_INVARIANT_UUID, false}, + {"I'm not a uuid", false}, + {null, false}, + }; + } + + @Test(dataProvider = "invariantUuidToMacroDataProvider") + public void testIsMacroByInvariantUuid(String uuid, boolean expectedIsMacro) { + assertEquals(expectedIsMacro, vidNotionsBuilder.isMacroByInvariantUuid(uuid)); } } diff --git a/vid-app-common/src/test/java/org/onap/vid/client/SyncRestClientForHttpServerTest.java b/vid-app-common/src/test/java/org/onap/vid/client/SyncRestClientForHttpServerTest.java index 5a2eb59d2..bf33eff94 100644 --- a/vid-app-common/src/test/java/org/onap/vid/client/SyncRestClientForHttpServerTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/client/SyncRestClientForHttpServerTest.java @@ -42,10 +42,13 @@ import com.xebialabs.restito.semantics.Condition; import com.xebialabs.restito.server.StubServer; import io.joshworks.restclient.http.HttpResponse; import io.joshworks.restclient.http.JsonNode; +import java.net.URI; +import java.net.URISyntaxException; import java.util.Collections; import java.util.Map; import org.glassfish.grizzly.http.Method; import org.glassfish.grizzly.http.util.HttpStatus; +import org.jetbrains.annotations.NotNull; import org.onap.vid.utils.Logging; import org.springframework.http.HttpMethod; import org.testng.annotations.AfterMethod; @@ -76,11 +79,20 @@ public class SyncRestClientForHttpServerTest { syncRestClient.destroy(); } + @NotNull + private String getTestUrl(String protocol) { + try { + return new URI(protocol, null, "127.0.0.1" , stubServer.getPort(), "/test", null, null).toString(); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + } + @Test public void testJsonResponseFromGet() throws JsonProcessingException { // given stubGetCall(); - String url = "http://0.0.0.0:" + stubServer.getPort() + "/test"; + String url = getTestUrl("http"); // when HttpResponse<JsonNode> jsonNodeHttpResponse = syncRestClient .get(url, Collections.emptyMap(), Collections.emptyMap()); @@ -97,7 +109,7 @@ public class SyncRestClientForHttpServerTest { public void testObjectResponseFromGet() throws JsonProcessingException { // given stubGetCall(); - String url = "http://0.0.0.0:" + stubServer.getPort() + "/test"; + String url = getTestUrl("http"); // when HttpResponse<SyncRestClientModel.TestModel> testModelHttpResponse = syncRestClient .get(url, Collections.emptyMap(), Collections.emptyMap(), SyncRestClientModel.TestModel.class); @@ -114,7 +126,7 @@ public class SyncRestClientForHttpServerTest { public void testJsonResponseFromPost() throws JsonProcessingException { // given stubPostCall(); - String url = "http://0.0.0.0:" + stubServer.getPort() + "/test"; + String url = getTestUrl("http"); // when HttpResponse<JsonNode> jsonNodeHttpResponse = syncRestClient.post(url, Collections.emptyMap(), testObject); // then @@ -130,7 +142,7 @@ public class SyncRestClientForHttpServerTest { public void test404JsonResponseFromPost() throws JsonProcessingException { // given stubPostCall(); - String url = "http://0.0.0.0:" + stubServer.getPort() + "/test"; + String url = getTestUrl("http"); // when HttpResponse<JsonNode> jsonNodeHttpResponse = syncRestClient .post(url, Collections.emptyMap(), NOT_EXISTING_OBJECT); @@ -146,7 +158,7 @@ public class SyncRestClientForHttpServerTest { // given stubPostCall(); Map headers = ImmutableMap.<String, String>builder().put("Authorization", "Basic anyHash").build(); - String url = "http://0.0.0.0:" + stubServer.getPort() + "/test"; + String url = getTestUrl("http"); // when HttpResponse<JsonNode> jsonNodeHttpResponse = syncRestClient.post(url, headers, testObject); // then @@ -160,7 +172,7 @@ public class SyncRestClientForHttpServerTest { public void testFailedJsonResponseFromPost() throws JsonProcessingException { // given stubPostCall(); - String url = "http://0.0.0.0:" + stubServer.getPort() + "/test"; + String url = getTestUrl("http"); // when stubServer.stop(); syncRestClient.post(url, Collections.emptyMap(), testObject); @@ -170,7 +182,7 @@ public class SyncRestClientForHttpServerTest { public void testObjectResponseFromPost() throws JsonProcessingException { // given stubPostCall(); - String url = "http://0.0.0.0:" + stubServer.getPort() + "/test"; + String url = getTestUrl("http"); // when HttpResponse<SyncRestClientModel.TestModel> objectHttpResponse = syncRestClient .post(url, Collections.emptyMap(), testObject, SyncRestClientModel.TestModel.class); @@ -187,7 +199,7 @@ public class SyncRestClientForHttpServerTest { public void testJsonResponseFromPut() throws JsonProcessingException { // given stubPutCall(); - String url = "http://0.0.0.0:" + stubServer.getPort() + "/test"; + String url = getTestUrl("http"); // when HttpResponse<JsonNode> jsonNodeHttpResponse = syncRestClient.put(url, Collections.emptyMap(), testObject); // then @@ -203,7 +215,7 @@ public class SyncRestClientForHttpServerTest { public void testObjectResponseFromPut() throws JsonProcessingException { // given stubPutCall(); - String url = "http://0.0.0.0:" + stubServer.getPort() + "/test"; + String url = getTestUrl("http"); // when HttpResponse<SyncRestClientModel.TestModel> modelHttpResponse = syncRestClient .put(url, Collections.emptyMap(), testObject, SyncRestClientModel.TestModel.class); @@ -220,7 +232,7 @@ public class SyncRestClientForHttpServerTest { public void testJsonResponseFromDelete() throws JsonProcessingException { // given stubDeleteCall(); - String url = "http://0.0.0.0:" + stubServer.getPort() + "/test"; + String url = getTestUrl("http"); // when HttpResponse<JsonNode> jsonNodeHttpResponse = syncRestClient.delete(url, Collections.emptyMap()); // then @@ -236,7 +248,7 @@ public class SyncRestClientForHttpServerTest { public void testObjectResponseFromDelete() throws JsonProcessingException { // given stubDeleteCall(); - String url = "http://0.0.0.0:" + stubServer.getPort() + "/test"; + String url = getTestUrl("http"); // when HttpResponse<SyncRestClientModel.TestModel> modelHttpResponse = syncRestClient .delete(url, Collections.emptyMap(), SyncRestClientModel.TestModel.class); @@ -253,8 +265,8 @@ public class SyncRestClientForHttpServerTest { public void testRedirectToHttp() throws JsonProcessingException { // given stubGetCall(); - String secured_url = "https://0.0.0.0:" + stubServer.getPort() + "/test"; - String available_url = "http://0.0.0.0:" + stubServer.getPort() + "/test"; + String secured_url = getTestUrl("https");; + String available_url = getTestUrl("http"); // when HttpResponse<JsonNode> jsonNodeHttpResponse = syncRestClient .get(secured_url, Collections.emptyMap(), Collections.emptyMap()); diff --git a/vid-app-common/src/test/java/org/onap/vid/client/SyncRestClientForHttpsServerTest.java b/vid-app-common/src/test/java/org/onap/vid/client/SyncRestClientForHttpsServerTest.java index 645b5eac0..27cd81e70 100644 --- a/vid-app-common/src/test/java/org/onap/vid/client/SyncRestClientForHttpsServerTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/client/SyncRestClientForHttpsServerTest.java @@ -42,8 +42,8 @@ import com.xebialabs.restito.semantics.Condition; import com.xebialabs.restito.server.StubServer; import io.joshworks.restclient.http.HttpResponse; import io.joshworks.restclient.http.JsonNode; - -import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.KeyStoreException; @@ -55,13 +55,13 @@ import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; - import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.ssl.SSLContextBuilder; import org.glassfish.grizzly.http.Method; +import org.jetbrains.annotations.NotNull; import org.onap.vid.utils.Logging; import org.springframework.http.HttpMethod; import org.testng.annotations.AfterMethod; @@ -91,12 +91,21 @@ public class SyncRestClientForHttpsServerTest { stubServer.stop(); } + @NotNull + private String getTestUrl(String protocol) { + try { + return new URI(protocol, null, "127.0.0.1" , stubServer.getPort(), "/test", null, null).toString(); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + } + @Test public void testJsonResponseFromGet() throws JsonProcessingException { // given stubGetCall(); - String securedUrl = "https://0.0.0.0:" + stubServer.getPort() + "/test"; - String notSecuredUrl = "http://0.0.0.0:" + stubServer.getPort() + "/test"; + String securedUrl = getTestUrl("https"); + String notSecuredUrl = getTestUrl("http"); // when HttpResponse<JsonNode> jsonNodeHttpResponse = syncRestClient .get(securedUrl, Collections.emptyMap(), Collections.emptyMap()); @@ -115,8 +124,8 @@ public class SyncRestClientForHttpsServerTest { // given stubServer.run(); stubGetCall(); - String securedUrl = "https://0.0.0.0:" + stubServer.getPort() + "/test"; - String notSecuredUrl = "http://0.0.0.0:" + stubServer.getPort() + "/test"; + String securedUrl = getTestUrl("https"); + String notSecuredUrl = getTestUrl("http"); // when HttpResponse<SyncRestClientModel.TestModel> testModelHttpResponse = syncRestClient .get(securedUrl, Collections.emptyMap(), Collections.emptyMap(), SyncRestClientModel.TestModel.class); diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/AaiControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/AaiControllerTest.java index 51bdec882..521102383 100644 --- a/vid-app-common/src/test/java/org/onap/vid/controller/AaiControllerTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/controller/AaiControllerTest.java @@ -57,8 +57,10 @@ import org.onap.vid.aai.AaiResponseTranslator; import org.onap.vid.aai.AaiResponseTranslator.PortMirroringConfigData; import org.onap.vid.aai.AaiResponseTranslator.PortMirroringConfigDataError; import org.onap.vid.aai.AaiResponseTranslator.PortMirroringConfigDataOk; +import org.onap.vid.aai.OperationalEnvironment; import org.onap.vid.aai.model.AaiGetAicZone.AicZones; import org.onap.vid.aai.model.AaiGetAicZone.Zone; +import org.onap.vid.aai.model.AaiGetOperationalEnvironments.OperationalEnvironmentList; import org.onap.vid.aai.model.AaiGetPnfs.Pnf; import org.onap.vid.aai.model.PortDetailsTranslator.PortDetails; import org.onap.vid.aai.model.PortDetailsTranslator.PortDetailsError; @@ -561,5 +563,27 @@ public class AaiControllerTest { .andExpect(content().string(expectedResponse)); } + @Test + public void getOperationalEnvironments_shouldReturnOkResponse() throws Exception { + String operationalEnvironmentType = "testEnvType"; + String operationalEnvironmentStatus = "testEnvStatus"; + OperationalEnvironmentList operationalEnvironmentList = new OperationalEnvironmentList( + ImmutableList.of(OperationalEnvironment.builder() + .withOperationalEnvironmentType(operationalEnvironmentType) + .withOperationalEnvironmentStatus(operationalEnvironmentStatus) + .build())); + AaiResponse<OperationalEnvironmentList> aaiResponse = new AaiResponse<>(operationalEnvironmentList, null, + HttpStatus.OK.value()); + given(aaiService.getOperationalEnvironments(operationalEnvironmentType, operationalEnvironmentStatus)) + .willReturn(aaiResponse); + + mockMvc.perform(get("/get_operational_environments") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .param("operationalEnvironmentType", operationalEnvironmentType) + .param("operationalEnvironmentStatus", operationalEnvironmentStatus)) + .andExpect(status().isOk()) + .andExpect(content().json(objectMapper.writeValueAsString(aaiResponse))); + } } diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/LocalWebConfig.java b/vid-app-common/src/test/java/org/onap/vid/controller/LocalWebConfig.java index fcc314a3c..681f9d1ab 100644 --- a/vid-app-common/src/test/java/org/onap/vid/controller/LocalWebConfig.java +++ b/vid-app-common/src/test/java/org/onap/vid/controller/LocalWebConfig.java @@ -40,7 +40,6 @@ import org.onap.vid.asdc.AsdcClient; import org.onap.vid.asdc.parser.ToscaParserImpl2; import org.onap.vid.asdc.parser.VidNotionsBuilder; import org.onap.vid.services.AAIServiceTree; -import org.onap.vid.services.AAITreeNodeBuilder; import org.onap.vid.services.AaiService; import org.onap.vid.services.AaiServiceImpl; import org.onap.vid.services.VidService; @@ -72,8 +71,8 @@ public class LocalWebConfig { @Bean public AaiService getAaiService(AaiClientInterface aaiClient, AaiResponseTranslator aaiResponseTranslator, - AAITreeNodeBuilder aaiTreeNode, AAIServiceTree aaiServiceTree, ExecutorService executorService) { - return new AaiServiceImpl(aaiClient, aaiResponseTranslator, aaiServiceTree, executorService); + AAIServiceTree aaiServiceTree, Logging logging, ExecutorService executorService) { + return new AaiServiceImpl(aaiClient, aaiResponseTranslator, aaiServiceTree, executorService, logging); } @Bean diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/LoggerControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/LoggerControllerTest.java index fdc0f44d1..f0d840929 100644 --- a/vid-app-common/src/test/java/org/onap/vid/controller/LoggerControllerTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/controller/LoggerControllerTest.java @@ -108,4 +108,19 @@ public class LoggerControllerTest { .andExpect(content().string("")) .andExpect(status().isOk()); } + + @Test + public void shouldReturnEmptyString_whenDebugLogFileIsEmpty() throws Exception { + List<Role> list = ImmutableList.of(new Role(EcompRole.READ, "subName1", "servType1", "tenant1")); + + given(provider.getUserRoles(argThat(req -> req.getRequestedSessionId().equals("id1")))).willReturn(list); + given(provider.userPermissionIsReadLogs(list)).willReturn(true); + given(creator.getLogfilePath("debug")).willReturn(EMPTY_LOG_PATH); + + mockMvc.perform(get("/logger/debug") + .with(req -> {req.setRequestedSessionId("id1"); + return req;})) + .andExpect(content().string("")) + .andExpect(status().isOk()); + } } diff --git a/vid-app-common/src/test/java/org/onap/vid/dal/AsyncInstantiationRepositoryTest.java b/vid-app-common/src/test/java/org/onap/vid/dal/AsyncInstantiationRepositoryTest.java index be5a44e82..012c37f4d 100644 --- a/vid-app-common/src/test/java/org/onap/vid/dal/AsyncInstantiationRepositoryTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/dal/AsyncInstantiationRepositoryTest.java @@ -20,18 +20,23 @@ package org.onap.vid.dal; +import static java.util.stream.Collectors.toList; import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals; import static net.javacrumbs.jsonunit.core.Option.IGNORING_ARRAY_ORDER; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.is; import static org.hamcrest.collection.IsCollectionWithSize.hasSize; import static org.hamcrest.core.IsEqual.equalTo; +import static org.onap.vid.job.Job.JobStatus.COMPLETED; import com.google.common.collect.ImmutableList; +import java.time.LocalDateTime; import java.time.ZonedDateTime; import java.util.List; import java.util.Map; import java.util.UUID; -import java.util.stream.Collectors; import javax.inject.Inject; import org.onap.portalsdk.core.service.DataAccessService; import org.onap.portalsdk.core.util.SystemProperties; @@ -39,6 +44,7 @@ import org.onap.vid.config.DataSourceConfig; import org.onap.vid.config.MockedAaiClientAndFeatureManagerConfig; import org.onap.vid.job.Job; import org.onap.vid.model.ResourceInfo; +import org.onap.vid.model.ServiceInfo; import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; import org.onap.vid.mso.rest.AsyncRequestStatus; import org.onap.vid.mso.rest.RequestStatus; @@ -46,6 +52,7 @@ import org.onap.vid.services.AsyncInstantiationBaseTest; import org.onap.vid.utils.TimeUtils; import org.springframework.test.context.ContextConfiguration; import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @ContextConfiguration(classes = {DataSourceConfig.class, SystemProperties.class, MockedAaiClientAndFeatureManagerConfig.class}) @@ -53,19 +60,56 @@ public class AsyncInstantiationRepositoryTest extends AsyncInstantiationBaseTest @Inject private DataAccessService dataAccessService; + private AsyncInstantiationRepository asyncInstantiationRepository; @BeforeClass void initServicesInfoService() { + asyncInstantiationRepository = new AsyncInstantiationRepository(dataAccessService); createInstanceParamsMaps(); + createNewTestServicesInfoWithServiceModelID(); + } + + private void createNewTestServicesInfoWithServiceModelID() { + + LocalDateTime NOW = LocalDateTime.now(); + + addNewServiceInfo(UUID.randomUUID(), "abc", "1", NOW.minusYears(1L), NOW, COMPLETED, false, false, + MODEL_UUID); + addNewServiceInfo(UUID.randomUUID(), "abc", "2", NOW, NOW, COMPLETED, false, false, + MODEL_UUID_2); + addNewServiceInfo(UUID.randomUUID(), "abc", "3", NOW, NOW, COMPLETED, false, false, + MODEL_UUID); + addNewServiceInfo(UUID.randomUUID(), "abc", "hidden", NOW, NOW, COMPLETED, true, false, + MODEL_UUID); + } + + @DataProvider + public static Object[][] listServicesByServiceModelIdDataProvider() { + return new Object[][]{ + { "services info filtered by MODEL_UUID not hidden , ordered by newer first", MODEL_UUID, "3", "1" }, + { "services info filtered by MODEL_UUID2", MODEL_UUID_2, "2" }, + }; + } + + @Test(dataProvider = "listServicesByServiceModelIdDataProvider") + public void testListServicesByServiceModelId(String desc, String modelUUID, String... expectedResult) { + List<ServiceInfo> serviceInfoListResult = asyncInstantiationRepository.listServicesByServiceModelId(UUID.fromString(modelUUID)); + assertThat(desc, serviceInfoListResult.stream().map(ServiceInfo::getServiceInstanceName).collect(toList()), + contains(expectedResult)); + } + + @Test + public void whenFilterServiceByNotExistUUID_emptyListIsReturned() { + List<ServiceInfo> serviceInfoListResult = asyncInstantiationRepository.listServicesByServiceModelId(UUID.randomUUID()); + assertThat(serviceInfoListResult, is(empty())); } @Test public void whenSaveNewRequest_thenRequestIsRetrieved() { - AsyncInstantiationRepository underTest = new AsyncInstantiationRepository(dataAccessService); ServiceInstantiation serviceInstantiation = generateALaCarteWithVnfsServiceInstantiationPayload(); UUID jobUuid = UUID.randomUUID(); - underTest.addJobRequest(jobUuid, serviceInstantiation); - ServiceInstantiation stored = underTest.getJobRequest(jobUuid); + asyncInstantiationRepository.addJobRequest(jobUuid, serviceInstantiation); + ServiceInstantiation stored = asyncInstantiationRepository.getJobRequest(jobUuid); assertThat(stored, jsonEquals(serviceInstantiation).when(IGNORING_ARRAY_ORDER)); } @@ -77,7 +121,6 @@ public class AsyncInstantiationRepositoryTest extends AsyncInstantiationBaseTest @Test public void getResourceInfoByRootJobId_returnsMapOfjobIdResources(){ - AsyncInstantiationRepository underTest = new AsyncInstantiationRepository(dataAccessService); UUID jobId1= UUID.randomUUID(); UUID jobId2= UUID.randomUUID(); AsyncRequestStatus errorMessage= createAsyncRequestStatus("MSO failed resource", "FAILED"); @@ -90,14 +133,16 @@ public class AsyncInstantiationRepositoryTest extends AsyncInstantiationBaseTest new ResourceInfo("ffffff",jobId2, "66f3123a-f9a8-4591-b481-ghfgh6767567", Job.JobStatus.COMPLETED, null) ); for(ResourceInfo info: requestInfoList){ - underTest.saveResourceInfo(info); + asyncInstantiationRepository.saveResourceInfo(info); } - Map<String, ResourceInfo> storedByTrackId = underTest.getResourceInfoByRootJobId(jobId1); + Map<String, ResourceInfo> storedByTrackId = asyncInstantiationRepository.getResourceInfoByRootJobId(jobId1); assertThat(storedByTrackId.values(), hasSize(4)); assertThat(storedByTrackId.get("aaaaaa").getInstanceId(), equalTo("64f3123a-f9a8-4591-b481-d662134bcb52")); assertThat(storedByTrackId.get("cccccc").getErrorMessage().request.requestStatus.getStatusMessage(), equalTo("MSO failed resource")); assertThat(storedByTrackId.get("cccccc").getErrorMessage().request.requestStatus.getRequestState(), equalTo("FAILED")); assertThat(storedByTrackId.get("dddddd").getErrorMessage(), equalTo(null)); - assertThat(storedByTrackId.values(), jsonEquals(requestInfoList.stream().filter(i-> i.getRootJobId().equals(jobId1)).collect(Collectors.toList())).when(IGNORING_ARRAY_ORDER)); + assertThat(storedByTrackId.values(), + jsonEquals(requestInfoList.stream().filter(i -> i.getRootJobId().equals(jobId1)).collect( + toList())).when(IGNORING_ARRAY_ORDER)); } } diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceCommandTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceCommandTest.java index 986f5d0f5..db856d757 100644 --- a/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceCommandTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceCommandTest.java @@ -319,8 +319,8 @@ public class ResourceCommandTest { } static VfModule createVfModule(Action action) { - return new VfModule(mock(ModelInfo.class), null, null, action.toString(), null, null, null, null, null, false, false, null, null, null, null, - null); + return new VfModule(mock(ModelInfo.class), null, null, action.toString(), null, null, null, null, null, + false, false, null, null, null, null, null, null, null); } static Network createNetwork(Action action) { diff --git a/vid-app-common/src/test/java/org/onap/vid/logging/VidLoggingInterceptorTest.java b/vid-app-common/src/test/java/org/onap/vid/logging/VidLoggingInterceptorTest.java index fc78ed714..c31d00df8 100644 --- a/vid-app-common/src/test/java/org/onap/vid/logging/VidLoggingInterceptorTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/logging/VidLoggingInterceptorTest.java @@ -20,10 +20,22 @@ package org.onap.vid.logging; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import static org.onap.vid.logging.VidLoggingInterceptor.INBOUND_INVO_ID; import static org.testng.Assert.assertEquals; +import static org.testng.AssertJUnit.assertNull; +import java.util.HashMap; +import javax.servlet.http.HttpServletRequest; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.logging.filter.base.SimpleHashMap; +import org.onap.logging.filter.base.SimpleMap; import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs; +import org.onap.vid.controller.ControllersUtils; import org.slf4j.MDC; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @@ -32,17 +44,58 @@ public class VidLoggingInterceptorTest { private VidLoggingInterceptor interceptor; + @Mock + private ControllersUtils controllersUtils; + @BeforeMethod public void setup() { - interceptor = new VidLoggingInterceptor(); + MockitoAnnotations.initMocks(this); + interceptor = new VidLoggingInterceptor(controllersUtils); MDC.clear(); } @Test public void testAdditionalPreHandling() { - MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, "987"); - interceptor.additionalPreHandling(null); - assertEquals(MDC.get(INBOUND_INVO_ID), "987"); + + //given + final String invoID = "987"; + MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invoID); + MDC.put(MDCs.PARTNER_NAME, "wrongPartnerName"); + final String myUserId = "myUserId"; + when(controllersUtils.extractUserId(any(HttpServletRequest.class))) + .thenReturn(myUserId); + + //when + interceptor.additionalPreHandling(mock(HttpServletRequest.class)); + + //then + assertEquals(MDC.get(INBOUND_INVO_ID), invoID); + assertEquals(MDC.get(MDCs.PARTNER_NAME), myUserId); + } + + @Test + public void whenNoUserId_previousPartnerNameIsPreserved() { + //given + final String prevPartnerName = "prevPartnerName"; + MDC.put(MDCs.PARTNER_NAME, prevPartnerName); + final HttpServletRequest mockedRequest = mock(HttpServletRequest.class); + when(controllersUtils.extractUserId(any(HttpServletRequest.class))) + .thenReturn(""); + + //when + interceptor.additionalPreHandling(mockedRequest); + + //then + assertEquals(MDC.get(MDCs.PARTNER_NAME), prevPartnerName); + + } + + @Test + public void givenNotValidAuthorizationHeader_whenGetBasicAuthUserName_noExceptionIsThrown() { + HashMap<String, String> hashMap = new HashMap<>(); + hashMap.put("Authorization","abcdefghi"); + SimpleMap headers = new SimpleHashMap(hashMap); + assertNull(interceptor.getBasicAuthUserName(headers)); } } diff --git a/vid-app-common/src/test/java/org/onap/vid/model/ModelUtilTest.java b/vid-app-common/src/test/java/org/onap/vid/model/ModelUtilTest.java index 0dd6e32a9..922a59200 100644 --- a/vid-app-common/src/test/java/org/onap/vid/model/ModelUtilTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/model/ModelUtilTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,49 +20,81 @@ package org.onap.vid.model; -import org.junit.Assert; -import org.junit.Test; +import static java.util.Collections.emptyMap; +import static java.util.function.Function.identity; +import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.anEmptyMap; + +import com.google.common.collect.ImmutableMap; +import java.util.Map; +import org.onap.vid.mso.model.ModelInfo; +import org.testng.annotations.Test; public class ModelUtilTest { - private ModelUtil createTestSubject() { - return new ModelUtil(); - } + private final ModelUtil testSubject = new ModelUtil(); + + private ModelInfo modelWithCustomizationId(String id) { + ModelInfo result = new ModelInfo(); + result.setModelCustomizationId(id); + return result; + } + + private ModelInfo modelWithModelVersionId(String id) { + ModelInfo result = new ModelInfo(); + result.setModelVersionId(id); + return result; + } - - @Test - public void testGetTags() throws Exception { - String[] namespaces; - String constantValue = "test"; - String[] result; + private ModelInfo modelWithNullValues() { + return new ModelInfo(); + } - // test 1 - namespaces = null; - result = ModelUtil.getTags(namespaces, constantValue); - Assert.assertNull(result); + @Test + public void getExistingCounterMap_trivialCase() { + Map<String, Long> existingCounterMap = + testSubject.getExistingCounterMap( + ImmutableMap.of( + "a", modelWithCustomizationId("model_1"), + "b", modelWithCustomizationId("model_1"), + "c", modelWithCustomizationId("model_2") + ), + identity() + ); - // test 2 - namespaces = new String[] { "" }; - result = ModelUtil.getTags(namespaces, constantValue); - Assert.assertArrayEquals(new String[] { constantValue }, result); - } + assertThat(existingCounterMap, jsonEquals(ImmutableMap.of( + "model_1", 2, + "model_2", 1 + ))); + } - - @Test - public void testIsType() throws Exception { - String type = "a"; - String[] tags; - boolean result; + @Test + public void getExistingCounterMap_givenMixOfIdsAndNulls_resultContainsIdsAndOmitsNulls() { + Map<String, Long> existingCounterMap = + testSubject.getExistingCounterMap( + ImmutableMap.of( + "a", modelWithCustomizationId("model_1"), + "b", modelWithModelVersionId("model_1"), + "c", modelWithModelVersionId("model_2"), + "d", modelWithNullValues() + ), + identity() + ); - // test 1 - tags = null; - result = ModelUtil.isType(type, tags); - Assert.assertEquals(false, result); + assertThat(existingCounterMap, jsonEquals(ImmutableMap.of( + "model_1", 2, + "model_2", 1 + ))); + } - // test 2 - tags = new String[] { "a" }; - result = ModelUtil.isType(type, tags); - Assert.assertEquals(true, result); - } + @Test + public void getExistingCounterMap_handleEmptyCollections() { + assertThat(testSubject.getExistingCounterMap( + emptyMap(), + any -> modelWithCustomizationId("foo") + ), is(anEmptyMap())); + } } diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AAIServiceIntegrativeTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AAIServiceIntegrativeTest.java index a159efd30..a73a5a7bd 100644 --- a/vid-app-common/src/test/java/org/onap/vid/services/AAIServiceIntegrativeTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/services/AAIServiceIntegrativeTest.java @@ -44,9 +44,11 @@ import org.onap.vid.aai.util.AAIRestInterface; import org.onap.vid.aai.util.AAITreeConverter; import org.onap.vid.aai.util.CacheProvider; import org.onap.vid.aai.util.TestWithAaiClient; +import org.onap.vid.model.ModelUtil; import org.onap.vid.model.aaiTree.Network; import org.onap.vid.model.aaiTree.VpnBinding; import org.onap.vid.testUtils.TestUtils; +import org.onap.vid.utils.Logging; import org.springframework.http.HttpMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; @@ -56,19 +58,20 @@ public class AAIServiceIntegrativeTest extends TestWithAaiClient { private AAIRestInterface aaiRestInterface; private AaiServiceImpl aaiServiceWithoutMocks; + private Logging logging = new Logging(); private AaiServiceImpl createAaiServiceWithoutMocks(AAIRestInterface aaiRestInterface, CacheProvider cacheProvider) { AaiClient aaiClient = new AaiClient(aaiRestInterface, null, cacheProvider); ExecutorService executorService = MoreExecutors.newDirectExecutorService(); AAIServiceTree aaiServiceTree = new AAIServiceTree( aaiClient, - new AAITreeNodeBuilder(aaiClient), - new AAITreeConverter(), + new AAITreeNodeBuilder(aaiClient, logging), + new AAITreeConverter(new ModelUtil()), null, null, executorService ); - return new AaiServiceImpl(aaiClient, null, aaiServiceTree, executorService); + return new AaiServiceImpl(aaiClient, null, aaiServiceTree, executorService, logging); } @BeforeMethod diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AAIServiceTreeIntegrativeTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AAIServiceTreeIntegrativeTest.java index a956468f3..0d2d51cee 100644 --- a/vid-app-common/src/test/java/org/onap/vid/services/AAIServiceTreeIntegrativeTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/services/AAIServiceTreeIntegrativeTest.java @@ -37,8 +37,10 @@ import java.io.IOException; import java.net.URI; import java.util.Arrays; import java.util.List; +import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.function.Function; import javax.ws.rs.core.Response; import org.mockito.Mock; import org.onap.vid.aai.AaiClientInterface; @@ -48,12 +50,14 @@ import org.onap.vid.asdc.AsdcCatalogException; import org.onap.vid.asdc.parser.ServiceModelInflator; import org.onap.vid.exceptions.GenericUncheckedException; import org.onap.vid.model.Action; +import org.onap.vid.model.ModelUtil; import org.onap.vid.model.ServiceModel; import org.onap.vid.model.aaiTree.AAITreeNode; import org.onap.vid.model.aaiTree.FailureAAITreeNode; import org.onap.vid.model.aaiTree.ServiceInstance; import org.onap.vid.model.aaiTree.Vnf; import org.onap.vid.testUtils.TestUtils; +import org.onap.vid.utils.Logging; import org.springframework.http.HttpMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @@ -75,9 +79,12 @@ public class AAIServiceTreeIntegrativeTest { @Mock ServiceModelInflator serviceModelInflator; + @Mock + Logging logging; + private AAITreeNodeBuilder aaiTreeNodeBuilder; - private AAITreeConverter aaiTreeConverter = new AAITreeConverter(); + private AAITreeConverter aaiTreeConverter = new AAITreeConverter(new ModelUtil()); private ExecutorService executorService = Executors.newFixedThreadPool(10); @@ -87,7 +94,6 @@ public class AAIServiceTreeIntegrativeTest { private String serviceType = "vWINIFRED"; private String serviceInstanceId = "62888f15-6d24-4f7b-92a7-c3f35beeb215"; - //TODO Amichai: if in the future it is neede, add here the SUFFIX to the URL: "?format=simple" private String serviceInstanceRequestUri = "business/customers/customer/" + globalCustomerID + "/service-subscriptions/service-subscription/" + @@ -292,7 +298,13 @@ public class AAIServiceTreeIntegrativeTest { @BeforeMethod public void initMocks() { TestUtils.initMockitoMocks(this); - aaiTreeNodeBuilder = new AAITreeNodeBuilder(aaiClient); + reboundLoggingWithMdcMock(); + aaiTreeNodeBuilder = new AAITreeNodeBuilder(aaiClient, logging); + } + + private void reboundLoggingWithMdcMock() { + when(logging.withMDC(any(), any(Callable.class))).thenAnswer(invocation -> invocation.getArgument(1)); + when(logging.withMDC(any(), any(Function.class))).thenAnswer(invocation -> invocation.getArgument(1)); } public void getServiceInstanceTreeAndAssert(boolean isDuplicatedKeysInTenantRelation) throws IOException, AsdcCatalogException { diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AAIServiceTreeTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AAIServiceTreeTest.java index ada1f857e..be195c89b 100644 --- a/vid-app-common/src/test/java/org/onap/vid/services/AAIServiceTreeTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/services/AAIServiceTreeTest.java @@ -51,10 +51,12 @@ import org.onap.vid.aai.AaiClient; import org.onap.vid.aai.util.AAITreeConverter; import org.onap.vid.asdc.parser.ServiceModelInflator; import org.onap.vid.asdc.parser.ServiceModelInflator.Names; +import org.onap.vid.model.ModelUtil; import org.onap.vid.model.aaiTree.AAITreeNode; import org.onap.vid.model.aaiTree.NodeType; import org.onap.vid.mso.model.CloudConfiguration; import org.onap.vid.testUtils.TestUtils; +import org.onap.vid.utils.Logging; import org.onap.vid.utils.Unchecked; import org.springframework.http.HttpMethod; import org.testng.annotations.BeforeTest; @@ -199,8 +201,8 @@ public class AAIServiceTreeTest { ExecutorService executorService = MoreExecutors.newDirectExecutorService(); AAIServiceTree aaiServiceTree = new AAIServiceTree( aaiClientMock, - new AAITreeNodeBuilder(aaiClientMock), - new AAITreeConverter(), + new AAITreeNodeBuilder(aaiClientMock, new Logging()), + new AAITreeConverter(new ModelUtil()), null, null, executorService diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AAITreeNodeBuilderTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AAITreeNodeBuilderTest.java index c2a3f5d61..2c954b297 100644 --- a/vid-app-common/src/test/java/org/onap/vid/services/AAITreeNodeBuilderTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/services/AAITreeNodeBuilderTest.java @@ -20,7 +20,20 @@ package org.onap.vid.services; -import com.fasterxml.jackson.core.JsonProcessingException; +import static java.util.Comparator.comparing; +import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals; +import static net.javacrumbs.jsonunit.core.Option.IGNORING_ARRAY_ORDER; +import static net.javacrumbs.jsonunit.core.Option.IGNORING_EXTRA_FIELDS; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; +import static org.onap.vid.services.AAIServiceTree.AAI_TREE_PATHS; +import static org.onap.vid.utils.KotlinUtilsKt.JACKSON_OBJECT_MAPPER; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; + import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; @@ -28,7 +41,14 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.util.concurrent.MoreExecutors; - +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentSkipListSet; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; import org.apache.commons.lang3.tuple.Pair; import org.jetbrains.annotations.NotNull; import org.mockito.Mock; @@ -41,37 +61,15 @@ import org.onap.vid.exceptions.GenericUncheckedException; import org.onap.vid.model.aaiTree.AAITreeNode; import org.onap.vid.model.aaiTree.NodeType; import org.onap.vid.mso.model.CloudConfiguration; +import org.onap.vid.testUtils.TestUtils; +import org.onap.vid.utils.Logging; import org.onap.vid.utils.Tree; import org.onap.vid.utils.Unchecked; -import org.onap.vid.testUtils.TestUtils; import org.springframework.http.HttpMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; -import java.io.IOException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.ConcurrentSkipListSet; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import static java.util.Comparator.comparing; -import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals; -import static net.javacrumbs.jsonunit.core.Option.IGNORING_ARRAY_ORDER; -import static net.javacrumbs.jsonunit.core.Option.IGNORING_EXTRA_FIELDS; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.when; -import static org.onap.vid.services.AAIServiceTree.AAI_TREE_PATHS; -import static org.onap.vid.utils.KotlinUtilsKt.JACKSON_OBJECT_MAPPER; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; - public class AAITreeNodeBuilderTest { private AAITreeNodeBuilder aaiTreeNodeBuilder; @@ -80,13 +78,14 @@ public class AAITreeNodeBuilderTest { private AaiClientInterface aaiClientMock; private ExecutorService executorService; + private Logging logging = new Logging(); private static final ObjectMapper mapper = new ObjectMapper(); @BeforeClass public void initMocks() { MockitoAnnotations.initMocks(this); - aaiTreeNodeBuilder = new AAITreeNodeBuilder(aaiClientMock); + aaiTreeNodeBuilder = new AAITreeNodeBuilder(aaiClientMock, logging); executorService = MoreExecutors.newDirectExecutorService(); } diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AaiServiceImplTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AaiServiceImplTest.java index 9df99faa6..d3b2a48b1 100644 --- a/vid-app-common/src/test/java/org/onap/vid/services/AaiServiceImplTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/services/AaiServiceImplTest.java @@ -42,6 +42,7 @@ import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.function.Function; import javax.ws.rs.core.Response; import org.apache.http.HttpStatus; import org.jetbrains.annotations.NotNull; @@ -88,6 +89,7 @@ import org.onap.vid.model.aaiTree.AAITreeNode; import org.onap.vid.model.aaiTree.RelatedVnf; import org.onap.vid.model.aaiTree.ServiceInstance; import org.onap.vid.roles.RoleValidator; +import org.onap.vid.utils.Logging; import org.springframework.http.HttpMethod; @RunWith(MockitoJUnitRunner.class) @@ -131,6 +133,8 @@ public class AaiServiceImplTest { @Mock private AaiResponseTranslator aaiResponseTranslator; @Mock + private Logging logging; + @Mock private AAIServiceTree aaiServiceTree; @Spy private ExecutorService executorService = Executors.newFixedThreadPool(1); @@ -504,6 +508,7 @@ public class AaiServiceImplTest { when(aaiServiceTree.buildAAITree(anyString(), isNull(), eq(HttpMethod.GET), any(), anyBoolean())) .thenReturn(Collections.singletonList(testedTree)); when(aaiClient.getCloudRegionAndTenantByVnfId(anyString())).thenReturn(regionsAndTenants); + when(logging.withMDC(any(), any(Function.class))).thenAnswer(invocation -> invocation.getArgument(1)); List<RelatedVnf> actualGroupMembers = aaiService.searchGroupMembers(GLOBAL_CUSTOMER_ID, SERVICE_TYPE, INVARIANT_ID, GROUP_TYPE_FAILING, GROUP_ROLE_FAILING); diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBaseTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBaseTest.java index 9c0260e85..d41ce87bf 100644 --- a/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBaseTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBaseTest.java @@ -22,6 +22,8 @@ package org.onap.vid.services; import static java.util.Collections.emptyList; import static java.util.Collections.emptyMap; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.IsEqual.equalTo; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -32,9 +34,12 @@ import static org.onap.vid.model.VidNotions.ModelCategory; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; +import java.time.LocalDateTime; +import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Collections; +import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; @@ -43,9 +48,14 @@ import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.inject.Inject; +import org.hibernate.SessionFactory; +import org.onap.portalsdk.core.domain.FusionObject; +import org.onap.portalsdk.core.service.DataAccessService; import org.onap.vid.aai.AaiClientInterface; import org.onap.vid.aai.ExceptionWithRequestInfo; +import org.onap.vid.job.Job.JobStatus; import org.onap.vid.model.Action; +import org.onap.vid.model.ServiceInfo; import org.onap.vid.model.VidNotions; import org.onap.vid.model.serviceInstantiation.InstanceGroup; import org.onap.vid.model.serviceInstantiation.Network; @@ -57,13 +67,19 @@ import org.onap.vid.mso.model.ModelInfo; import org.onap.vid.mso.rest.AsyncRequestStatus; import org.onap.vid.mso.rest.RequestStatus; import org.onap.vid.properties.Features; +import org.onap.vid.services.AsyncInstantiationBusinessLogicTest.ServiceInfoComparator; +import org.onap.vid.utils.DaoUtils; import org.onap.vid.utils.TimeUtils; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpMethod; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.togglz.core.manager.FeatureManager; public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests { + public static final String MODEL_UUID = "337be3fc-293e-43ec-af0b-cf932dad07e6"; + public static final String MODEL_UUID_2 = "ce052844-22ba-4030-a838-822f2b39eb9b"; + public static final String OWNING_ENTITY_ID = "038d99af-0427-42c2-9d15-971b99b9b489"; public static final String JULIO_ERICKSON = "JULIO ERICKSON"; public static final String PROJECT_NAME = "{some project name}"; @@ -90,6 +106,12 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests protected HashMap<String, String> vfModuleInstanceParamsMapWithParamsToRemove; protected HashMap<String, String> vnfInstanceParamsMapWithParamsToRemove; + protected int serviceCount = 0; + + + @Inject + protected DataAccessService dataAccessService; + @Inject protected FeatureManager featureManager; @@ -99,6 +121,56 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests @Inject protected CloudOwnerService cloudOwnerService; + @Autowired + protected SessionFactory sessionFactory; + + + protected static Date toDate(LocalDateTime localDateTime) { + return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()); + } + + protected HashMap<String, Object> getPropsMap() { + HashMap<String, Object> props = new HashMap<>(); + props.put(FusionObject.Parameters.PARAM_USERID, 0); + return props; + } + + + private void setCreateDateToServiceInfo(UUID jobUuid, LocalDateTime createDate) { + List<ServiceInfo> serviceInfoList = dataAccessService.getList(ServiceInfo.class, getPropsMap()); + DaoUtils.tryWithSessionAndTransaction(sessionFactory, session -> { + serviceInfoList.stream() + .filter(serviceInfo -> jobUuid.equals(serviceInfo.getJobId())) + .forEach(serviceInfo -> { + serviceInfo.setCreated(toDate(createDate)); + session.saveOrUpdate(serviceInfo); + }); + return 1; + }); + } + + protected void addNewServiceInfo(UUID uuid, String userId, String serviceName, LocalDateTime createDate, + LocalDateTime statusModifiedDate, JobStatus status, boolean isHidden, boolean retryEnabled, + String modelUUID) { + ServiceInfo serviceInfo = new ServiceInfo(); + serviceInfo.setJobId(uuid); + serviceInfo.setUserId(userId); + serviceInfo.setServiceInstanceName(serviceName); + serviceInfo.setStatusModifiedDate(toDate(statusModifiedDate)); + serviceInfo.setJobStatus(status); + serviceInfo.setPause(false); + serviceInfo.setOwningEntityId("1234"); + serviceInfo.setCreatedBulkDate(toDate(createDate)); + serviceInfo.setRetryEnabled(retryEnabled); + serviceInfo.setServiceModelId(modelUUID); + serviceInfo.setHidden(isHidden); + dataAccessService.saveDomainObject(serviceInfo, getPropsMap()); + setCreateDateToServiceInfo(uuid, createDate); + serviceCount++; + + } + + public ServiceInstantiation generateMockMacroServiceInstantiationPayload(boolean isPause, Map<String, Vnf> vnfs, int bulkSize, boolean isUserProvidedNaming, String projectName, boolean rollbackOnFailure) { return generateMockServiceInstantiationPayload(isPause, vnfs, Collections.EMPTY_MAP, Collections.EMPTY_MAP, bulkSize, isUserProvidedNaming, projectName, rollbackOnFailure, false, null, Action.Create, null); } @@ -172,20 +244,22 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests vfModuleInfo.setModelVersion("10.0"); return new VfModule(vfModuleInfo, instanceName, volumeGroupInstanceName, Action.Create.name(), "mdt1", null, "88a6ca3ee0394ade9403f075db23167e", instanceParams, supplementaryParams, false, true, null, UUID.randomUUID().toString(), null, null, - null); + null, null, null); } return new VfModule(vfModuleInfo, instanceName, volumeGroupInstanceName, Action.Create.name(), null, null, null, - instanceParams, supplementaryParams, false, false, null, UUID.randomUUID().toString(), null, null, null); + instanceParams, supplementaryParams, false, false, null, UUID.randomUUID().toString(), null, + null, null, null, null); } protected ModelInfo createVfModuleModelInfo(String modelName, String modelVersion, String modelVersionId, String modelInvariantId, String modelCustomizationId, String modelCustomizationName) { return createModelInfo("vfModule", modelName, modelVersion, modelVersionId, modelInvariantId, modelCustomizationId, modelCustomizationName); } - protected VfModule createVfModuleForReplace(ModelInfo vfModuleModelInfo, String instanceName, String lcpCloudRegionId, String tenantId) { + protected VfModule createVfModuleForReplace(ModelInfo vfModuleModelInfo, String instanceName, + String lcpCloudRegionId, String tenantId, Boolean retainAssignments, Boolean retainVolumeGroups, Map<String, String> supplementaryParams) { return new VfModule( vfModuleModelInfo, instanceName, null, Action.Upgrade.name(), lcpCloudRegionId, null, tenantId, - null, null, true, null, null, UUID.randomUUID().toString(), null, null, null); + null, supplementaryParams, true, null, null, UUID.randomUUID().toString(), null, null, retainAssignments, retainVolumeGroups, null); } protected ModelInfo createVnfModelInfo(boolean isAlacarte) { diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBusinessLogicTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBusinessLogicTest.java index c1a6abc73..d1124f3a8 100644 --- a/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBusinessLogicTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBusinessLogicTest.java @@ -37,13 +37,13 @@ import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.core.Every.everyItem; import static org.hamcrest.core.IsEqual.equalTo; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.anyInt; -import static org.mockito.Mockito.anyString; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.spy; @@ -93,10 +93,8 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.stream.Collectors; import java.util.stream.IntStream; -import javax.inject.Inject; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.time.DateUtils; -import org.hibernate.SessionFactory; import org.jetbrains.annotations.NotNull; import org.json.JSONException; import org.mockito.ArgumentCaptor; @@ -104,8 +102,6 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.stubbing.Answer; -import org.onap.portalsdk.core.domain.FusionObject; -import org.onap.portalsdk.core.service.DataAccessService; import org.onap.portalsdk.core.util.SystemProperties; import org.onap.vid.aai.ExceptionWithRequestInfo; import org.onap.vid.aai.model.ResourceType; @@ -143,7 +139,6 @@ import org.onap.vid.properties.Features; import org.onap.vid.testUtils.TestUtils; import org.onap.vid.utils.DaoUtils; import org.onap.vid.utils.TimeUtils; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.testng.Assert; import org.testng.annotations.AfterMethod; @@ -155,8 +150,7 @@ import org.testng.annotations.Test; @ContextConfiguration(classes = {DataSourceConfig.class, SystemProperties.class, MockedAaiClientAndFeatureManagerConfig.class}) public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseTest { - @Inject - private DataAccessService dataAccessService; + @Mock private JobAdapter jobAdapterMock; @@ -168,15 +162,11 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT private AuditService auditService; - @Autowired - private SessionFactory sessionFactory; private AsyncInstantiationBusinessLogicImpl asyncInstantiationBL; protected MsoRequestBuilder msoRequestBuilder; - private int serviceCount = 0; - private static final String UPDATE_SERVICE_INFO_EXCEPTION_MESSAGE = "Failed to retrieve class .*ServiceInfo with jobId .* from table. no resource found"; @@ -209,6 +199,7 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT Mockito.reset(aaiClient); Mockito.reset(jobAdapterMock); Mockito.reset(jobsBrokerServiceMock); + Mockito.reset(asyncInstantiationRepository); mockAaiClientAnyNameFree(); enableAddCloudOwnerOnMsoRequest(); } @@ -236,13 +227,15 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT uuid = UUID.randomUUID(); addNewJob(uuid); createdDate = NOW.minusYears(1); - addNewServiceInfo(uuid, userId, "Old", createdDate, createdDate, COMPLETED, false, false); + addNewServiceInfo(uuid, userId, "Old", createdDate, createdDate, COMPLETED, false, false, + MODEL_UUID); uuid = UUID.randomUUID(); addNewJob(uuid); createdDate = NOW.minusDays(20); modifiedDate = NOW.minusDays(19); - addNewServiceInfo(uuid, userId, "Hidden", createdDate, modifiedDate, PAUSE, true, false); + addNewServiceInfo(uuid, userId, "Hidden", createdDate, modifiedDate, PAUSE, true, false, + MODEL_UUID); createNewTestServicesInfo(String.valueOf(userId)); } @@ -257,20 +250,26 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT addNewJob(uuid); createdDate = NOW.minusDays(40); - addNewServiceInfo(uuid, userId, "service instance 5", createdDate, createdDate, COMPLETED, false, false); - addNewServiceInfo(uuid, userId, "service instance 6", createdDate, createdDate, STOPPED, false, false); + addNewServiceInfo(uuid, userId, "service instance 5", createdDate, createdDate, COMPLETED, false, false, + MODEL_UUID); + addNewServiceInfo(uuid, userId, "service instance 6", createdDate, createdDate, STOPPED, false, false, + MODEL_UUID); uuid = UUID.randomUUID(); addNewJob(uuid); createdDate = NOW.minusDays(20); modifiedDate = NOW.minusDays(10); - addNewServiceInfo(uuid, userId, "service instance 4", createdDate, modifiedDate, STOPPED, false, false); - addNewServiceInfo(uuid, userId, "service instance 2", createdDate, modifiedDate, COMPLETED, false, false); - addNewServiceInfo(uuid, userId, "service instance 3", createdDate, modifiedDate, PAUSE, false, false); + addNewServiceInfo(uuid, userId, "service instance 4", createdDate, modifiedDate, STOPPED, false, false, + MODEL_UUID); + addNewServiceInfo(uuid, userId, "service instance 2", createdDate, modifiedDate, COMPLETED, false, false, + MODEL_UUID); + addNewServiceInfo(uuid, userId, "service instance 3", createdDate, modifiedDate, PAUSE, false, false, + MODEL_UUID); modifiedDate = NOW.minusDays(19); - addNewServiceInfo(uuid, userId, "service instance 1", createdDate, modifiedDate, FAILED, false, false); + addNewServiceInfo(uuid, userId, "service instance 1", createdDate, modifiedDate, FAILED, false, false, + MODEL_UUID); // Job to a different user @@ -278,10 +277,13 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT addNewJob(uuid); createdDate = NOW.minusMonths(2); - addNewServiceInfo(uuid, "2221", "service instance 7", createdDate, createdDate, COMPLETED, false, false); + addNewServiceInfo(uuid, "2221", "service instance 7", createdDate, createdDate, COMPLETED, false, false, + MODEL_UUID); } + + private UUID createServicesInfoWithDefaultValues(Job.JobStatus status) { LocalDateTime NOW = LocalDateTime.now(); @@ -290,7 +292,8 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT uuid = UUID.randomUUID(); addNewJob(uuid, status); - addNewServiceInfo(uuid, null, "service instance 1", NOW, NOW, status, false, false); + addNewServiceInfo(uuid, null, "service instance 1", NOW, NOW, status, false, false, + MODEL_UUID); return uuid; @@ -303,9 +306,7 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT return expectedOrderServiceInfo; } - private static Date toDate(LocalDateTime localDateTime) { - return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()); - } + private LocalDateTime fromDate(Date date) { return Instant.ofEpochMilli(date.getTime()) @@ -313,25 +314,6 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT .toLocalDateTime(); } - private void addNewServiceInfo(UUID uuid, String userId, String serviceName, LocalDateTime createDate, LocalDateTime statusModifiedDate, JobStatus status, boolean isHidden, boolean retryEnabled) { - ServiceInfo serviceInfo = new ServiceInfo(); - serviceInfo.setJobId(uuid); - serviceInfo.setUserId(userId); - serviceInfo.setServiceInstanceName(serviceName); - serviceInfo.setStatusModifiedDate(toDate(statusModifiedDate)); - serviceInfo.setJobStatus(status); - serviceInfo.setPause(false); - serviceInfo.setOwningEntityId("1234"); - serviceInfo.setCreatedBulkDate(toDate(createDate)); - serviceInfo.setRetryEnabled(retryEnabled); - - serviceInfo.setHidden(isHidden); - dataAccessService.saveDomainObject(serviceInfo, getPropsMap()); - setCreateDateToServiceInfo(uuid, createDate); - serviceCount++; - - } - private void setCreateDateToServiceInfo(UUID jobUuid, LocalDateTime createDate) { List<ServiceInfo> serviceInfoList = dataAccessService.getList(ServiceInfo.class, getPropsMap()); DaoUtils.tryWithSessionAndTransaction(sessionFactory, session -> { @@ -357,7 +339,9 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT } private ServiceInstantiation addOriginalService(UUID jobId, String userID){ - addNewServiceInfo(jobId, userID, "name", LocalDateTime.now(), LocalDateTime.now(), COMPLETED_WITH_ERRORS, false, true); + addNewServiceInfo(jobId, userID, "name", LocalDateTime.now(), LocalDateTime.now(), COMPLETED_WITH_ERRORS, false, + true, + MODEL_UUID); assertThat(asyncInstantiationRepository.getServiceInfoByJobId(jobId).isRetryEnabled(), is(true)); ServiceInstantiation originalServiceInstantiation = prepareServiceInstantiation(true, 1); doReturn(originalServiceInstantiation).when(asyncInstantiationRepository).getJobRequest(jobId); @@ -469,11 +453,7 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT when(aaiClient.isNodeTypeExistsByName(uniqueName, serviceInstance)).thenReturn(true); } - private HashMap<String, Object> getPropsMap() { - HashMap<String, Object> props = new HashMap<>(); - props.put(FusionObject.Parameters.PARAM_USERID, 0); - return props; - } + @DataProvider @@ -1387,4 +1367,5 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT assertThat(path, equalTo("/serviceInstantiation/v7/serviceInstances/myService/vnfs/myVNF/vfModules/myVFModule/replace")); } + } diff --git a/vid-app-common/src/test/java/org/onap/vid/services/InstantiationTemplatesServiceTest.java b/vid-app-common/src/test/java/org/onap/vid/services/InstantiationTemplatesServiceTest.java new file mode 100644 index 000000000..f09ea313c --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/services/InstantiationTemplatesServiceTest.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 - 2019 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.onap.vid.services; + +import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.anEmptyMap; +import static org.hamcrest.Matchers.hasProperty; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.common.collect.ImmutableMap; +import java.util.Map; +import java.util.UUID; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.onap.vid.dal.AsyncInstantiationRepository; +import org.onap.vid.model.ModelUtil; +import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; +import org.onap.vid.model.serviceInstantiation.ServiceInstantiationTemplate; +import org.onap.vid.model.serviceInstantiation.Vnf; +import org.onap.vid.testUtils.TestUtils; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +public class InstantiationTemplatesServiceTest { + + @Mock + private AsyncInstantiationRepository asyncInstantiationRepository; + + @Mock + private ModelUtil modelUtil; + + @InjectMocks + private InstantiationTemplatesService instantiationTemplatesService; + + @BeforeMethod + public void initMocks() { + TestUtils.initMockitoMocks(this); + } + + @Test + public void getJobRequestAsTemplate_whenIsCalled_asyncInstantiationRepositoryGetJobRequestIsInvoked() { + UUID jobId = UUID.randomUUID(); + ServiceInstantiation serviceInstantiationMock = mock(ServiceInstantiation.class, RETURNS_DEEP_STUBS); + doReturn(serviceInstantiationMock).when(asyncInstantiationRepository).getJobRequest(jobId); + + // When... + instantiationTemplatesService.getJobRequestAsTemplate(jobId); + + verify(asyncInstantiationRepository).getJobRequest(jobId); + } + + @Test + public void getJobRequestAsTemplate_givenModelUtilReturnsValue_thenVnfCounterMapIsPopulatedWithThatValue() { + Map<String, Integer> dummyNonEmptyMap = ImmutableMap.of("dummyKey", 9); + ServiceInstantiation serviceInstantiation = mock(ServiceInstantiation.class, RETURNS_DEEP_STUBS); + doReturn(serviceInstantiation).when(asyncInstantiationRepository).getJobRequest(any()); + + // Given... + when(modelUtil.getExistingCounterMap(any(), any())).thenAnswer( + // return empty counterMap if argument is an empty map; otherwise return a mocked response + invocation -> ((Map)invocation.getArgument(0)).size() == 0 // isEmpty() does not work on mocks + ? ImmutableMap.of() + : dummyNonEmptyMap + ); + + // only vnf will have a non-empty value + when(serviceInstantiation.getVnfs()).thenReturn(ImmutableMap.of("1", mock(Vnf.class))); + + // When... + ServiceInstantiationTemplate result = instantiationTemplatesService.getJobRequestAsTemplate(UUID.randomUUID()); + + assertThat(result, hasProperty("existingVNFCounterMap", jsonEquals(dummyNonEmptyMap))); + assertThat(result, hasProperty("existingNetworksCounterMap", anEmptyMap())); + assertThat(result, hasProperty("existingVnfGroupCounterMap", anEmptyMap())); + assertThat(result, hasProperty("existingVRFCounterMap", anEmptyMap())); + } + +} diff --git a/vid-app-common/src/test/java/org/onap/vid/services/MsoRequestBuilderTest.java b/vid-app-common/src/test/java/org/onap/vid/services/MsoRequestBuilderTest.java index a7e2d553d..cb59129c3 100644 --- a/vid-app-common/src/test/java/org/onap/vid/services/MsoRequestBuilderTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/services/MsoRequestBuilderTest.java @@ -22,6 +22,7 @@ package org.onap.vid.services; import static com.google.common.collect.Maps.newHashMap; import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals; +import static net.javacrumbs.jsonunit.JsonMatchers.jsonPartEquals; import static net.javacrumbs.jsonunit.core.Option.IGNORING_ARRAY_ORDER; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; @@ -74,8 +75,9 @@ import org.onap.vid.mso.model.ModelInfo; import org.onap.vid.mso.model.NetworkInstantiationRequestDetails; import org.onap.vid.mso.model.ServiceDeletionRequestDetails; import org.onap.vid.mso.model.ServiceInstantiationRequestDetails; -import org.onap.vid.mso.model.VfModuleInstantiationRequestDetails; +import org.onap.vid.mso.model.UserParamMap; import org.onap.vid.mso.model.VfModuleMacro; +import org.onap.vid.mso.model.VfModuleOrVolumeGroupRequestDetails; import org.onap.vid.mso.model.VnfInstantiationRequestDetails; import org.onap.vid.mso.model.VolumeGroupRequestDetails; import org.onap.vid.properties.Features; @@ -370,7 +372,7 @@ public class MsoRequestBuilderTest extends AsyncInstantiationBaseTest { when(aaiClient.isNodeTypeExistsByName(eq("vmxnjr001_AVPN_base_vRE_BV_expansion"), eq(ResourceType.VF_MODULE))).thenReturn(false); String expected = IOUtils.toString(this.getClass().getResource(fileName), "UTF-8"); - final RequestDetailsWrapper<VfModuleInstantiationRequestDetails> result = msoRequestBuilder.generateVfModuleInstantiationRequest( + final RequestDetailsWrapper<VfModuleOrVolumeGroupRequestDetails> result = msoRequestBuilder.generateVfModuleInstantiationRequest( vfModule, siModelInfo, serviceInstanceId, vnfModelInfo, vnfInstanceId, volumeGroupInstanceId, "pa0916", "VNF_API"); MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result); @@ -390,8 +392,8 @@ public class MsoRequestBuilderTest extends AsyncInstantiationBaseTest { } @Test(dataProvider = "expectedAggregatedParams") - public void testAggregateInstanceParamsAndSuppFile(Map<String, String> instanceParams, Map<String, String> suppParams, List<VfModuleInstantiationRequestDetails.UserParamMap<String, String>> expected) { - List<VfModuleInstantiationRequestDetails.UserParamMap<String, String>> aggParams = msoRequestBuilder.aggregateAllInstanceParams(instanceParams, suppParams); + public void testAggregateInstanceParamsAndSuppFile(Map<String, String> instanceParams, Map<String, String> suppParams, List<UserParamMap<String, String>> expected) { + List<UserParamMap<String, String>> aggParams = msoRequestBuilder.aggregateAllInstanceParams(instanceParams, suppParams); assertThat("Aggregated params are not as expected", aggParams, equalTo(expected)); } @@ -565,7 +567,7 @@ public class MsoRequestBuilderTest extends AsyncInstantiationBaseTest { " }" + "}"; VfModule vfModuleDetails = createVfModule("201673MowAvpnVpeBvL..AVPN_base_vPE_BV..module-0", VF_MODULE_0_MODEL_VERSION_ID, VF_MODULE_0_MODEL_CUSTOMIZATION_NAME, null, new HashMap<>(), "vmxnjr001_AVPN_base_vPE_BV_base", null, true); - RequestDetailsWrapper<VfModuleInstantiationRequestDetails> result = + RequestDetailsWrapper<VfModuleOrVolumeGroupRequestDetails> result = msoRequestBuilder.generateDeleteVfModuleRequest(vfModuleDetails, "az2018"); MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result); } @@ -609,24 +611,67 @@ public class MsoRequestBuilderTest extends AsyncInstantiationBaseTest { assertThat(result, jsonEquals(expected).when(IGNORING_ARRAY_ORDER)); } + @Test(dataProvider = "trueAndFalse", dataProviderClass = TestUtils.class) + public void generateReplaceVfModuleRequest_whenRetainAssignmentsProvidedFromFrontend_retainAssignmentsToMsoIsTheSame(boolean retainAssignments) { + + assertThat(generatedVfModuleReplaceRequest(retainAssignments, null, null), + jsonPartEquals("requestDetails.requestParameters.retainAssignments", retainAssignments)); + } + + @Test + public void generateReplaceVfModuleRequest_whenRetainVolumeGroupIsTrue_rebuildVolumeGroupIsFalse() { + boolean retainVolumeGroups = true; + + assertThat(generatedVfModuleReplaceRequest(null, retainVolumeGroups, null), + jsonPartEquals("requestDetails.requestParameters.rebuildVolumeGroups", false)); + } + + @Test + public void generateReplaceVfModuleRequest_whenThereAreSupplementaryParams_thenTheyAreAddToUserParams() { + + String expectedParams = "[{" + + " \"vre_a_volume_size_0\" : \"100\"," + + " \"vmx_int_net_len\" : \"24\"," + + " \"availability_zone_0\": \"abc\"" + + " }]"; + + Map<String, String> supplementaryParams = ImmutableMap.of( + "vre_a_volume_size_0", "100", + "vmx_int_net_len", "24", + "availability_zone_0", "abc" + ); + + assertThat(generatedVfModuleReplaceRequest(null, null, supplementaryParams), + jsonPartEquals("requestDetails.requestParameters.userParams", expectedParams)); + } + @Test public void generateReplaceVfModuleRequest_verifyResultAsExpected() { + Boolean retainVolumeGroups = null; + Boolean retainAssignments = null; + String expected = TestUtils.readFileAsString("/payload_jsons/vfmodule/replace_vfmodule__payload_to_mso.json"); + assertThat(generatedVfModuleReplaceRequest(retainAssignments, retainVolumeGroups, null), jsonEquals(expected).when(IGNORING_ARRAY_ORDER)); + } + + private RequestDetailsWrapper<VfModuleOrVolumeGroupRequestDetails> generatedVfModuleReplaceRequest( + Boolean retainAssignments, Boolean retainVolumeGroups, Map<String, String> supplementaryParams) { when(featureManager.isActive(Features.FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST)).thenReturn(true); when(aaiClient.getCloudOwnerByCloudRegionId("regionOne")).thenReturn("irma-aic"); ModelInfo vfModuleModelInfo = createVfModuleModelInfo("newest-model-name-vfm", "newest-model-version-vfm", "newest-model-uuid-vfm", "f7a867f2-596b-4f4a-a128-421e825a6190", "newest-model-customization-uuid-vfm","newest-model-customization-name-vfm" ); - VfModule vfModuleDetails = createVfModuleForReplace(vfModuleModelInfo, "replace_module", "regionOne", "0422ffb57ba042c0800a29dc85ca70f8"); + VfModule vfModuleDetails = createVfModuleForReplace(vfModuleModelInfo, "replace_module", "regionOne", "0422ffb57ba042c0800a29dc85ca70f8", + retainAssignments, retainVolumeGroups, supplementaryParams); ModelInfo serviceModelInfo = createServiceModelInfo("newest-model-name-service", "newest-model-version-service", "newest-model-uuid-service", "b16a9398-ffa3-4041-b78c-2956b8ad9c7b", null, null ); ModelInfo vnfModelInfo = createVnfModelInfo("newest-model-name-vnf", "newest-model-version-vnf", "newest-model-uuid-vnf", "23122c9b-dd7f-483f-bf0a-e069303db2f7", "newest-model-customization-uuid-vnf", "newest-model-customization-name-vnf" ); - RequestDetailsWrapper<VfModuleInstantiationRequestDetails> result = - msoRequestBuilder.generateVfModuleInstantiationRequest(vfModuleDetails, serviceModelInfo, "e9993045-cc96-4f3f-bf9a-71b2a400a956", vnfModelInfo, "5c9c2896-1fe6-4055-b7ec-d0a01e5f9bf5", null,"az2016", "GR_API"); - - assertThat(result, jsonEquals(expected).when(IGNORING_ARRAY_ORDER)); + return msoRequestBuilder.generateVfModuleReplaceRequest(vfModuleDetails, serviceModelInfo, + "e9993045-cc96-4f3f-bf9a-71b2a400a956", vnfModelInfo, + "5c9c2896-1fe6-4055-b7ec-d0a01e5f9bf5", null, "az2016", "GR_API" + ); } -}
\ No newline at end of file +} diff --git a/vid-app-common/src/test/java/org/onap/vid/utils/LoggingUtilsTest.java b/vid-app-common/src/test/java/org/onap/vid/utils/LoggingUtilsTest.java index 6cbb14ac2..c2a1f2877 100644 --- a/vid-app-common/src/test/java/org/onap/vid/utils/LoggingUtilsTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/utils/LoggingUtilsTest.java @@ -21,7 +21,11 @@ package org.onap.vid.utils; import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.CoreMatchers.sameInstance; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.matchesPattern; import static org.mockito.ArgumentMatchers.contains; import static org.mockito.Mockito.mock; @@ -33,12 +37,15 @@ import com.att.eelf.configuration.EELFLogger; import com.fasterxml.jackson.core.JsonLocation; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; +import com.google.common.collect.ImmutableMap; import io.joshworks.restclient.http.HttpResponse; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; +import java.util.concurrent.Callable; +import java.util.function.Function; import javax.crypto.BadPaddingException; import javax.net.ssl.SSLHandshakeException; import javax.ws.rs.ProcessingException; @@ -46,6 +53,7 @@ import org.apache.commons.io.IOUtils; import org.mockito.ArgumentCaptor; import org.onap.vid.exceptions.GenericUncheckedException; import org.onap.vid.testUtils.TestUtils; +import org.slf4j.MDC; import org.springframework.http.HttpMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; @@ -196,6 +204,71 @@ public class LoggingUtilsTest { assertThat(Logging.exceptionToDescription(exceptionToDescribe), matchesRegEx(expectedButDotsEscaped)); } + @Test + public void testWithMDCInternal_whenGivenProvider_functionShouldBeExtractedWithMdc() { + Object myAnything = new Object(); + + Object result = logginService.withMDCInternal(ImmutableMap.of("my key", "my value"), + () -> { + assertThat("MDC values should be installed when extracting the supplier", + MDC.getCopyOfContextMap(), hasEntry("my key", "my value")); + return myAnything; + } + ); + + assertThat("withMDCInternal should extract my function", result, is(sameInstance(myAnything))); + assertThat("MDC values should be removed", MDC.getCopyOfContextMap(), not(hasEntry("k", "v"))); + } + + @Test + public void testWithMDC_whenGivenFunction_functionShouldBeEncapsulated() { + // Given + String[] stringsArray = {"before"}; + + Function<String, Integer> myFunction = s -> { + assertThat("MDC values should be installed when inside myFunction", + MDC.getCopyOfContextMap(), hasEntry("my key", "my value")); + stringsArray[0] = s; + return 42; + }; + + // When + Function<String, Integer> functionWithMDC = + logginService.withMDC(ImmutableMap.of("my key", "my value"), myFunction); + + + assertThat("invocation of function must not happen yet", stringsArray[0], is("before")); + + Integer result = functionWithMDC.apply("after"); + + assertThat("invocation of my function should have been deferred", stringsArray[0], is("after")); + assertThat("apply should return function's value", result, is(42)); + } + + @Test + public void testWithMDC_whenGivenCallable_callableShouldBeEncapsulated() throws Exception { + // Given + String[] stringsArray = {"before"}; + + Callable<Integer> myCallable = () -> { + assertThat("MDC values should be installed when inside myCallable", + MDC.getCopyOfContextMap(), hasEntry("my key", "my value")); + stringsArray[0] = "after"; + return 42; + }; + + // When + Callable<Integer> callableWithMDC = logginService.withMDC(ImmutableMap.of("my key", "my value"), myCallable); + + + assertThat("invocation of callable must not happen yet", stringsArray[0], is("before")); + + Integer result = callableWithMDC.call(); + + assertThat("invocation of my callable should have been deferred", stringsArray[0], is("after")); + assertThat("apply should return function's value", result, is(42)); + } + private static String escapeBrackets(String in) { return in.replaceAll("[\\(\\[\\{\\)]", "\\\\$0"); } diff --git a/vid-app-common/src/test/resources/csars/portMirroringService.zip b/vid-app-common/src/test/resources/csars/portMirroringService.zip Binary files differnew file mode 100644 index 000000000..c074f31bd --- /dev/null +++ b/vid-app-common/src/test/resources/csars/portMirroringService.zip diff --git a/vid-app-common/src/test/resources/csars/service-Vocg1804Svc.zip b/vid-app-common/src/test/resources/csars/service-Vocg1804Svc.zip Binary files differnew file mode 100644 index 000000000..05e0a2974 --- /dev/null +++ b/vid-app-common/src/test/resources/csars/service-Vocg1804Svc.zip diff --git a/vid-app-common/src/test/resources/macro_services_by_invariant_uuid.json b/vid-app-common/src/test/resources/macro_services_by_invariant_uuid.json new file mode 100644 index 000000000..3afb9321a --- /dev/null +++ b/vid-app-common/src/test/resources/macro_services_by_invariant_uuid.json @@ -0,0 +1,4 @@ +[ + "117f5f1a-1b47-4ae1-ae04-489c9a7ada28", + "2efab359-cdd4-4da2-9b79-61df990796c2" +] diff --git a/vid-app-common/src/test/resources/payload_jsons/vfmodule/upgrade_vfmodule_e2e__fe_input_cypress.json b/vid-app-common/src/test/resources/payload_jsons/vfmodule/upgrade_vfmodule_e2e__fe_input_cypress.json index 9571a2d13..748b5f267 100644 --- a/vid-app-common/src/test/resources/payload_jsons/vfmodule/upgrade_vfmodule_e2e__fe_input_cypress.json +++ b/vid-app-common/src/test/resources/payload_jsons/vfmodule/upgrade_vfmodule_e2e__fe_input_cypress.json @@ -1,6 +1,6 @@ { "action": "None_Upgrade", - "isDirty": true, + "isDirty": false, "vnfs": { "d520268f-7489-4662-be59-f81495b3a069": { "action": "None_Upgrade", @@ -33,6 +33,9 @@ "xbitestmodulereplace0..XbiTestModuleReplace..base_ocg..module-0": { "b0732bed-3ddf-43cc-b193-7f18db84e476": { "action": "None_Upgrade", + "retainAssignments" : false, + "retainVolumeGroups" : false, + "sdncPreLoad" : true, "instanceName": "PST-VfMod-Replace-5-Vfmod", "instanceId": "b0732bed-3ddf-43cc-b193-7f18db84e476", "orchStatus": "Active", @@ -57,7 +60,10 @@ "platformName": null, "trackById": "b0732bed-3ddf-43cc-b193-7f18db84e476", "isBase": true, - "volumeGroupName": null + "volumeGroupName": null, + "supplementaryFile": null, + "supplementaryFile_hidden": null, + "supplementaryFile_hidden_content" : null } } }, @@ -113,4 +119,4 @@ "viewEditUI": "legacy", "instantiationType": "ALaCarte" } -}
\ No newline at end of file +} diff --git a/vid-app-common/src/test/resources/payload_jsons/vfmodule/upgrade_vfmodule_e2e__payload_to_mso.json b/vid-app-common/src/test/resources/payload_jsons/vfmodule/upgrade_vfmodule_e2e__payload_to_mso.json index a9a9eda7d..45b89f730 100644 --- a/vid-app-common/src/test/resources/payload_jsons/vfmodule/upgrade_vfmodule_e2e__payload_to_mso.json +++ b/vid-app-common/src/test/resources/payload_jsons/vfmodule/upgrade_vfmodule_e2e__payload_to_mso.json @@ -33,6 +33,9 @@ } ], "requestParameters": { + "retainAssignments": false, + "rebuildVolumeGroups":true, + "usePreload" : true, "userParams": [], "testApi": "VNF_API" }, diff --git a/vid-app-common/src/test/resources/sampleTosca.csar b/vid-app-common/src/test/resources/sampleTosca.csar Binary files differdeleted file mode 100644 index d9c469a15..000000000 --- a/vid-app-common/src/test/resources/sampleTosca.csar +++ /dev/null |