From b3d4898d9e8452ea0b8d848c048e712d43b8d9a3 Mon Sep 17 00:00:00 2001 From: Michael Lando Date: Sun, 11 Jun 2017 14:22:02 +0300 Subject: [SDC-29] rebase continue work to align source Change-Id: I218f1c5ee23fb2c8314f1c70921d3ad8682c10f4 Signed-off-by: Michael Lando --- catalog-be/pom.xml | 4 +- .../sdc/be/components/ArtifactsResolver.java | 27 + .../engine/JsonContainerResourceInstance.java | 7 + .../distribution/engine/NotificationDataImpl.java | 4 +- .../engine/VfModuleArtifactPayload.java | 2 + .../be/components/impl/ArtifactResolverImpl.java | 62 + .../be/components/impl/ArtifactsBusinessLogic.java | 109 +- .../be/components/impl/AttributeBusinessLogic.java | 32 +- .../be/components/impl/ComponentBusinessLogic.java | 93 +- .../impl/ComponentInstanceBusinessLogic.java | 42 +- .../be/components/impl/CsarValidationUtils.java | 2 +- .../be/components/impl/ElementBusinessLogic.java | 6 +- .../sdc/be/components/impl/GroupBusinessLogic.java | 1860 ++++++++------------ .../sdc/be/components/impl/ImportUtils.java | 27 +- .../be/components/impl/InputsBusinessLogic.java | 21 +- .../be/components/impl/ResourceBusinessLogic.java | 85 +- .../be/components/impl/ResourceImportManager.java | 33 +- .../be/components/impl/ServiceBusinessLogic.java | 31 +- .../components/lifecycle/CheckoutTransition.java | 12 +- .../datamodel/utils/UiComponentDataConverter.java | 17 + .../org/openecomp/sdc/be/ecomp/EcompIntImpl.java | 27 +- .../ecomp/converters/AssetMetadataConverter.java | 391 ++++ .../servlet/AssetMetadataConverter.java | 392 ----- .../be/externalapi/servlet/AssetsDataServlet.java | 1 + .../org/openecomp/sdc/be/impl/ComponentsUtils.java | 27 + .../sdc/be/listen/BEAppContextListener.java | 34 +- .../be/servlets/AbstractValidationsServlet.java | 2 +- .../sdc/be/servlets/AttributeServlet.java | 22 +- .../sdc/be/servlets/BeGenericServlet.java | 2 +- .../sdc/be/servlets/ComponentInstanceServlet.java | 8 +- .../sdc/be/servlets/ComponentServlet.java | 6 +- .../sdc/be/servlets/LifecycleServlet.java | 5 +- .../sdc/be/servlets/UserAdminServlet.java | 38 - .../java/org/openecomp/sdc/be/tosca/CsarUtils.java | 154 +- .../openecomp/sdc/be/tosca/ToscaExportHandler.java | 7 +- .../openecomp/sdc/be/user/IUserBusinessLogic.java | 4 - .../openecomp/sdc/be/user/UserBusinessLogic.java | 108 +- .../src/main/resources/application-context.xml | 2 +- catalog-be/src/main/resources/config/SDC.zip | Bin 29236 -> 30057 bytes .../main/resources/config/error-configuration.yaml | 10 +- catalog-be/src/main/resources/config/logback.xml | 4 +- .../import/tosca/data-types/dataTypes.yml | 13 + .../import/tosca/data-types/dataTypes.zip | Bin 5243 -> 5277 bytes .../components/impl/ArtifactBusinessLogicTest.java | 4 +- .../be/components/impl/ArtifactResolverTest.java | 91 + .../sdc/be/components/impl/ImportUtilsTest.java | 7 +- .../externalapi/servlet/AssetsDataServletTest.java | 1 + 47 files changed, 1861 insertions(+), 1975 deletions(-) create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/ArtifactsResolver.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/AssetMetadataConverter.java delete mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetMetadataConverter.java create mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactResolverTest.java (limited to 'catalog-be') diff --git a/catalog-be/pom.xml b/catalog-be/pom.xml index e53069cf5a..6f35b3a5a1 100644 --- a/catalog-be/pom.xml +++ b/catalog-be/pom.xml @@ -24,7 +24,7 @@ com.fasterxml.jackson.dataformat jackson-dataformat-yaml - ${jackson.version} + ${jackson.yaml.version} compile @@ -450,7 +450,7 @@ org.openecomp.ecompsdkos - ecompFW + epsdk-fw ${ecomp.version} compile diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/ArtifactsResolver.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/ArtifactsResolver.java new file mode 100644 index 0000000000..95f1edd61f --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/ArtifactsResolver.java @@ -0,0 +1,27 @@ +package org.openecomp.sdc.be.components; + +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; + +public interface ArtifactsResolver { + + /** + * searching for an artifact with the give {@code artifactId} on the given {@code component} + * @param component the component to look for artifact in + * @param componentType the type of the component to look for artifact in + * @param artifactId the id of the artifact to find + * @return the found artifact or null if not exist + */ + ArtifactDefinition findArtifactOnComponent(Component component, ComponentTypeEnum componentType, String artifactId); + + /** + * searching for an artifact with the give {@code artifactId} on the given {@code componentInstance} + * @param componentInstance the component instance to look for the artifact in + * @param artifactId the if of the artifact to find + * @return the found artifact or null if not exist + */ + ArtifactDefinition findArtifactOnComponentInstance(ComponentInstance componentInstance, String artifactId); + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/JsonContainerResourceInstance.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/JsonContainerResourceInstance.java index d1b445b065..5efcfe7fa8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/JsonContainerResourceInstance.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/JsonContainerResourceInstance.java @@ -118,4 +118,11 @@ public class JsonContainerResourceInstance { public void setSubcategory(String subcategory) { this.subcategory = subcategory; } + + @Override + public String toString() { + return "JsonContainerResourceInstance [resourceInstanceName=" + resourceInstanceName + ", resourceName=" + resourceName + ", resourceVersion=" + resourceVersion + ", resoucreType=" + resoucreType + ", resourceUUID=" + resourceUUID + + ", resourceInvariantUUID=" + resourceInvariantUUID + ", resourceCustomizationUUID=" + resourceCustomizationUUID + ", category=" + category + ", subcategory=" + subcategory + ", artifacts=" + artifacts + "]"; + } + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationDataImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationDataImpl.java index 8a2ef8e63b..149499811f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationDataImpl.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationDataImpl.java @@ -77,9 +77,11 @@ public class NotificationDataImpl implements INotificationData { this.serviceDescription = serviceDescription; } + @Override public String toString() { - return "NotificationDataImpl [distributionID=" + distributionID + ", serviceName=" + serviceName + ", serviceVersion=" + serviceVersion + ", serviceUUID=" + serviceUUID + ", serviceInvariantUUID=" + serviceInvariantUUID + "]"; + return "NotificationDataImpl [distributionID=" + distributionID + ", serviceName=" + serviceName + ", serviceVersion=" + serviceVersion + ", serviceUUID=" + serviceUUID + ", serviceDescription=" + serviceDescription + + ", serviceInvariantUUID=" + serviceInvariantUUID + ", resources=" + resources + ", serviceArtifacts=" + serviceArtifacts + "]"; } @Override diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/VfModuleArtifactPayload.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/VfModuleArtifactPayload.java index 71593fa99a..2bcaa4f54a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/VfModuleArtifactPayload.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/VfModuleArtifactPayload.java @@ -62,6 +62,8 @@ public class VfModuleArtifactPayload { vfModuleModelDescription = group.getDescription(); artifacts = group.getArtifactsUuid(); + artifacts.addAll(group.getGroupInstanceArtifactsUuid()); + // Base Value is set from properties setBaseValue(group); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java new file mode 100644 index 0000000000..7ef3a1961f --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java @@ -0,0 +1,62 @@ +package org.openecomp.sdc.be.components.impl; + +import org.openecomp.sdc.be.components.ArtifactsResolver; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Service; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +@org.springframework.stereotype.Component("artifact-resolver") +public class ArtifactResolverImpl implements ArtifactsResolver { + + @Override + public ArtifactDefinition findArtifactOnComponent(Component component, ComponentTypeEnum componentType, String artifactId) { + List allComponentsArtifacts = getAllComponentsArtifacts(component, componentType); + return findById(allComponentsArtifacts, artifactId); + + } + + @Override + public ArtifactDefinition findArtifactOnComponentInstance(ComponentInstance componentInstance, String artifactId) { + List allInstanceArtifacts = getAllInstanceArtifacts(componentInstance); + return findById(allInstanceArtifacts, artifactId); + } + + private ArtifactDefinition findById(List artifacts, String artifactId) { + return artifacts.stream() + .filter(artifact -> artifact.getUniqueId().equals(artifactId)) + .findFirst().orElse(null); + } + + private List getAllComponentsArtifacts(Component component, ComponentTypeEnum componentType) { + Map deploymentArtifacts = Optional.ofNullable(component.getDeploymentArtifacts()).orElse(Collections.emptyMap()); + Map artifacts = Optional.ofNullable(component.getArtifacts()).orElse(Collections.emptyMap()); + Map serviceApiArtifacts = Collections.emptyMap(); + if (componentType.equals(ComponentTypeEnum.SERVICE)) { + serviceApiArtifacts = Optional.ofNullable(((Service) component).getServiceApiArtifacts()).orElse(Collections.emptyMap()); + } + return appendAllArtifacts(deploymentArtifacts, artifacts, serviceApiArtifacts); + } + + private List getAllInstanceArtifacts(ComponentInstance instance) { + Map deploymentArtifacts = Optional.ofNullable(instance.getDeploymentArtifacts()).orElse(Collections.emptyMap()); + Map artifacts = Optional.ofNullable(instance.getArtifacts()).orElse(Collections.emptyMap()); + return appendAllArtifacts(deploymentArtifacts, artifacts); + } + + @SafeVarargs + private final List appendAllArtifacts(Map... artifacts) { + List allArtifacts = new ArrayList<>(); + Arrays.stream(artifacts).forEach(a -> allArtifacts.addAll(a.values())); + return allArtifacts; + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java index 6739d28bd4..83c8183a01 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java @@ -43,6 +43,7 @@ import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.be.components.ArtifactsResolver; import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum; import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic; @@ -180,6 +181,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { @Autowired NodeTemplateOperation nodeTemplateOperation; + @Autowired + private ArtifactsResolver artifactsResolver; + public ArtifactsBusinessLogic() { // defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes(); // if ((defaultHeatTimeout == null) || (defaultHeatTimeout < 1)) { @@ -609,22 +613,22 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) { List list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId); - if (list != null && !list.isEmpty()){ + if (list != null && !list.isEmpty()) { resMap = list.stream().collect(Collectors.toMap(a -> a.getArtifactLabel(), a -> a)); - }else{ + } else { resMap = new HashMap<>(); } resultOp = Either.left(resMap); return resultOp; } else { - Either, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType.getNodeType(), false, groupType, componentId ); + Either, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType.getNodeType(), false, groupType, componentId); if (artifactsMapStatus.isRight()) { if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) { ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION); log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId); resultOp = Either.right(responseFormat); - }else{ + } else { resMap = new HashMap<>(); resultOp = Either.left(resMap); } @@ -934,7 +938,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (validateAndSetArtifactname.isRight()) { return Either.right(validateAndSetArtifactname.right().value()); } - Either artifactById = findArtifactOnParentComponent(parentComponent, parentId, operation, artifactId); + Either artifactById = findArtifactOnParentComponent(parentComponent, componentType, parentId, operation, artifactId); if (artifactById.isRight()) { return Either.right(artifactById.right().value()); } @@ -1033,27 +1037,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return Either.left(artifactInfo); } - private Either findArtifactOnParentComponent(Component parentComponent, String parentId, ArtifactOperationInfo operation, String artifactId) { + private Either findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) { Either result = null; ArtifactDefinition foundArtifact = null; if (StringUtils.isNotEmpty(artifactId)) { - if (parentComponent.getUniqueId().equals(parentId)) { - if (parentComponent.getDeploymentArtifacts() != null) { - foundArtifact = parentComponent.getDeploymentArtifacts().values().stream().filter(e -> e.getUniqueId().equals(artifactId)).findFirst().orElse(null); - } - if (foundArtifact == null && parentComponent.getArtifacts() != null) { - foundArtifact = parentComponent.getArtifacts().values().stream().filter(e -> e.getUniqueId().equals(artifactId)).findFirst().orElse(null); - } - } else { - ComponentInstance instance = findComponentInstance(parentId, parentComponent); - if (instance.getDeploymentArtifacts() != null) { - foundArtifact = instance.getDeploymentArtifacts().values().stream().filter(e -> e.getUniqueId().equals(artifactId)).findFirst().orElse(null); - } - if (foundArtifact == null && instance.getArtifacts() != null) { - foundArtifact = instance.getArtifacts().values().stream().filter(e -> e.getUniqueId().equals(artifactId)).findFirst().orElse(null); - } - } + foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId); } if (foundArtifact != null && operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) { log.debug("Artifact {} already exist", artifactId); @@ -1069,6 +1058,17 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return result; } + private ArtifactDefinition findArtifact(Component parentComponent, ComponentTypeEnum componentType, String parentId, String artifactId) { + ArtifactDefinition foundArtifact; + if (parentComponent.getUniqueId().equals(parentId)) { + foundArtifact = artifactsResolver.findArtifactOnComponent(parentComponent, componentType, artifactId); + } else { + ComponentInstance instance = findComponentInstance(parentId, parentComponent); + foundArtifact = artifactsResolver.findArtifactOnComponentInstance(instance, artifactId); + } + return foundArtifact; + } + private Either validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) { ComponentTypeEnum parentComponentType = parentComponent.getComponentType(); ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType(); @@ -1254,11 +1254,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { for (GroupInstance groupInstance : groupInstances) { isUpdated = false; if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts().contains(artifactId)) { - groupInstance.getArtifacts().remove(artifactId); + groupInstance.getGroupInstanceArtifacts().remove(artifactId); isUpdated = true; } if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid().contains(foundArtifact.getArtifactUUID())) { - groupInstance.getArtifacts().remove(foundArtifact.getArtifactUUID()); + groupInstance.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID()); isUpdated = true; } if (isUpdated) { @@ -1278,7 +1278,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { if (isMandatory) { log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId); resetMandatoryArtifactFields(foundArtifact); - result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId); + result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId, true); } else if (cloneIsNeeded) { log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId); result = artifactToscaOperation.deleteArtifactWithClonnigOnGraph(componentId, foundArtifact, parentType, instanceId, false); @@ -2098,11 +2098,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return deploymentArtifacts; } ComponentInstance ri = getRI.left().value(); - if(ri.getDeploymentArtifacts() != null){ + if (ri.getDeploymentArtifacts() != null) { deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values()); } - } else if(parentComponent.getDeploymentArtifacts() !=null){ - deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values()); + } else if (parentComponent.getDeploymentArtifacts() != null) { + deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values()); } } return deploymentArtifacts; @@ -3145,7 +3145,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } } - if ( !found ){ + if (!found) { artifacts = resourceInstance.getArtifacts(); if (artifacts != null) { for (Map.Entry entry : artifacts.entrySet()) { @@ -3154,7 +3154,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { break; } } - } + } } } return found; @@ -3370,7 +3370,37 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { public Either generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier, boolean shouldLock, String instanceId) { String payload = generateHeatEnvPayload(artifactDefinition); - return generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, shouldLock, instanceId); + String prevUUID = artifactDefinition.getArtifactUUID(); + ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition); + Either generateResult = generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, shouldLock, instanceId); + if (generateResult.isLeft()) { + ArtifactDefinition updatedArtDef = generateResult.left().value(); + if (!prevUUID.equals(updatedArtDef.getArtifactUUID())) { + List componentInstances = component.getComponentInstances(); + if (componentInstances != null) { + Optional findFirst = componentInstances.stream().filter(ci -> ci.getUniqueId().equals(instanceId)).findFirst(); + if (findFirst.isPresent()) { + ComponentInstance relevantInst = findFirst.get(); + List updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst.getGroupInstances()); + + if (CollectionUtils.isNotEmpty(updatedGroupInstances)) { + updatedGroupInstances.forEach(gi -> { + gi.getGroupInstanceArtifacts().add(updatedArtDef.getUniqueId()); + gi.getGroupInstanceArtifactsUuid().add(updatedArtDef.getArtifactUUID()); + }); + Either, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, componentType, instanceId, updatedGroupInstances); + if (status.isRight()) { + log.debug("Failed to update groups of the component {}. ", component.getUniqueId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), clonedBeforeGenerate.getArtifactDisplayName()); + return Either.right(responseFormat); + } + } + } + } + } + } + + return generateResult; } private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) { @@ -3438,7 +3468,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter()); - // DE265919 fix Tal G + // DE265919 fix String result = sb.toString().replaceAll("\\\\n", "\n"); return result; @@ -3522,7 +3552,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { oldCheckSum = artifactDefinition.getArtifactChecksum(); artifactDefinition.setArtifactChecksum(newCheckSum); - artifactToscaOperation.updateUUID(artifactDefinition, oldCheckSum, artifactDefinition.getArtifactVersion()); +// artifactToscaOperation.updateUUID(artifactDefinition, oldCheckSum, artifactDefinition.getArtifactVersion()); artifactDefinition.setEsId(artifactDefinition.getUniqueId()); updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId); @@ -3530,6 +3560,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) { + artifactDefinition = updateArifactDefinitionStatus.left().value(); artifactData.setId(artifactDefinition.getUniqueId()); CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData); @@ -3965,7 +3996,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { String origMd5 = request.getHeader(Constants.MD5_HEADER); String userId = request.getHeader(Constants.USER_ID_HEADER); - Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata); + Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); if (getComponentRes.isRight()) { StorageOperationStatus status = getComponentRes.right().value(); log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); @@ -4026,7 +4057,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { String userId = request.getHeader(Constants.USER_ID_HEADER); ImmutablePair componentRiPair = null; - Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata); + Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); if (getComponentRes.isRight()) { StorageOperationStatus status = getComponentRes.right().value(); log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); @@ -4089,7 +4120,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { String origMd5 = request.getHeader(Constants.MD5_HEADER); String userId = request.getHeader(Constants.USER_ID_HEADER); - Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata); + Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); if (getComponentRes.isRight()) { StorageOperationStatus status = getComponentRes.right().value(); log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); @@ -4158,7 +4189,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { String userId = request.getHeader(Constants.USER_ID_HEADER); ImmutablePair componentRiPair = null; - Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata); + Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); if (getComponentRes.isRight()) { StorageOperationStatus status = getComponentRes.right().value(); log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); @@ -4223,7 +4254,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { String origMd5 = request.getHeader(Constants.MD5_HEADER); String userId = request.getHeader(Constants.USER_ID_HEADER); - Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata); + Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); if (getComponentRes.isRight()) { StorageOperationStatus status = getComponentRes.right().value(); log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); @@ -4288,7 +4319,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { String origMd5 = request.getHeader(Constants.MD5_HEADER); String userId = request.getHeader(Constants.USER_ID_HEADER); ImmutablePair componentRiPair = null; - Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata); + Either getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true); if (getComponentRes.isRight()) { StorageOperationStatus status = getComponentRes.right().value(); log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java index 84cf20dcfa..4fd4610ef9 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java @@ -28,8 +28,8 @@ import java.util.Optional; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.AttributeDefinition; import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -65,8 +65,8 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { * @param userId * @return AttributeDefinition if created successfully Or ResponseFormat */ - public Either createAttribute(String resourceId, AttributeDefinition newAttributeDef, String userId) { - Either result = null; + public Either createAttribute(String resourceId, PropertyDefinition newAttributeDef, String userId) { + Either result = null; Either resp = validateUserExists(userId, "create Attribute", false); if (resp.isRight()) { return Either.right(resp.right().value()); @@ -111,7 +111,7 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { // add the new attribute to resource on graph // need to get StorageOpaerationStatus and convert to ActionStatus from // componentsUtils - Either either = toscaOperationFacade.addAttributeOfResource(resource, newAttributeDef); + Either either = toscaOperationFacade.addAttributeOfResource(resource, newAttributeDef); if (either.isRight()) { result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName())); return result; @@ -126,7 +126,7 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { } - private boolean isAttributeExist(List attributes, String resourceUid, String propertyName) { + private boolean isAttributeExist(List attributes, String resourceUid, String propertyName) { boolean isExist = false; if (attributes != null) { isExist = attributes.stream().filter(p -> Objects.equals(p.getName(), propertyName) && Objects.equals(p.getParentUniqueId(), resourceUid)).findAny().isPresent(); @@ -141,7 +141,7 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { * @param userId * @return */ - public Either getAttribute(String resourceId, String attributeId, String userId) { + public Either getAttribute(String resourceId, String attributeId, String userId) { Either resp = validateUserExists(userId, "get Attribute", false); if (resp.isRight()) { @@ -155,13 +155,13 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { } Resource resource = status.left().value(); - List attributes = resource.getAttributes(); + List attributes = resource.getAttributes(); if (attributes == null) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_NOT_FOUND, "")); } else { - Either result; + Either result; // verify attribute exist in resource - Optional optionalAtt = attributes.stream().filter(att -> att.getUniqueId().equals(attributeId) && att.getParentUniqueId().equals(resourceId)).findAny(); + Optional optionalAtt = attributes.stream().filter(att -> att.getUniqueId().equals(attributeId) && att.getParentUniqueId().equals(resourceId)).findAny(); if (optionalAtt.isPresent()) { result = Either.left(optionalAtt.get()); @@ -182,8 +182,8 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { * @param userId * @return */ - public Either updateAttribute(String resourceId, String attributeId, AttributeDefinition newAttDef, String userId) { - Either result = null; + public Either updateAttribute(String resourceId, String attributeId, PropertyDefinition newAttDef, String userId) { + Either result = null; StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); if (lockResult != StorageOperationStatus.OK) { @@ -205,7 +205,7 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { } // verify attribute exist in resource - Either eitherAttribute = getAttribute(resourceId, attributeId, userId); + Either eitherAttribute = getAttribute(resourceId, attributeId, userId); if (eitherAttribute.isRight()) { return Either.right(eitherAttribute.right().value()); } @@ -228,7 +228,7 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { } - Either eitherAttUpdate = toscaOperationFacade.updateAttributeOfResource(resource, newAttDef); + Either eitherAttUpdate = toscaOperationFacade.updateAttributeOfResource(resource, newAttDef); if (eitherAttUpdate.isRight()) { log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId, eitherAttUpdate.right().value()); @@ -253,9 +253,9 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { * @param userId * @return */ - public Either deleteAttribute(String resourceId, String attributeId, String userId) { + public Either deleteAttribute(String resourceId, String attributeId, String userId) { - Either result = null; + Either result = null; Either resp = validateUserExists(userId, "delete Attribute", false); if (resp.isRight()) { @@ -283,7 +283,7 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { } // verify attribute exist in resource - Either eitherAttributeExist = getAttribute(resourceId, attributeId, userId); + Either eitherAttributeExist = getAttribute(resourceId, attributeId, userId); if (eitherAttributeExist.isRight()) { return Either.right(eitherAttributeExist.right().value()); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java index f880883438..5ee5c88f69 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java @@ -21,38 +21,31 @@ package org.openecomp.sdc.be.components.impl; import java.util.ArrayList; -import java.util.Collection; import java.util.EnumMap; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; -import java.util.function.Function; -import java.util.function.Predicate; import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum; -import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter; -import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.CapReqDef; -import org.openecomp.sdc.be.model.CapabilityDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.ComponentInstanceInput; @@ -64,13 +57,10 @@ import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.Operation; import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.RequirementDefinition; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.cache.ComponentCache; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.ComponentOperation; -import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.openecomp.sdc.be.resources.data.ComponentMetadataData; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; @@ -87,9 +77,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import com.datastax.driver.core.UserType.Field; -import com.wordnik.swagger.models.auth.In; - import fj.data.Either; public abstract class ComponentBusinessLogic extends BaseBusinessLogic { @@ -283,40 +270,43 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { } - public Either validateConformanceLevel(String componentId, ComponentTypeEnum componentTypeEnum, String userId) { + public Either validateConformanceLevel(String componentUuid, ComponentTypeEnum componentTypeEnum, String userId) { log.trace("validate conformance level"); if (componentTypeEnum != ComponentTypeEnum.SERVICE) { - log.error("conformance level validation for non service component, id {}", componentId); + log.error("conformance level validation for non service component, id {}", componentUuid); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT); return Either.right(errorResponse); } Either resp = validateUserExists(userId, "validateConformanceLevel", false); if (resp.isRight()) { - log.error("can't validate conformance level, user is not validated, id {}, userId {}", componentId, userId); + log.error("can't validate conformance level, user is not validated, uuid {}, userId {}", componentUuid, userId); return Either.right(resp.right().value()); } - ComponentParametersView filter = new ComponentParametersView(true); - Either eitherComponent = validateComponentExists(componentId, componentTypeEnum, filter); + Either eitherComponent = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, null); if (eitherComponent.isRight()) { - log.error("can't validate conformance level, component not found, id {}", componentId); - BeEcompErrorManager.getInstance().logBeComponentMissingError("validateConformanceLevel", componentTypeEnum.getValue(), componentId); - return Either.right(eitherComponent.right().value()); + log.error("can't validate conformance level, component not found, uuid {}", componentUuid); + BeEcompErrorManager.getInstance().logBeComponentMissingError("validateConformanceLevel", componentTypeEnum.getValue(), componentUuid); + + StorageOperationStatus status = eitherComponent.right().value(); + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(status, componentTypeEnum); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus); + return Either.right(responseFormat); } - Component component = eitherComponent.left().value(); - if (component.getConformanceLevel() == null || "".equals(component.getConformanceLevel())) { - log.error("component conformance level property is null or empty, id {}", componentId); + String componentConformanceLevel = eitherComponent.left().value().getMetadataDataDefinition().getConformanceLevel(); + if (StringUtils.isBlank(componentConformanceLevel)) { + log.error("component conformance level property is null or empty, uuid {}", componentUuid); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); return Either.right(errorResponse); } String configConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getMinToscaConformanceLevel(); Boolean result = true; - if (CommonBeUtils.conformanceLevelCompare(component.getConformanceLevel(), configConformanceLevel) < 0) { - log.error("invalid asset conformance level, id {}, asset conformanceLevel {}, config conformanceLevel {}", componentId, component.getConformanceLevel(), configConformanceLevel); + if (CommonBeUtils.conformanceLevelCompare(componentConformanceLevel, configConformanceLevel) < 0) { + log.error("invalid asset conformance level, uuid {}, asset conformanceLevel {}, config conformanceLevel {}", componentUuid, componentConformanceLevel, configConformanceLevel); result = false; } log.trace("conformance level validation finished"); @@ -1154,9 +1144,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { return Either.right(fetchAndSetLatestGeneric.right().value()); Resource genericTypeResource = fetchAndSetLatestGeneric.left().value(); if(null == currentGenericType || !currentGenericType.equals(genericTypeResource.getToscaResourceName()) || !currentGenericVersion.equals(genericTypeResource.getVersion())){ - List genericTypeProps = genericTypeResource.getProperties(); - List genericTypeInputs = null == genericTypeProps? null : convertGenericTypePropertiesToInputsDefintion(genericTypeProps, genericTypeResource.getUniqueId()); - shouldUpgrade = upgradeToLatestGeneric(clonedComponent, genericTypeInputs); + shouldUpgrade = upgradeToLatestGeneric(clonedComponent, genericTypeResource); if(!shouldUpgrade) { reverntUpdateOfGenericVersion(clonedComponent, currentGenericType, currentGenericVersion); } @@ -1169,12 +1157,37 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { clonedComponent.setDerivedFromGenericVersion(currentGenericVersion); } + private Either, String> validateNoConflictingProperties(List currentList, List upgradedList) { + Map currentMap = ToscaDataDefinition.listToMapByName(currentList); + Map upgradedMap = ToscaDataDefinition.listToMapByName(upgradedList); + return ToscaDataDefinition.mergeDataMaps(upgradedMap, currentMap, true); + } - private boolean upgradeToLatestGeneric(Component componentToCheckOut, List upgradedList) { - - if (!componentToCheckOut.shouldGenerateInputs()) - return true; + private boolean shouldUpgradeNodeType(Component componentToCheckOut, Resource latestGeneric){ + List genericTypeProps = latestGeneric.getProperties(); + Either, String> validMerge = validateNoConflictingProperties(genericTypeProps, ((Resource)componentToCheckOut).getProperties()); + if (validMerge.isRight()) { + log.debug("property {} cannot be overriden, check out performed without upgrading to latest generic", validMerge.right().value()); + return false; + } + List genericTypeAttributes = latestGeneric.getAttributes(); + validMerge = validateNoConflictingProperties(genericTypeAttributes, ((Resource)componentToCheckOut).getAttributes()); + if (validMerge.isRight()) { + log.debug("attribute {} cannot be overriden, check out performed without upgrading to latest generic", validMerge.right().value()); + return false; + } + return true; + } + + private boolean upgradeToLatestGeneric(Component componentToCheckOut, Resource latestGeneric) { + + if (!componentToCheckOut.shouldGenerateInputs()) { + //node type - validate properties and attributes + return shouldUpgradeNodeType(componentToCheckOut, latestGeneric); + } + List genericTypeProps = latestGeneric.getProperties(); + List genericTypeInputs = null == genericTypeProps? null : convertGenericTypePropertiesToInputsDefintion(genericTypeProps, latestGeneric.getUniqueId()); List currentList = new ArrayList<>(); // nullify existing ownerId from existing list and merge into updated list if (null != componentToCheckOut.getInputs()) { @@ -1184,20 +1197,20 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { currentList.add(copy); } } - if (null == upgradedList) { + if (null == genericTypeInputs) { componentToCheckOut.setInputs(currentList); return true; } - Map currentMap = PropertyDataDefinition.listToMapByName(currentList); - Map upgradedMap = PropertyDataDefinition.listToMapByName(upgradedList); - Either, String> eitherMerged = PropertyDataDefinition.mergeProperties(upgradedMap, currentMap, true); + + Either, String> eitherMerged = validateNoConflictingProperties(genericTypeInputs, currentList); if (eitherMerged.isRight()) { - log.debug("property {} cannot be overriden, check out performed without upgrading to latest generic", eitherMerged.right().value()); + log.debug("input {} cannot be overriden, check out performed without upgrading to latest generic", eitherMerged.right().value()); return false; } componentToCheckOut.setInputs(new ArrayList(eitherMerged.left().value().values())); return true; } + private List getFilteredInstances(Component component, List resourceTypes) { List filteredInstances = null; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java index 1623375926..203a63894b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java @@ -51,7 +51,6 @@ import org.openecomp.sdc.be.info.CreateAndAssotiateInfo; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceAttribute; import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.ComponentParametersView; @@ -338,6 +337,10 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) { String type = artifact.getArtifactType(); + + if ( !type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType()) ){ + finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact); + } if (!(type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()))) { continue; @@ -351,9 +354,6 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } ArtifactDefinition artifactDefinition = createHeatEnvPlaceHolder.left().value(); - //put heat - finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact); - //put env finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition); @@ -890,12 +890,12 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } } - private Either updateAttributeValue(ComponentInstanceAttribute attribute, String resourceInstanceId) { - Either eitherAttribute = componentInstanceOperation.updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true); - Either result; + private Either updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) { + Either eitherAttribute = componentInstanceOperation.updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true); + Either result; if (eitherAttribute.isLeft()) { log.debug("Attribute value {} was updated on graph.", attribute.getValueUniqueUid()); - ComponentInstanceAttribute instanceAttribute = eitherAttribute.left().value(); + ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value(); result = Either.left(instanceAttribute); @@ -910,9 +910,9 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return result; } - private Either createAttributeValue(ComponentInstanceAttribute attribute, String resourceInstanceId) { + private Either createAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) { - Either result; + Either result; Wrapper indexCounterWrapper = new Wrapper<>(); Wrapper errorWrapper = new Wrapper<>(); @@ -921,10 +921,10 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { if (!errorWrapper.isEmpty()) { result = Either.right(errorWrapper.getInnerElement()); } else { - Either eitherAttribute = componentInstanceOperation.addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true); + Either eitherAttribute = componentInstanceOperation.addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true); if (eitherAttribute.isLeft()) { log.debug("Attribute value was added to resource instance {}", resourceInstanceId); - ComponentInstanceAttribute instanceAttribute = eitherAttribute.left().value(); + ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value(); result = Either.left(instanceAttribute); } else { @@ -948,8 +948,8 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { * @param userId * @return */ - public Either createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceAttribute attribute, String userId) { - Either result = null; + public Either createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty attribute, String userId) { + Either result = null; Wrapper errorWrapper = new Wrapper<>(); validateUserExist(userId, "create Or Update Attribute Value", errorWrapper); @@ -1104,8 +1104,6 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)))); } - - try { List instanceProperties = containerComponent.getComponentInstancesProperties().get(resourceInstanceId); @@ -1122,6 +1120,10 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); return resultOp; } + List path = new ArrayList<>(); + path.add(foundResourceInstance.getUniqueId()); + property.setPath(path); + foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString()); Either updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); @@ -1603,7 +1605,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return resultOp; } - List groupInstances = currentResourceInstance.getGroupInstances(); + // List groupInstances = currentResourceInstance.getGroupInstances(); Map deploymentArtifacts = currentResourceInstance.getDeploymentArtifacts(); resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType); if (resultOp.isRight()) { @@ -1639,13 +1641,15 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return resultOp; } - if (CollectionUtils.isNotEmpty(groupInstances)) { + /* if (CollectionUtils.isNotEmpty(groupInstances)) { StorageOperationStatus addGroupsToComponentInstance = toscaOperationFacade.addGroupInstancesToComponentInstance(containerComponent, updatedComponentInstance, groupInstances); if (addGroupsToComponentInstance != StorageOperationStatus.OK) { BeEcompErrorManager.getInstance().logInternalFlowError("ChangeComponentInstanceVersion", "Failed to associate groups to new component instance", ErrorSeverity.ERROR); resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); return resultOp; } + + } if (MapUtils.isNotEmpty(deploymentArtifacts)) { StorageOperationStatus addDeploymentArtifactsToComponentInstance = toscaOperationFacade.addDeploymentArtifactsToComponentInstance(containerComponent, updatedComponentInstance, deploymentArtifacts); @@ -1654,7 +1658,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic { resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); return resultOp; } - } + }*/ ComponentParametersView filter = new ComponentParametersView(true); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java index ae6237897a..3d280ab7ca 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java @@ -289,7 +289,7 @@ public class CsarValidationUtils { return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID)); } byte[] toscaMetaBytes = csar.get(TOSCA_METADATA_FILE); - // Tal && exchanged for || + // && exchanged for || if (toscaMetaBytes == null || toscaMetaBytes.length == 0) { log.debug("TOSCA-Metadata/TOSCA.meta file not found in csar, csar ID {}", csarUUID); BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java index 958adc0eef..d8746737d3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java @@ -990,9 +990,9 @@ public class ElementBusinessLogic extends BaseBusinessLogic { } Map> resMap = new HashMap<>(); - Either, StorageOperationStatus> resResources = toscaOperationFacade.getCatalogComponents(ComponentTypeEnum.RESOURCE); + Either, StorageOperationStatus> resResources = toscaOperationFacade.getCatalogComponents(ComponentTypeEnum.RESOURCE, true); if (resResources.isLeft()) { - Either, StorageOperationStatus> resServices = toscaOperationFacade.getCatalogComponents(ComponentTypeEnum.SERVICE); + Either, StorageOperationStatus> resServices = toscaOperationFacade.getCatalogComponents(ComponentTypeEnum.SERVICE, true); if (resServices.isLeft()) { // Either, StorageOperationStatus> resProducts = productOperation.getProductCatalogData(false); // if (resProducts.isLeft()) { @@ -1021,7 +1021,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic { } if (filters == null || filters.isEmpty()) { - Either, StorageOperationStatus> componentsList = toscaOperationFacade.getCatalogComponents(assetTypeEnum); + Either, StorageOperationStatus> componentsList = toscaOperationFacade.getCatalogComponents(assetTypeEnum, false); if(componentsList.isRight()) { return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentsList.right().value()))); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java index ba08f11928..f298b0f203 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java @@ -79,6 +79,7 @@ import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.GroupOperation; import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; @@ -112,7 +113,6 @@ public class GroupBusinessLogic extends BaseBusinessLogic { @javax.annotation.Resource private GroupTypeOperation groupTypeOperation; - @Autowired ArtifactsOperations artifactsOperation; @@ -121,7 +121,6 @@ public class GroupBusinessLogic extends BaseBusinessLogic { @Autowired private ApplicationDataTypeCache dataTypeCache; - /** * * 1. validate user exist @@ -145,67 +144,39 @@ public class GroupBusinessLogic extends BaseBusinessLogic { * @param inTransaction * @return */ - /*public Either createGroup(String componentId, String userId, ComponentTypeEnum componentType, GroupDefinition groupDefinition, boolean inTransaction) { - - Either result = null; - - try { - Either validateUserExists = validateUserExists(userId, CREATE_GROUP, inTransaction); - - if (validateUserExists.isRight()) { - result = Either.right(validateUserExists.right().value()); - return result; - } - - User user = validateUserExists.left().value(); - // 5. check service/resource existence - // 6. check service/resource check out - // 7. user is owner of checkout state - org.openecomp.sdc.be.model.Component component = null; - - // String realComponentId = componentType == - // ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId; - String realComponentId = componentId; - - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreGroups(false); - componentParametersView.setIgnoreArtifacts(false); - componentParametersView.setIgnoreUsers(false); - componentParametersView.setIgnoreComponentInstances(false); - - Either validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView); - - if (validateComponent.isRight()) { - result = Either.right(validateComponent.right().value()); - return result; - } - component = validateComponent.left().value(); - Either canWork = validateCanWorkOnComponent(component, userId); - if (canWork.isRight()) { - result = Either.right(canWork.right().value()); - return result; - } - - result = this.createGroup(component, user, componentType, groupDefinition, inTransaction); - return result; - - } finally { - - if (false == inTransaction) { - - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on create group."); - titanDao.rollback(); - } else { - log.debug("Going to execute commit on create group."); - titanDao.commit(); - } - - } - - } - }*/ + /* + * public Either createGroup(String componentId, String userId, ComponentTypeEnum componentType, GroupDefinition groupDefinition, boolean inTransaction) { + * + * Either result = null; + * + * try { Either validateUserExists = validateUserExists(userId, CREATE_GROUP, inTransaction); + * + * if (validateUserExists.isRight()) { result = Either.right(validateUserExists.right().value()); return result; } + * + * User user = validateUserExists.left().value(); // 5. check service/resource existence // 6. check service/resource check out // 7. user is owner of checkout state org.openecomp.sdc.be.model.Component component = null; + * + * // String realComponentId = componentType == // ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId; String realComponentId = componentId; + * + * ComponentParametersView componentParametersView = new ComponentParametersView(); componentParametersView.disableAll(); componentParametersView.setIgnoreGroups(false); componentParametersView.setIgnoreArtifacts(false); + * componentParametersView.setIgnoreUsers(false); componentParametersView.setIgnoreComponentInstances(false); + * + * Either validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView); + * + * if (validateComponent.isRight()) { result = Either.right(validateComponent.right().value()); return result; } component = validateComponent.left().value(); Either canWork = validateCanWorkOnComponent(component, + * userId); if (canWork.isRight()) { result = Either.right(canWork.right().value()); return result; } + * + * result = this.createGroup(component, user, componentType, groupDefinition, inTransaction); return result; + * + * } finally { + * + * if (false == inTransaction) { + * + * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); } + * + * } + * + * } } + */ private String getComponentTypeForResponse(org.openecomp.sdc.be.model.Component component) { String componentTypeForResponse = "SERVICE"; @@ -235,7 +206,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } List currentArtifacts = deploymentArtifacts.values().stream().map(p -> p.getUniqueId()).collect(Collectors.toList()); - log.debug("The deployment artifacts of component {} are {}" , component.getNormalizedName(), deploymentArtifacts); + log.debug("The deployment artifacts of component {} are {}", component.getNormalizedName(), deploymentArtifacts); if (false == currentArtifacts.containsAll(artifacts)) { BeEcompErrorManager.getInstance().logInvalidInputError(context, "Not all artifacts belongs to component " + component.getNormalizedName(), ErrorSeverity.INFO); return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); @@ -285,48 +256,48 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } } -// ComponentOperation componentOperation = getComponentOperationByParentComponentType(componentType); -// if (componentOperation instanceof ResourceOperation) { -// ResourceOperation resourceOperation = (ResourceOperation) componentOperation; -// -// for (Entry groupMember : groupMembers.entrySet()) { -// -// String componentInstName = groupMember.getKey(); -// String componentInstUid = groupMember.getValue(); -// -// ComponentInstance componentInstance = compInstUidToCompInstMap.get(componentInstUid); -// String componentUid = componentInstance.getComponentUid(); -// List componentToscaNames = new ArrayList<>(); -// TitanOperationStatus status = resourceOperation.fillResourceDerivedListFromGraph(componentUid, componentToscaNames); -// if (status != TitanOperationStatus.OK) { -// BeEcompErrorManager.getInstance().logInternalFlowError(CREATE_GROUP, "Cannot find tosca list of component id " + componentUid, ErrorSeverity.ERROR); -// return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); -// } -// -// log.debug("The tosca names of component id {} are {}", componentUid, memberToscaTypes); -// -// boolean found = false; -// for (String memberToscaType : memberToscaTypes) { -// if (componentToscaNames.contains(memberToscaType)) { -// found = true; -// break; -// } -// } -// if (found == false) { -// BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, -// "No tosca types from " + memberToscaTypes + " can be found in the tosca list " + componentToscaNames + " of component " + componentInstance.getNormalizedName(), ErrorSeverity.INFO); -// /* -// * # %1 - member name # %2 - group name # %3 - group type -// */ -// return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_TOSCA_NAME_OF_COMPONENT_INSTANCE, componentInstName, groupName, groupType)); -// } else { -// log.debug("Component instance {} fits to one of the required tosca types", componentInstance.getNormalizedName()); -// } -// } -// } else { -// BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "Cannot find tosca list since it is not supported for product", ErrorSeverity.ERROR); -// return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); -// } + // ComponentOperation componentOperation = getComponentOperationByParentComponentType(componentType); + // if (componentOperation instanceof ResourceOperation) { + // ResourceOperation resourceOperation = (ResourceOperation) componentOperation; + // + // for (Entry groupMember : groupMembers.entrySet()) { + // + // String componentInstName = groupMember.getKey(); + // String componentInstUid = groupMember.getValue(); + // + // ComponentInstance componentInstance = compInstUidToCompInstMap.get(componentInstUid); + // String componentUid = componentInstance.getComponentUid(); + // List componentToscaNames = new ArrayList<>(); + // TitanOperationStatus status = resourceOperation.fillResourceDerivedListFromGraph(componentUid, componentToscaNames); + // if (status != TitanOperationStatus.OK) { + // BeEcompErrorManager.getInstance().logInternalFlowError(CREATE_GROUP, "Cannot find tosca list of component id " + componentUid, ErrorSeverity.ERROR); + // return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + // } + // + // log.debug("The tosca names of component id {} are {}", componentUid, memberToscaTypes); + // + // boolean found = false; + // for (String memberToscaType : memberToscaTypes) { + // if (componentToscaNames.contains(memberToscaType)) { + // found = true; + // break; + // } + // } + // if (found == false) { + // BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, + // "No tosca types from " + memberToscaTypes + " can be found in the tosca list " + componentToscaNames + " of component " + componentInstance.getNormalizedName(), ErrorSeverity.INFO); + // /* + // * # %1 - member name # %2 - group name # %3 - group type + // */ + // return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_TOSCA_NAME_OF_COMPONENT_INSTANCE, componentInstName, groupName, groupType)); + // } else { + // log.debug("Component instance {} fits to one of the required tosca types", componentInstance.getNormalizedName()); + // } + // } + // } else { + // BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "Cannot find tosca list since it is not supported for product", ErrorSeverity.ERROR); + // return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + // } } @@ -340,21 +311,12 @@ public class GroupBusinessLogic extends BaseBusinessLogic { * @param inTransaction * @return */ - /*public Either updateGroupVersion(GroupDefinition groupDefinition, boolean inTransaction) { - Either result = null; - List groupIdsToUpdateVersion = new ArrayList<>(); - groupIdsToUpdateVersion.add(groupDefinition.getUniqueId()); - Either, StorageOperationStatus> updateGroupVersion = updateGroupVersion(groupIdsToUpdateVersion, inTransaction); - if (updateGroupVersion.isLeft()) { - result = Either.left(updateGroupVersion.left().value().get(0)); - } else { - log.debug("Failed to update group version. Status is {} ", updateGroupVersion.right().value()); - result = Either.right(updateGroupVersion.right().value()); - } - return result; - }*/ - - + /* + * public Either updateGroupVersion(GroupDefinition groupDefinition, boolean inTransaction) { Either result = null; List groupIdsToUpdateVersion = new + * ArrayList<>(); groupIdsToUpdateVersion.add(groupDefinition.getUniqueId()); Either, StorageOperationStatus> updateGroupVersion = updateGroupVersion(groupIdsToUpdateVersion, inTransaction); if (updateGroupVersion.isLeft()) + * { result = Either.left(updateGroupVersion.left().value().get(0)); } else { log.debug("Failed to update group version. Status is {} ", updateGroupVersion.right().value()); result = Either.right(updateGroupVersion.right().value()); } return + * result; } + */ /** * Update list of groups versions @@ -363,52 +325,44 @@ public class GroupBusinessLogic extends BaseBusinessLogic { * @param inTransaction * @return */ - /*public Either, StorageOperationStatus> updateGroupVersion(List groupsUniqueId, boolean inTransaction) { - - Either, StorageOperationStatus> result = null; - - try { - - result = groupOperation.updateGroupVersion(groupsUniqueId, true); - - return result; - - } finally { - - if (false == inTransaction) { - - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on create group."); - titanDao.rollback(); - } else { - log.debug("Going to execute commit on create group."); - titanDao.commit(); - } - - } - - } + /* + * public Either, StorageOperationStatus> updateGroupVersion(List groupsUniqueId, boolean inTransaction) { + * + * Either, StorageOperationStatus> result = null; + * + * try { + * + * result = groupOperation.updateGroupVersion(groupsUniqueId, true); + * + * return result; + * + * } finally { + * + * if (false == inTransaction) { + * + * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); } + * + * } + * + * } + * + * } + */ - }*/ + /** + * Update GroupDefinition metadata + * + * @param componentId + * @param user + * @param componentType + * @param updatedGroup + * @param inTransaction + * @return + */ + public Either validateAndUpdateGroupMetadata(String componentId, User user, ComponentTypeEnum componentType, GroupDefinition updatedGroup, boolean inTransaction) { -/** - * Update GroupDefinition metadata - * @param componentId - * @param user - * @param componentType - * @param updatedGroup - * @param inTransaction - * @return - */ - public Either validateAndUpdateGroupMetadata( - String componentId, - User user, - ComponentTypeEnum componentType, - GroupDefinition updatedGroup, - boolean inTransaction) { - Either result = null; - try{ + try { // Validate user exist Either validateUserExists = validateUserExists(user.getUserId(), UPDATE_GROUP, inTransaction); if (validateUserExists.isRight()) { @@ -429,14 +383,14 @@ public class GroupBusinessLogic extends BaseBusinessLogic { return result; } List currentGroups = component.getGroups(); - if(CollectionUtils.isEmpty(currentGroups)){ + if (CollectionUtils.isEmpty(currentGroups)) { log.error("Failed to update the metadata of group {} on component {}. The status is {}. ", updatedGroup.getName(), component.getName(), ActionStatus.GROUP_IS_MISSING); result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, updatedGroup.getName(), component.getName(), component.getComponentType().getValue())); return result; } // Validate groups exists in the component Optional currentGroupOpt = currentGroups.stream().filter(g -> g.getUniqueId().equals(updatedGroup.getUniqueId())).findAny(); - if(!currentGroupOpt.isPresent()){ + if (!currentGroupOpt.isPresent()) { log.error("Failed to update the metadata of group {} on component {}. The status is {}. ", updatedGroup.getName(), component.getName(), ActionStatus.GROUP_IS_MISSING); result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, updatedGroup.getName(), component.getName(), component.getComponentType().getValue())); return result; @@ -451,14 +405,14 @@ public class GroupBusinessLogic extends BaseBusinessLogic { if (!currentGroup.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) { log.error("Failed to update the metadata of group {}. Group type is {} and different then: {}", currentGroup.getName(), currentGroup.getType(), Constants.DEFAULT_GROUP_VF_MODULE); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_TYPE, updatedGroup.getType()); - result = Either.right(responseFormat); + result = Either.right(responseFormat); return result; } result = updateGroupMetadata(component, currentGroup, updatedGroup); return result; - + } finally { - if(result.isLeft()){ + if (result.isLeft()) { titanDao.commit(); } else { titanDao.rollback(); @@ -466,15 +420,15 @@ public class GroupBusinessLogic extends BaseBusinessLogic { graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); } } - + private Either updateGroupMetadata(Component component, GroupDefinition currentGroup, GroupDefinition updatedGroup) { String currentGroupName = currentGroup.getName(); Either result = validateAndUpdateGroupMetadata(currentGroup, updatedGroup); - - if(result.isRight()){ + + if (result.isRight()) { log.debug("Failed to validate a metadata of the group {} on component {}. ", updatedGroup.getName(), component.getName()); } - if(result.isLeft()){ + if (result.isLeft()) { result = updateGroup(component, currentGroup, currentGroupName); } return result; @@ -483,25 +437,25 @@ public class GroupBusinessLogic extends BaseBusinessLogic { private Either updateGroup(Component component, GroupDefinition updatedGroup, String currentGroupName) { Either handleGroupRes; Either result = null; - if(updatedGroup.getName().equals(currentGroupName)){ + if (updatedGroup.getName().equals(currentGroupName)) { handleGroupRes = groupsOperation.updateGroup(component, updatedGroup); - if(handleGroupRes.isRight()){ + if (handleGroupRes.isRight()) { log.debug("Failed to update a metadata of the group {} on component {}. ", updatedGroup.getName(), component.getName()); result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(handleGroupRes.right().value()))); } } else { StorageOperationStatus deleteStatus = groupsOperation.deleteGroup(component, currentGroupName); - if(deleteStatus != StorageOperationStatus.OK){ + if (deleteStatus != StorageOperationStatus.OK) { log.debug("Failed to delete the group {} from component {}. ", updatedGroup.getName(), component.getName()); - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteStatus))); + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteStatus))); } handleGroupRes = groupsOperation.addGroup(component, updatedGroup); - if(handleGroupRes.isRight()){ + if (handleGroupRes.isRight()) { log.debug("Failed to add the group {} to component {}. ", updatedGroup.getName(), component.getName()); result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(handleGroupRes.right().value()))); } } - if(result == null){ + if (result == null) { result = Either.left(updatedGroup); } return result; @@ -509,6 +463,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { /** * Validate and Update Group Property + * * @param componentId * @param groupUniqueId * @param user @@ -517,43 +472,36 @@ public class GroupBusinessLogic extends BaseBusinessLogic { * @param inTransaction * @return */ - public Either, ResponseFormat> validateAndUpdateGroupProperties( - String componentId, - String groupUniqueId, - User user, - ComponentTypeEnum componentType, - List groupPropertiesToUpdate, boolean inTransaction) { - + public Either, ResponseFormat> validateAndUpdateGroupProperties(String componentId, String groupUniqueId, User user, ComponentTypeEnum componentType, List groupPropertiesToUpdate, boolean inTransaction) { + Either, ResponseFormat> result = Either.left(groupPropertiesToUpdate); - try{ + try { Optional optionalGroupConnectedToVf = null; GroupDefinition currentGroup = null; StorageOperationStatus lockResult = graphLockOperation.lockComponent(componentId, componentType.getNodeType()); - if( lockResult != StorageOperationStatus.OK ){ - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse( - lockResult, componentType), componentId)); + if (lockResult != StorageOperationStatus.OK) { + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult, componentType), componentId)); } - if( result.isLeft() ){ - //VF exist because lock succedded + if (result.isLeft()) { + // VF exist because lock succedded Resource vf = (Resource) toscaOperationFacade.getToscaElement(componentId).left().value(); - optionalGroupConnectedToVf = - //All groups on resource + optionalGroupConnectedToVf = + // All groups on resource vf.getGroups().stream(). - //Filter in group sent is part of VF groups - filter( e -> e.getUniqueId().equals(groupUniqueId)). - //Collect - findAny(); - if( !optionalGroupConnectedToVf.isPresent() ){ - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, - groupUniqueId, vf.getName(), ComponentTypeEnum.RESOURCE.getValue())); + // Filter in group sent is part of VF groups + filter(e -> e.getUniqueId().equals(groupUniqueId)). + // Collect + findAny(); + if (!optionalGroupConnectedToVf.isPresent()) { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, groupUniqueId, vf.getName(), ComponentTypeEnum.RESOURCE.getValue())); } } - - if( result.isLeft() ){ + + if (result.isLeft()) { currentGroup = optionalGroupConnectedToVf.get(); result = validateGroupPropertyAndResetEmptyValue(currentGroup, groupPropertiesToUpdate); } - if( result.isLeft() ){ + if (result.isLeft()) { result = updateGroupPropertiesValue(componentId, currentGroup, groupPropertiesToUpdate, inTransaction); if (result.isRight()) { BeEcompErrorManager.getInstance().logBeSystemError("Update GroupProperties"); @@ -561,49 +509,47 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } } - } - catch(Exception e){ + } catch (Exception e) { log.debug("Error in validateAndUpdateGroupProperty {}", e); result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - finally{ + } finally { graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); } return result; } + private void resetEmptyValueWithDefaults(List groupPropertiesToUpdate, GroupDefinition originalGroup) { Map originalProperties = - //Stream of original properties from group + // Stream of original properties from group originalGroup.convertToGroupProperties().stream(). - //Collecting to map with name as key - collect(Collectors.toMap(e -> e.getName(), e -> e)); - for( GroupProperty gp : groupPropertiesToUpdate){ - if( StringUtils.isEmpty(gp.getValue())){ + // Collecting to map with name as key + collect(Collectors.toMap(e -> e.getName(), e -> e)); + for (GroupProperty gp : groupPropertiesToUpdate) { + if (StringUtils.isEmpty(gp.getValue())) { gp.setValue(originalProperties.get(gp.getName()).getDefaultValue()); } } - + } - private Either, ResponseFormat> validateGroupPropertyAndResetEmptyValue( - GroupDefinition originalGroup, List groupPropertiesToUpdate) { - + private Either, ResponseFormat> validateGroupPropertyAndResetEmptyValue(GroupDefinition originalGroup, List groupPropertiesToUpdate) { + Either, ResponseFormat> ret = validateOnlyValueChanged(groupPropertiesToUpdate, originalGroup); if (ret.isLeft()) { resetEmptyValueWithDefaults(groupPropertiesToUpdate, originalGroup); } if (ret.isLeft()) { // Validate Type Match Value - Optional optionalError = - //Stream of group properties + Optional optionalError = + // Stream of group properties groupPropertiesToUpdate.stream(). - //Validate each and map to returned Strorage status value - map( e -> groupOperation .validateAndUpdatePropertyValue(e)). - //Keep only failed result if there is such - filter( e -> e != StorageOperationStatus.OK). - //collect - findFirst(); - if( optionalError.isPresent()){ + // Validate each and map to returned Strorage status value + map(e -> groupOperation.validateAndUpdatePropertyValue(e)). + // Keep only failed result if there is such + filter(e -> e != StorageOperationStatus.OK). + // collect + findFirst(); + if (optionalError.isPresent()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(optionalError.get()); ret = Either.right(componentsUtils.getResponseFormat(actionStatus)); } @@ -612,60 +558,54 @@ public class GroupBusinessLogic extends BaseBusinessLogic { if (ret.isLeft()) { // Validate min max ect... ret = validatePropertyBusinessLogic(groupPropertiesToUpdate, originalGroup); - } + } return ret; } - private Either, ResponseFormat> validatePropertyBusinessLogic( - List groupPropertiesToUpdate, GroupDefinition originalGroup) { + + private Either, ResponseFormat> validatePropertyBusinessLogic(List groupPropertiesToUpdate, GroupDefinition originalGroup) { Either, ResponseFormat> ret = Either.left(groupPropertiesToUpdate); - + Map nameValueMap = new HashMap<>(); - for(GroupProperty gp : groupPropertiesToUpdate){ - //Filter out non special properties which does not have Enum + for (GroupProperty gp : groupPropertiesToUpdate) { + // Filter out non special properties which does not have Enum final PropertyNames gpEnum = PropertyNames.findName(gp.getName()); - if( gpEnum != null ){ + if (gpEnum != null) { nameValueMap.put(gpEnum, gp.getValue()); } } - - if ( !MapUtils.isEmpty(nameValueMap) ) { - if (nameValueMap.containsKey(PropertyNames.INITIAL_COUNT) || nameValueMap.containsKey(PropertyNames.MAX_INSTANCES) - || nameValueMap.containsKey(PropertyNames.MIN_INSTANCES)) { - - + if (!MapUtils.isEmpty(nameValueMap)) { + + if (nameValueMap.containsKey(PropertyNames.INITIAL_COUNT) || nameValueMap.containsKey(PropertyNames.MAX_INSTANCES) || nameValueMap.containsKey(PropertyNames.MIN_INSTANCES)) { + Map oldValueMap = prepareMapWithOriginalProperties(originalGroup); - - Either eitherValid = validateMinMaxAndInitialCountPropertyLogicVF(nameValueMap, - oldValueMap); + + Either eitherValid = validateMinMaxAndInitialCountPropertyLogicVF(nameValueMap, oldValueMap); if (eitherValid.isRight()) { ret = Either.right(eitherValid.right().value()); } } - if (ret.isLeft() && (nameValueMap.containsKey(PropertyNames.VF_MODULE_DESCRIPTION) - || nameValueMap.containsKey(PropertyNames.VF_MODULE_LABEL))) { + if (ret.isLeft() && (nameValueMap.containsKey(PropertyNames.VF_MODULE_DESCRIPTION) || nameValueMap.containsKey(PropertyNames.VF_MODULE_LABEL))) { - Optional optionalError = - //Stream of group Properties + Optional optionalError = + // Stream of group Properties groupPropertiesToUpdate.stream(). - //Filter in only properties that needs text validation - filter(e -> enumHasValueFilter(e.getName(), - enumName -> PropertyNames.findName(enumName), - PropertyNames.VF_MODULE_DESCRIPTION, PropertyNames.VF_MODULE_LABEL)). - //validate text properties - map( e -> validateFreeText(e)). - //filter in only errors if exist - filter( e -> e.isRight()). - //map the Either value to the Error - map( e -> e.right().value()) - //collect - .findFirst(); - if( optionalError.isPresent() ){ + // Filter in only properties that needs text validation + filter(e -> enumHasValueFilter(e.getName(), enumName -> PropertyNames.findName(enumName), PropertyNames.VF_MODULE_DESCRIPTION, PropertyNames.VF_MODULE_LABEL)). + // validate text properties + map(e -> validateFreeText(e)). + // filter in only errors if exist + filter(e -> e.isRight()). + // map the Either value to the Error + map(e -> e.right().value()) + // collect + .findFirst(); + if (optionalError.isPresent()) { ret = Either.right(optionalError.get()); } - + } } @@ -674,83 +614,77 @@ public class GroupBusinessLogic extends BaseBusinessLogic { private Map prepareMapWithOriginalProperties(GroupDefinition originalGroup) { Map oldValueMap = new HashMap<>(); - PropertyNames[] propertiesToCheck = new PropertyNames[] { PropertyNames.INITIAL_COUNT, - PropertyNames.MAX_INSTANCES, PropertyNames.MIN_INSTANCES }; - - for(GroupProperty gp : originalGroup.convertToGroupProperties()){ - if( enumHasValueFilter(gp.getName(), enumName -> PropertyNames.findName(enumName), propertiesToCheck)){ + PropertyNames[] propertiesToCheck = new PropertyNames[] { PropertyNames.INITIAL_COUNT, PropertyNames.MAX_INSTANCES, PropertyNames.MIN_INSTANCES }; + + for (GroupProperty gp : originalGroup.convertToGroupProperties()) { + if (enumHasValueFilter(gp.getName(), enumName -> PropertyNames.findName(enumName), propertiesToCheck)) { oldValueMap.put(PropertyNames.findName(gp.getName()), gp.getValue()); } } - if( StringUtils.isEmpty(oldValueMap.get(PropertyNames.MAX_INSTANCES)) ){ + if (StringUtils.isEmpty(oldValueMap.get(PropertyNames.MAX_INSTANCES))) { oldValueMap.put(PropertyNames.MAX_INSTANCES, String.valueOf(Integer.MAX_VALUE)); } return oldValueMap; } - - private Either, ResponseFormat> validateOnlyValueChanged( - List groupPropertiesToUpdate, GroupDefinition originalGroup) { - + + private Either, ResponseFormat> validateOnlyValueChanged(List groupPropertiesToUpdate, GroupDefinition originalGroup) { + Either, ResponseFormat> ret = Either.left(groupPropertiesToUpdate); - if( CollectionUtils.isEmpty(groupPropertiesToUpdate) ){ + if (CollectionUtils.isEmpty(groupPropertiesToUpdate)) { ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, StringUtils.EMPTY)); - } - else if (CollectionUtils.isEmpty(originalGroup.getProperties())) { - ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, - groupPropertiesToUpdate.get(NumberUtils.INTEGER_ZERO).getName())); + } else if (CollectionUtils.isEmpty(originalGroup.getProperties())) { + ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, groupPropertiesToUpdate.get(NumberUtils.INTEGER_ZERO).getName())); } else { - Map namePropertyMap = - //Original Group Properties Stream + Map namePropertyMap = + // Original Group Properties Stream originalGroup.convertToGroupProperties().stream(). - //Collect to map with name as key - collect(Collectors.toMap(e -> e.getName(), e -> e)); - - Optional optionalMissingProperty = - //Group Properties to be updated Stream + // Collect to map with name as key + collect(Collectors.toMap(e -> e.getName(), e -> e)); + + Optional optionalMissingProperty = + // Group Properties to be updated Stream groupPropertiesToUpdate.stream(). - //Filter in property that is not contained in original if there is such - filter(e -> !namePropertyMap.containsKey(e.getName())). - //collect - findFirst(); - + // Filter in property that is not contained in original if there is such + filter(e -> !namePropertyMap.containsKey(e.getName())). + // collect + findFirst(); + if (optionalMissingProperty.isPresent()) { - ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, - optionalMissingProperty.get().getName())); - } - else{ - Optional optionalNonValueChange = - //groups to be updated stream + ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, optionalMissingProperty.get().getName())); + } else { + Optional optionalNonValueChange = + // groups to be updated stream groupPropertiesToUpdate.stream(). - //filter in only properties with non-value (illegal) change - filter( e -> !isOnlyGroupPropertyValueChanged(e, namePropertyMap.get(e.getName()))). - //Collect - findFirst(); + // filter in only properties with non-value (illegal) change + filter(e -> !isOnlyGroupPropertyValueChanged(e, namePropertyMap.get(e.getName()))). + // Collect + findFirst(); if (optionalNonValueChange.isPresent()) { - ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY, - optionalNonValueChange.get().getName())); + ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY, optionalNonValueChange.get().getName())); } } - + } return ret; } /** * if groupProperty are the same or if only value is different returns true, otherwise returns false. + * * @param groupProperty * @param groupProperty2 * @return */ private boolean isOnlyGroupPropertyValueChanged(GroupProperty groupProperty, GroupProperty groupProperty2) { - //Create 2 duplicates for groupPropery and reset their values + // Create 2 duplicates for groupPropery and reset their values Gson gson = new GsonBuilder().setPrettyPrinting().create(); try { GroupProperty groupPropertyDuplicate = new GroupProperty(groupProperty); groupPropertyDuplicate.setValue(null); groupPropertyDuplicate.setSchema(null); groupPropertyDuplicate.setParentUniqueId(null); -// GroupProperty groupProperty2Duplicate = gson.fromJson(JsonParserUtils.jsonToString(groupProperty2), GroupProperty.class); + // GroupProperty groupProperty2Duplicate = gson.fromJson(JsonParserUtils.jsonToString(groupProperty2), GroupProperty.class); GroupProperty groupProperty2Duplicate = new GroupProperty(groupProperty2); groupProperty2Duplicate.setValue(null); groupProperty2Duplicate.setSchema(null); @@ -759,8 +693,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } catch (Exception e) { log.debug("Failed validate group properties. ", e); return false; - } + } } + /** * Validate and update GroupDefinition metadata * @@ -864,183 +799,105 @@ public class GroupBusinessLogic extends BaseBusinessLogic { * @param inTransaction * @return */ - /*public Either, ResponseFormat> associateArtifactsToGroup(String componentId, String userId, ComponentTypeEnum componentType, List groups, boolean shouldLockComp, boolean inTransaction) { - - Either, ResponseFormat> result = null; - - if (shouldLockComp == true && inTransaction == true) { - BeEcompErrorManager.getInstance().logInternalFlowError("dissociateArtifactsFromGroup", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR); - // Cannot lock component since we are in a middle of another - // transaction. - ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; - result = Either.right(componentsUtils.getResponseFormat(actionStatus)); - return result; - } - - Component component = null; - try { - - if (groups == null || groups.isEmpty()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.OK)); - } - - Either validateGroupsBeforeUpdate = validateGroupsBeforeUpdate(componentId, userId, componentType, groups, inTransaction); - if (validateGroupsBeforeUpdate.isRight()) { - result = Either.right(validateGroupsBeforeUpdate.right().value()); - return result; - } - - component = validateGroupsBeforeUpdate.left().value(); - - if (shouldLockComp) { - Either lockComponent = lockComponent(component, "Group - Associate Artifacts"); - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } - } - - List updatedGroups = new ArrayList<>(); - - List componentGroups = component.getGroups(); - - // per group, associate to it the artifacts - for (GroupDefinition groupDefinition : groups) { - - GroupDefinition componentGroup = componentGroups.stream().filter(p -> p.getUniqueId().equals(groupDefinition.getUniqueId())).findFirst().orElse(null); - if (componentGroup != null) { - List componentArtifacts = componentGroup.getArtifacts(); - int artifactsSizeInGroup = componentArtifacts == null ? 0 : componentArtifacts.size(); - if (artifactsSizeInGroup > 0) { - List artifactsToAssociate = groupDefinition.getArtifacts(); - - // if no artifcats sent - if (artifactsToAssociate == null || true == artifactsToAssociate.isEmpty()) { - continue; - } - - boolean isChanged = componentArtifacts.removeAll(artifactsToAssociate); - if (isChanged) {// I.e. At least one artifact is already - // associated to the group - log.debug("Some of the artifacts already associated to group {}" , groupDefinition.getUniqueId()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ARTIFACT_ALREADY_ASSOCIATED, componentGroup.getName())); - } - } - } - - Either associateArtifactsToGroup = groupOperation.associateArtifactsToGroup(groupDefinition.getUniqueId(), groupDefinition.getArtifacts(), true); - - if (associateArtifactsToGroup.isRight()) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(associateArtifactsToGroup.right().value()); - result = Either.right(componentsUtils.getResponseFormat(actionStatus)); - log.debug("Failed to update group {} under component {}, error: {}", groupDefinition.getName(), component.getNormalizedName(), actionStatus.name()); - return result; - } - updatedGroups.add(associateArtifactsToGroup.left().value()); - - } - - result = Either.left(updatedGroups); - return result; - - } finally { - - if (false == inTransaction) { - - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on create group."); - titanDao.rollback(); - } else { - log.debug("Going to execute commit on create group."); - titanDao.commit(); - } - - } - - // unlock resource - if (shouldLockComp && component != null) { - graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); - } - - } - }*/ - - /*public Either, ResponseFormat> associateMembersToGroup(String componentId, String userId, ComponentTypeEnum componentType, List groups, boolean shouldLockComp, boolean inTransaction) { - - Either, ResponseFormat> result = null; - - if (shouldLockComp == true && inTransaction == true) { - BeEcompErrorManager.getInstance().logInternalFlowError("dissociateArtifactsFromGroup", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR); - // Cannot lock component since we are in a middle of another - // transaction. - ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; - result = Either.right(componentsUtils.getResponseFormat(actionStatus)); - return result; - } - - Component component = null; - try { - - if (groups == null || groups.isEmpty()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.OK)); - } - - Either validateGroupsBeforeUpdate = validateGroupsBeforeUpdate(componentId, userId, componentType, groups, inTransaction); - if (validateGroupsBeforeUpdate.isRight()) { - result = Either.right(validateGroupsBeforeUpdate.right().value()); - return result; - } - - component = validateGroupsBeforeUpdate.left().value(); - - if (shouldLockComp) { - Either lockComponent = lockComponent(component, "Group - Associate Members"); - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } - } - - List updatedGroups = new ArrayList<>(); - - // per group, associate to it the members - for (GroupDefinition groupDefinition : groups) { - - Either associateMembersToGroup = groupOperation.associateMembersToGroup(groupDefinition.getUniqueId(), groupDefinition.getMembers(), true); - - if (associateMembersToGroup.isRight()) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(associateMembersToGroup.right().value()); - result = Either.right(componentsUtils.getResponseFormat(actionStatus)); - log.debug("Failed to update group {} under component {}, error: {}", groupDefinition.getName(), component.getNormalizedName(), actionStatus.name()); - return result; - } else { - updatedGroups.add(associateMembersToGroup.left().value()); - } - - } - - result = Either.left(updatedGroups); - return result; - - } finally { - - if (false == inTransaction) { - - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on create group."); - titanDao.rollback(); - } else { - log.debug("Going to execute commit on create group."); - titanDao.commit(); - } - - } - - // unlock resource - if (shouldLockComp && component != null) { - graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); - } + /* + * public Either, ResponseFormat> associateArtifactsToGroup(String componentId, String userId, ComponentTypeEnum componentType, List groups, boolean shouldLockComp, boolean inTransaction) { + * + * Either, ResponseFormat> result = null; + * + * if (shouldLockComp == true && inTransaction == true) { BeEcompErrorManager.getInstance().logInternalFlowError("dissociateArtifactsFromGroup", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR); // Cannot lock + * component since we are in a middle of another // transaction. ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; result = Either.right(componentsUtils.getResponseFormat(actionStatus)); return result; } + * + * Component component = null; try { + * + * if (groups == null || groups.isEmpty()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.OK)); } + * + * Either validateGroupsBeforeUpdate = validateGroupsBeforeUpdate(componentId, userId, componentType, groups, inTransaction); if (validateGroupsBeforeUpdate.isRight()) { result = + * Either.right(validateGroupsBeforeUpdate.right().value()); return result; } + * + * component = validateGroupsBeforeUpdate.left().value(); + * + * if (shouldLockComp) { Either lockComponent = lockComponent(component, "Group - Associate Artifacts"); if (lockComponent.isRight()) { return Either.right(lockComponent.right().value()); } } + * + * List updatedGroups = new ArrayList<>(); + * + * List componentGroups = component.getGroups(); + * + * // per group, associate to it the artifacts for (GroupDefinition groupDefinition : groups) { + * + * GroupDefinition componentGroup = componentGroups.stream().filter(p -> p.getUniqueId().equals(groupDefinition.getUniqueId())).findFirst().orElse(null); if (componentGroup != null) { List componentArtifacts = + * componentGroup.getArtifacts(); int artifactsSizeInGroup = componentArtifacts == null ? 0 : componentArtifacts.size(); if (artifactsSizeInGroup > 0) { List artifactsToAssociate = groupDefinition.getArtifacts(); + * + * // if no artifcats sent if (artifactsToAssociate == null || true == artifactsToAssociate.isEmpty()) { continue; } + * + * boolean isChanged = componentArtifacts.removeAll(artifactsToAssociate); if (isChanged) {// I.e. At least one artifact is already // associated to the group log.debug("Some of the artifacts already associated to group {}" , + * groupDefinition.getUniqueId()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ARTIFACT_ALREADY_ASSOCIATED, componentGroup.getName())); } } } + * + * Either associateArtifactsToGroup = groupOperation.associateArtifactsToGroup(groupDefinition.getUniqueId(), groupDefinition.getArtifacts(), true); + * + * if (associateArtifactsToGroup.isRight()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(associateArtifactsToGroup.right().value()); result = Either.right(componentsUtils.getResponseFormat(actionStatus)); + * log.debug("Failed to update group {} under component {}, error: {}", groupDefinition.getName(), component.getNormalizedName(), actionStatus.name()); return result; } updatedGroups.add(associateArtifactsToGroup.left().value()); + * + * } + * + * result = Either.left(updatedGroups); return result; + * + * } finally { + * + * if (false == inTransaction) { + * + * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); } + * + * } + * + * // unlock resource if (shouldLockComp && component != null) { graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); } + * + * } } + */ - } - }*/ + /* + * public Either, ResponseFormat> associateMembersToGroup(String componentId, String userId, ComponentTypeEnum componentType, List groups, boolean shouldLockComp, boolean inTransaction) { + * + * Either, ResponseFormat> result = null; + * + * if (shouldLockComp == true && inTransaction == true) { BeEcompErrorManager.getInstance().logInternalFlowError("dissociateArtifactsFromGroup", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR); // Cannot lock + * component since we are in a middle of another // transaction. ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; result = Either.right(componentsUtils.getResponseFormat(actionStatus)); return result; } + * + * Component component = null; try { + * + * if (groups == null || groups.isEmpty()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.OK)); } + * + * Either validateGroupsBeforeUpdate = validateGroupsBeforeUpdate(componentId, userId, componentType, groups, inTransaction); if (validateGroupsBeforeUpdate.isRight()) { result = + * Either.right(validateGroupsBeforeUpdate.right().value()); return result; } + * + * component = validateGroupsBeforeUpdate.left().value(); + * + * if (shouldLockComp) { Either lockComponent = lockComponent(component, "Group - Associate Members"); if (lockComponent.isRight()) { return Either.right(lockComponent.right().value()); } } + * + * List updatedGroups = new ArrayList<>(); + * + * // per group, associate to it the members for (GroupDefinition groupDefinition : groups) { + * + * Either associateMembersToGroup = groupOperation.associateMembersToGroup(groupDefinition.getUniqueId(), groupDefinition.getMembers(), true); + * + * if (associateMembersToGroup.isRight()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(associateMembersToGroup.right().value()); result = Either.right(componentsUtils.getResponseFormat(actionStatus)); + * log.debug("Failed to update group {} under component {}, error: {}", groupDefinition.getName(), component.getNormalizedName(), actionStatus.name()); return result; } else { updatedGroups.add(associateMembersToGroup.left().value()); } + * + * } + * + * result = Either.left(updatedGroups); return result; + * + * } finally { + * + * if (false == inTransaction) { + * + * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); } + * + * } + * + * // unlock resource if (shouldLockComp && component != null) { graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); } + * + * } } + */ /** * associate artifacts to a given group @@ -1084,17 +941,16 @@ public class GroupBusinessLogic extends BaseBusinessLogic { component = validateComponent.left().value(); Either groupEither = findGroupOnComponent(component, groupId); - + if (groupEither.isRight()) { log.debug("Faild to find group {} under component {}", groupId, component.getUniqueId()); BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "group " + groupId + " not found under component " + component.getUniqueId(), ErrorSeverity.INFO); String componentTypeForResponse = getComponentTypeForResponse(component); result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, groupId, component.getSystemName(), componentTypeForResponse)); return result; - } + } GroupDefinition group = groupEither.left().value(); - - + Boolean isBase = null;// Constants.IS_BASE; List props = group.convertToGroupProperties(); if (props != null && !props.isEmpty()) { @@ -1114,14 +970,14 @@ public class GroupBusinessLogic extends BaseBusinessLogic { List artifacts = new ArrayList<>(); List artifactsFromComponent = new ArrayList<>(); List artifactsIds = group.getArtifacts(); - + Map deploymentArtifacts = null; - if(MapUtils.isNotEmpty(component.getDeploymentArtifacts())){ + if (MapUtils.isNotEmpty(component.getDeploymentArtifacts())) { deploymentArtifacts = component.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(a -> a.getUniqueId(), a -> a)); } - + if (artifactsIds != null && !artifactsIds.isEmpty()) { - for(String id: artifactsIds){ + for (String id : artifactsIds) { if (MapUtils.isEmpty(deploymentArtifacts) || !deploymentArtifacts.containsKey(id)) { log.debug("Failed to get artifact {} . Status is {} ", id, StorageOperationStatus.NOT_FOUND); ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND)); @@ -1166,15 +1022,15 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } private Either findGroupOnComponent(Component component, String groupId) { - + Either result = null; - if(CollectionUtils.isNotEmpty(component.getGroups())){ + if (CollectionUtils.isNotEmpty(component.getGroups())) { Optional foundGroup = component.getGroups().stream().filter(g -> g.getUniqueId().equals(groupId)).findFirst(); - if(foundGroup.isPresent()){ - result = Either.left(foundGroup.get()); + if (foundGroup.isPresent()) { + result = Either.left(foundGroup.get()); } } - if(result == null){ + if (result == null) { result = Either.right(StorageOperationStatus.NOT_FOUND); } return result; @@ -1260,399 +1116,231 @@ public class GroupBusinessLogic extends BaseBusinessLogic { List currentGroups = component.getGroups(); boolean found = false; - List updatedGroupsName = groups.stream().map(getByParam).collect(Collectors.toList()); - - List missingGroupNames = updatedGroupsName; - - if (currentGroups != null && false == currentGroups.isEmpty()) { - List currentGroupsName = currentGroups.stream().map(getByParam).collect(Collectors.toList()); - - if (currentGroupsName.containsAll(updatedGroupsName)) { - found = true; - } else { - currentGroupsName.removeAll(currentGroupsName); - missingGroupNames = currentGroupsName; - } - } - if (false == found) { - String componentTypeForResponse = getComponentTypeForResponse(component); - String listOfGroups = getAsString(missingGroupNames); - result = componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, listOfGroups, component.getSystemName(), componentTypeForResponse); - return result; - } - - return null; - } - - public String getAsString(List list) { - - if (list == null || list.isEmpty()) { - return ""; - } - StringBuilder builder = new StringBuilder(); - list.forEach(p -> builder.append(p + ",")); - - String result = builder.toString(); - return result.substring(0, result.length()); - - } - - /** - * dissociate artifacts from a given group - * - * @param componentId - * @param userId - * @param componentType - * @param groups - * @param shouldLockComp - * @param inTransaction - * @return - */ - /*public Either, ResponseFormat> dissociateArtifactsFromGroup(String componentId, String userId, ComponentTypeEnum componentType, List groups, boolean shouldLockComp, boolean inTransaction) { - - Either, ResponseFormat> result = null; - - if (shouldLockComp == true && inTransaction == true) { - BeEcompErrorManager.getInstance().logInternalFlowError("dissociateArtifactsFromGroup", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR); - // Cannot lock component since we are in a middle of another - // transaction. - ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; - result = Either.right(componentsUtils.getResponseFormat(actionStatus)); - return result; - } - - Component component = null; - - try { - - if (groups == null || groups.isEmpty()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.OK)); - } - - Either validateGroupsBeforeUpdate = validateGroupsBeforeUpdate(componentId, userId, componentType, groups, inTransaction); - if (validateGroupsBeforeUpdate.isRight()) { - result = Either.right(validateGroupsBeforeUpdate.right().value()); - return result; - } - - component = validateGroupsBeforeUpdate.left().value(); - - if (shouldLockComp) { - Either lockComponent = lockComponent(component, "Group - Dissociate Artifacts"); - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } - } - - List updatedGroups = new ArrayList<>(); - - List componentGroups = component.getGroups(); - // per group, associate to it the artifacts - for (GroupDefinition groupDefinition : groups) { - - GroupDefinition componentGroup = componentGroups.stream().filter(p -> p.getUniqueId().equals(groupDefinition.getUniqueId())).findFirst().orElse(null); - if (componentGroup != null) { - List componentArtifacts = componentGroup.getArtifacts(); - int artifactsSizeInGroup = componentArtifacts == null ? 0 : componentArtifacts.size(); - List artifactsToDissociate = groupDefinition.getArtifacts(); - - // if no artifcats sent - if (artifactsToDissociate == null || true == artifactsToDissociate.isEmpty()) { - continue; - } - - if (artifactsSizeInGroup > 0) { - - boolean containsAll = componentArtifacts.containsAll(artifactsToDissociate); - if (false == containsAll) { // At least one artifact is - // not associated to the - // group - log.debug("Some of the artifacts already dissociated to group {}" , groupDefinition.getUniqueId()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ARTIFACT_ALREADY_DISSOCIATED, componentGroup.getName())); - } - } else { - if (artifactsSizeInGroup == 0) { - if (artifactsToDissociate != null && false == artifactsToDissociate.isEmpty()) { - log.debug("No artifact is found under the group {}" , groupDefinition.getUniqueId()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ARTIFACT_ALREADY_DISSOCIATED, componentGroup.getName())); - } - } - } - } - - Either associateArtifactsToGroup = groupOperation.dissociateArtifactsFromGroup(groupDefinition.getUniqueId(), groupDefinition.getArtifacts(), true); - - if (associateArtifactsToGroup.isRight()) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(associateArtifactsToGroup.right().value()); - result = Either.right(componentsUtils.getResponseFormat(actionStatus)); - log.debug("Failed to update group {} under component {}, error: {}", groupDefinition.getName(), component.getNormalizedName(), actionStatus.name()); - return result; - } - updatedGroups.add(associateArtifactsToGroup.left().value()); - - } - - result = Either.left(updatedGroups); - return result; - - } finally { - - if (false == inTransaction) { - - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on create group."); - titanDao.rollback(); - } else { - log.debug("Going to execute commit on create group."); - titanDao.commit(); - } - - } - // unlock resource - if (shouldLockComp && component != null) { - graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); - } - - } - - }*/ - - /*public Either, ResponseFormat> createGroups(String componentId, String userId, ComponentTypeEnum componentType, List groupDefinitions, boolean shouldLockComp, boolean inTransaction) { - - Either, ResponseFormat> result = null; - - List groups = new ArrayList<>(); - org.openecomp.sdc.be.model.Component component = null; - try { - - if (groupDefinitions != null && !groupDefinitions.isEmpty()) { - - if (shouldLockComp && inTransaction) { - BeEcompErrorManager.getInstance().logInternalFlowError("createGroups", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR); - // Cannot lock component since we are in a middle of another - // transaction. - ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; - result = Either.right(componentsUtils.getResponseFormat(actionStatus)); - return result; - } - - Either validateUserExists = validateUserExists(userId, CREATE_GROUP, true); - if (validateUserExists.isRight()) { - result = Either.right(validateUserExists.right().value()); - return result; - } - - User user = validateUserExists.left().value(); - - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreGroups(false); - componentParametersView.setIgnoreArtifacts(false); - componentParametersView.setIgnoreUsers(false); - componentParametersView.setIgnoreComponentInstances(false); - - Either validateComponent = validateComponentExists(componentId, componentType, componentParametersView); - - if (validateComponent.isRight()) { - result = Either.right(validateComponent.right().value()); - return result; - } - component = validateComponent.left().value(); - - if (shouldLockComp) { - Either lockComponent = lockComponent(component, "CreateGroups"); - if (lockComponent.isRight()) { - return Either.right(lockComponent.right().value()); - } - } - - Either canWork = validateCanWorkOnComponent(component, userId); - if (canWork.isRight()) { - result = Either.right(canWork.right().value()); - return result; - } - - for (GroupDefinition groupDefinition : groupDefinitions) { - Either createGroup = this.createGroup(component, user, componentType, groupDefinition, true); - if (createGroup.isRight()) { - log.debug("Failed to create group {}." , groupDefinition ); - result = Either.right(createGroup.right().value()); - return result; - } - GroupDefinition createdGroup = createGroup.left().value(); - groups.add(createdGroup); - } - } - - result = Either.left(groups); - return result; - - } finally { - - if (false == inTransaction) { - - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on create group."); - titanDao.rollback(); - } else { - log.debug("Going to execute commit on create group."); - titanDao.commit(); - } - - } - // unlock resource - if (shouldLockComp && component != null) { - graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); - } - - } - - } - - public Either createGroup(Component component, User user, ComponentTypeEnum componentType, GroupDefinition groupDefinition, boolean inTransaction) { - - Either result = null; - - log.trace("Going to create group {}" , groupDefinition); - - try { - - // 3. verify group not already exist - List groups = component.getGroups(); - boolean found = false; - if (groups != null && false == groups.isEmpty()) { - - GroupDefinition existGroupDef = groups.stream().filter(p -> p.getName().equalsIgnoreCase(groupDefinition.getName())).findFirst().orElse(null); - - found = existGroupDef != null; - } - - if (true == found) { - String componentTypeForResponse = getComponentTypeForResponse(component); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ALREADY_EXIST, groupDefinition.getName(), component.getNormalizedName(), componentTypeForResponse)); - return result; - } - - // 4. verify type of group exist - String groupType = groupDefinition.getType(); - if (groupType == null || groupType.isEmpty()) { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_MISSING_GROUP_TYPE, groupDefinition.getName())); - return result; - } - Either getGroupType = groupTypeOperation.getLatestGroupTypeByType(groupType, true); - if (getGroupType.isRight()) { - StorageOperationStatus status = getGroupType.right().value(); - if (status == StorageOperationStatus.NOT_FOUND) { - BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "group type " + groupType + " cannot be found", ErrorSeverity.INFO); - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, groupType)); - return result; - } else { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - return result; - } - } - - // 6. verify the component instances type are allowed according to - // the member types in the group type - GroupTypeDefinition groupTypeDefinition = getGroupType.left().value(); - - Either areValidMembers = verifyComponentInstancesAreValidMembers(component, componentType, groupDefinition.getName(), groupType, groupDefinition.getMembers(), groupTypeDefinition.getMembers()); - - if (areValidMembers.isRight()) { - ResponseFormat responseFormat = areValidMembers.right().value(); - result = Either.right(responseFormat); - return result; - } - - // 7. verify the artifacts belongs to the component - Either areValidArtifacts = verifyArtifactsBelongsToComponent(component, groupDefinition.getArtifacts(), CREATE_GROUP); - if (areValidArtifacts.isRight()) { - ResponseFormat responseFormat = areValidArtifacts.right().value(); - result = Either.right(responseFormat); - return result; - } - - NodeTypeEnum nodeTypeEnum = componentType.getNodeType(); - - // add invariantUUID - String invariantUUID = UniqueIdBuilder.buildInvariantUUID(); - groupDefinition.setInvariantUUID(invariantUUID); - - // add groupUUID - String groupUUID = UniqueIdBuilder.generateUUID(); - groupDefinition.setGroupUUID(groupUUID); - - // add version - groupDefinition.setVersion(INITIAL_VERSION); + List updatedGroupsName = groups.stream().map(getByParam).collect(Collectors.toList()); - // set groupType uid - groupDefinition.setTypeUid(groupTypeDefinition.getUniqueId()); + List missingGroupNames = updatedGroupsName; - Either addGroupToGraph = groupOperation.addGroup(nodeTypeEnum, component.getUniqueId(), groupDefinition, true); + if (currentGroups != null && false == currentGroups.isEmpty()) { + List currentGroupsName = currentGroups.stream().map(getByParam).collect(Collectors.toList()); - if (addGroupToGraph.isRight()) { - StorageOperationStatus storageOperationStatus = addGroupToGraph.right().value(); - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus); - result = Either.right(componentsUtils.getResponseFormat(actionStatus)); - log.debug("Failed to create group {} under component {}, error: {}", groupDefinition.getName(), component.getNormalizedName(), actionStatus.name()); + if (currentGroupsName.containsAll(updatedGroupsName)) { + found = true; } else { - GroupDefinition groupDefinitionCreated = addGroupToGraph.left().value(); - result = Either.left(groupDefinitionCreated); + currentGroupsName.removeAll(currentGroupsName); + missingGroupNames = currentGroupsName; } - + } + if (false == found) { + String componentTypeForResponse = getComponentTypeForResponse(component); + String listOfGroups = getAsString(missingGroupNames); + result = componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, listOfGroups, component.getSystemName(), componentTypeForResponse); return result; + } - } finally { - - if (false == inTransaction) { - - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on create group."); - titanDao.rollback(); - } else { - log.debug("Going to execute commit on create group."); - titanDao.commit(); - } + return null; + } - } + public String getAsString(List list) { + if (list == null || list.isEmpty()) { + return ""; } + StringBuilder builder = new StringBuilder(); + list.forEach(p -> builder.append(p + ",")); + + String result = builder.toString(); + return result.substring(0, result.length()); } - public Either, ResponseFormat> updateVfModuleGroupNames(String resourceSystemName, List groups, boolean inTransaction) { - List updatedGroups = new ArrayList<>(); - Either, ResponseFormat> updateGroupNamesRes = Either.left(updatedGroups); - Either updateGroupNameRes; - Either validateGenerateGroupNameRes; - int counter; - for (GroupDefinition group : groups) { - if (!group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE) && !Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(group.getName()).matches()) { - continue; - } - counter = Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1]); - validateGenerateGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, group.getDescription(), counter); - if (validateGenerateGroupNameRes.isRight()) { - updateGroupNamesRes = Either.right(validateGenerateGroupNameRes.right().value()); - break; - } - updateGroupNameRes = groupOperation.updateGroupName(group.getUniqueId(), validateGenerateGroupNameRes.left().value(), inTransaction); - if (updateGroupNameRes.isRight()) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(updateGroupNameRes.right().value()); - updateGroupNamesRes = Either.right(componentsUtils.getResponseFormat(actionStatus)); - break; - } - updatedGroups.add(updateGroupNameRes.left().value()); - } - return updateGroupNamesRes; - }*/ + /** + * dissociate artifacts from a given group + * + * @param componentId + * @param userId + * @param componentType + * @param groups + * @param shouldLockComp + * @param inTransaction + * @return + */ + /* + * public Either, ResponseFormat> dissociateArtifactsFromGroup(String componentId, String userId, ComponentTypeEnum componentType, List groups, boolean shouldLockComp, boolean inTransaction) { + * + * Either, ResponseFormat> result = null; + * + * if (shouldLockComp == true && inTransaction == true) { BeEcompErrorManager.getInstance().logInternalFlowError("dissociateArtifactsFromGroup", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR); // Cannot lock + * component since we are in a middle of another // transaction. ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; result = Either.right(componentsUtils.getResponseFormat(actionStatus)); return result; } + * + * Component component = null; + * + * try { + * + * if (groups == null || groups.isEmpty()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.OK)); } + * + * Either validateGroupsBeforeUpdate = validateGroupsBeforeUpdate(componentId, userId, componentType, groups, inTransaction); if (validateGroupsBeforeUpdate.isRight()) { result = + * Either.right(validateGroupsBeforeUpdate.right().value()); return result; } + * + * component = validateGroupsBeforeUpdate.left().value(); + * + * if (shouldLockComp) { Either lockComponent = lockComponent(component, "Group - Dissociate Artifacts"); if (lockComponent.isRight()) { return Either.right(lockComponent.right().value()); } } + * + * List updatedGroups = new ArrayList<>(); + * + * List componentGroups = component.getGroups(); // per group, associate to it the artifacts for (GroupDefinition groupDefinition : groups) { + * + * GroupDefinition componentGroup = componentGroups.stream().filter(p -> p.getUniqueId().equals(groupDefinition.getUniqueId())).findFirst().orElse(null); if (componentGroup != null) { List componentArtifacts = + * componentGroup.getArtifacts(); int artifactsSizeInGroup = componentArtifacts == null ? 0 : componentArtifacts.size(); List artifactsToDissociate = groupDefinition.getArtifacts(); + * + * // if no artifcats sent if (artifactsToDissociate == null || true == artifactsToDissociate.isEmpty()) { continue; } + * + * if (artifactsSizeInGroup > 0) { + * + * boolean containsAll = componentArtifacts.containsAll(artifactsToDissociate); if (false == containsAll) { // At least one artifact is // not associated to the // group log.debug("Some of the artifacts already dissociated to group {}" , + * groupDefinition.getUniqueId()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ARTIFACT_ALREADY_DISSOCIATED, componentGroup.getName())); } } else { if (artifactsSizeInGroup == 0) { if (artifactsToDissociate != null && + * false == artifactsToDissociate.isEmpty()) { log.debug("No artifact is found under the group {}" , groupDefinition.getUniqueId()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ARTIFACT_ALREADY_DISSOCIATED, + * componentGroup.getName())); } } } } + * + * Either associateArtifactsToGroup = groupOperation.dissociateArtifactsFromGroup(groupDefinition.getUniqueId(), groupDefinition.getArtifacts(), true); + * + * if (associateArtifactsToGroup.isRight()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(associateArtifactsToGroup.right().value()); result = Either.right(componentsUtils.getResponseFormat(actionStatus)); + * log.debug("Failed to update group {} under component {}, error: {}", groupDefinition.getName(), component.getNormalizedName(), actionStatus.name()); return result; } updatedGroups.add(associateArtifactsToGroup.left().value()); + * + * } + * + * result = Either.left(updatedGroups); return result; + * + * } finally { + * + * if (false == inTransaction) { + * + * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); } + * + * } // unlock resource if (shouldLockComp && component != null) { graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); } + * + * } + * + * } + */ + + /* + * public Either, ResponseFormat> createGroups(String componentId, String userId, ComponentTypeEnum componentType, List groupDefinitions, boolean shouldLockComp, boolean inTransaction) { + * + * Either, ResponseFormat> result = null; + * + * List groups = new ArrayList<>(); org.openecomp.sdc.be.model.Component component = null; try { + * + * if (groupDefinitions != null && !groupDefinitions.isEmpty()) { + * + * if (shouldLockComp && inTransaction) { BeEcompErrorManager.getInstance().logInternalFlowError("createGroups", "Cannot lock component since we are inside a transaction", ErrorSeverity.ERROR); // Cannot lock component since we are in a middle of + * another // transaction. ActionStatus actionStatus = ActionStatus.INVALID_CONTENT; result = Either.right(componentsUtils.getResponseFormat(actionStatus)); return result; } + * + * Either validateUserExists = validateUserExists(userId, CREATE_GROUP, true); if (validateUserExists.isRight()) { result = Either.right(validateUserExists.right().value()); return result; } + * + * User user = validateUserExists.left().value(); + * + * ComponentParametersView componentParametersView = new ComponentParametersView(); componentParametersView.disableAll(); componentParametersView.setIgnoreGroups(false); componentParametersView.setIgnoreArtifacts(false); + * componentParametersView.setIgnoreUsers(false); componentParametersView.setIgnoreComponentInstances(false); + * + * Either validateComponent = validateComponentExists(componentId, componentType, componentParametersView); + * + * if (validateComponent.isRight()) { result = Either.right(validateComponent.right().value()); return result; } component = validateComponent.left().value(); + * + * if (shouldLockComp) { Either lockComponent = lockComponent(component, "CreateGroups"); if (lockComponent.isRight()) { return Either.right(lockComponent.right().value()); } } + * + * Either canWork = validateCanWorkOnComponent(component, userId); if (canWork.isRight()) { result = Either.right(canWork.right().value()); return result; } + * + * for (GroupDefinition groupDefinition : groupDefinitions) { Either createGroup = this.createGroup(component, user, componentType, groupDefinition, true); if (createGroup.isRight()) { + * log.debug("Failed to create group {}." , groupDefinition ); result = Either.right(createGroup.right().value()); return result; } GroupDefinition createdGroup = createGroup.left().value(); groups.add(createdGroup); } } + * + * result = Either.left(groups); return result; + * + * } finally { + * + * if (false == inTransaction) { + * + * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); } + * + * } // unlock resource if (shouldLockComp && component != null) { graphLockOperation.unlockComponent(componentId, componentType.getNodeType()); } + * + * } + * + * } + * + * public Either createGroup(Component component, User user, ComponentTypeEnum componentType, GroupDefinition groupDefinition, boolean inTransaction) { + * + * Either result = null; + * + * log.trace("Going to create group {}" , groupDefinition); + * + * try { + * + * // 3. verify group not already exist List groups = component.getGroups(); boolean found = false; if (groups != null && false == groups.isEmpty()) { + * + * GroupDefinition existGroupDef = groups.stream().filter(p -> p.getName().equalsIgnoreCase(groupDefinition.getName())).findFirst().orElse(null); + * + * found = existGroupDef != null; } + * + * if (true == found) { String componentTypeForResponse = getComponentTypeForResponse(component); result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ALREADY_EXIST, groupDefinition.getName(), component.getNormalizedName(), + * componentTypeForResponse)); return result; } + * + * // 4. verify type of group exist String groupType = groupDefinition.getType(); if (groupType == null || groupType.isEmpty()) { result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_MISSING_GROUP_TYPE, + * groupDefinition.getName())); return result; } Either getGroupType = groupTypeOperation.getLatestGroupTypeByType(groupType, true); if (getGroupType.isRight()) { StorageOperationStatus status = + * getGroupType.right().value(); if (status == StorageOperationStatus.NOT_FOUND) { BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "group type " + groupType + " cannot be found", ErrorSeverity.INFO); result = + * Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, groupType)); return result; } else { result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); return result; } } + * + * // 6. verify the component instances type are allowed according to // the member types in the group type GroupTypeDefinition groupTypeDefinition = getGroupType.left().value(); + * + * Either areValidMembers = verifyComponentInstancesAreValidMembers(component, componentType, groupDefinition.getName(), groupType, groupDefinition.getMembers(), groupTypeDefinition.getMembers()); + * + * if (areValidMembers.isRight()) { ResponseFormat responseFormat = areValidMembers.right().value(); result = Either.right(responseFormat); return result; } + * + * // 7. verify the artifacts belongs to the component Either areValidArtifacts = verifyArtifactsBelongsToComponent(component, groupDefinition.getArtifacts(), CREATE_GROUP); if (areValidArtifacts.isRight()) { + * ResponseFormat responseFormat = areValidArtifacts.right().value(); result = Either.right(responseFormat); return result; } + * + * NodeTypeEnum nodeTypeEnum = componentType.getNodeType(); + * + * // add invariantUUID String invariantUUID = UniqueIdBuilder.buildInvariantUUID(); groupDefinition.setInvariantUUID(invariantUUID); + * + * // add groupUUID String groupUUID = UniqueIdBuilder.generateUUID(); groupDefinition.setGroupUUID(groupUUID); + * + * // add version groupDefinition.setVersion(INITIAL_VERSION); + * + * // set groupType uid groupDefinition.setTypeUid(groupTypeDefinition.getUniqueId()); + * + * Either addGroupToGraph = groupOperation.addGroup(nodeTypeEnum, component.getUniqueId(), groupDefinition, true); + * + * if (addGroupToGraph.isRight()) { StorageOperationStatus storageOperationStatus = addGroupToGraph.right().value(); ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus); result = + * Either.right(componentsUtils.getResponseFormat(actionStatus)); log.debug("Failed to create group {} under component {}, error: {}", groupDefinition.getName(), component.getNormalizedName(), actionStatus.name()); } else { GroupDefinition + * groupDefinitionCreated = addGroupToGraph.left().value(); result = Either.left(groupDefinitionCreated); } + * + * return result; + * + * } finally { + * + * if (false == inTransaction) { + * + * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); } + * + * } + * + * } + * + * } + * + * public Either, ResponseFormat> updateVfModuleGroupNames(String resourceSystemName, List groups, boolean inTransaction) { List updatedGroups = new ArrayList<>(); + * Either, ResponseFormat> updateGroupNamesRes = Either.left(updatedGroups); Either updateGroupNameRes; Either validateGenerateGroupNameRes; int counter; for + * (GroupDefinition group : groups) { if (!group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE) && !Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(group.getName()).matches()) { continue; } counter = + * Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1]); validateGenerateGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, group.getDescription(), counter); if (validateGenerateGroupNameRes.isRight()) { + * updateGroupNamesRes = Either.right(validateGenerateGroupNameRes.right().value()); break; } updateGroupNameRes = groupOperation.updateGroupName(group.getUniqueId(), validateGenerateGroupNameRes.left().value(), inTransaction); if + * (updateGroupNameRes.isRight()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(updateGroupNameRes.right().value()); updateGroupNamesRes = Either.right(componentsUtils.getResponseFormat(actionStatus)); break; } + * updatedGroups.add(updateGroupNameRes.left().value()); } return updateGroupNamesRes; } + */ - private Either, ResponseFormat> updateGroupPropertiesValue(String componentId, - GroupDefinition currentGroup, List groupPropertyToUpdate, boolean inTransaction) { + private Either, ResponseFormat> updateGroupPropertiesValue(String componentId, GroupDefinition currentGroup, List groupPropertyToUpdate, boolean inTransaction) { Either, ResponseFormat> result; - Either, StorageOperationStatus> eitherUpdate = groupsOperation - .updateGroupPropertiesOnComponent(componentId, currentGroup, groupPropertyToUpdate); + Either, StorageOperationStatus> eitherUpdate = groupsOperation.updateGroupPropertiesOnComponent(componentId, currentGroup, groupPropertyToUpdate); if (eitherUpdate.isRight()) { ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(eitherUpdate.right().value()); result = Either.right(componentsUtils.getResponseFormat(actionStatus)); @@ -1661,7 +1349,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } return result; } - + public Either validateGenerateVfModuleGroupNames(List allGroups, String resourceSystemName, int startGroupCounter) { Either validateGenerateGroupNamesRes = Either.left(true); Collections.sort(allGroups, (art1, art2) -> ArtifactTemplateInfo.compareByGroupName(art1, art2)); @@ -1768,53 +1456,38 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } newGroupName = newGroupNameRes.left().value(); group.setName(newGroupName); - + } updatedGroups.add(group); - + } result = Either.left(updatedGroups); return result; } - /*public Either, ResponseFormat> createGroups(Component component, User user, ComponentTypeEnum componentType, List groupDefinitions, boolean inTransaction) { - - List generatedGroups = new ArrayList<>(); - Either, ResponseFormat> result = Either.left(generatedGroups); - - try { - - if (groupDefinitions != null && false == groupDefinitions.isEmpty()) { - for (GroupDefinition groupDefinition : groupDefinitions) { - Either createGroup = this.createGroup(component, user, componentType, groupDefinition, true); - if (createGroup.isRight()) { - result = Either.right(createGroup.right().value()); - return result; - } - GroupDefinition generatedGroup = createGroup.left().value(); - generatedGroups.add(generatedGroup); - } - } - - return result; - } finally { - - if (false == inTransaction) { - - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on create group."); - titanDao.rollback(); - } else { - log.debug("Going to execute commit on create group."); - titanDao.commit(); - } - - } - - } - - }*/ + /* + * public Either, ResponseFormat> createGroups(Component component, User user, ComponentTypeEnum componentType, List groupDefinitions, boolean inTransaction) { + * + * List generatedGroups = new ArrayList<>(); Either, ResponseFormat> result = Either.left(generatedGroups); + * + * try { + * + * if (groupDefinitions != null && false == groupDefinitions.isEmpty()) { for (GroupDefinition groupDefinition : groupDefinitions) { Either createGroup = this.createGroup(component, user, componentType, + * groupDefinition, true); if (createGroup.isRight()) { result = Either.right(createGroup.right().value()); return result; } GroupDefinition generatedGroup = createGroup.left().value(); generatedGroups.add(generatedGroup); } } + * + * return result; } finally { + * + * if (false == inTransaction) { + * + * if (result == null || result.isRight()) { log.debug("Going to execute rollback on create group."); titanDao.rollback(); } else { log.debug("Going to execute commit on create group."); titanDao.commit(); } + * + * } + * + * } + * + * } + */ public Either getGroupInstWithArtifactsById(ComponentTypeEnum componentType, String componentId, String componentInstanceId, String groupInstId, String userId, boolean inTransaction) { Either result = null; @@ -1833,7 +1506,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { try { ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); + componentParametersView.disableAll(); componentParametersView.setIgnoreUsers(false); componentParametersView.setIgnoreComponentInstances(false); componentParametersView.setIgnoreArtifacts(false); @@ -1845,7 +1518,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } component = validateComponent.left().value(); Either, StorageOperationStatus> findComponentInstanceAndGroupInstanceRes = findComponentInstanceAndGroupInstanceOnComponent(component, componentInstanceId, groupInstId); - + if (findComponentInstanceAndGroupInstanceRes.isRight()) { log.debug("Failed to get group {} . Status is {} ", groupInstId, findComponentInstanceAndGroupInstanceRes.right().value()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findComponentInstanceAndGroupInstanceRes.right().value())); @@ -1855,7 +1528,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { GroupInstance group = findComponentInstanceAndGroupInstanceRes.left().value().getRight(); ComponentInstance componentInstance = findComponentInstanceAndGroupInstanceRes.left().value().getLeft(); - + Boolean isBase = null;// Constants.IS_BASE; List props = group.convertToGroupInstancesProperties(); if (props != null && !props.isEmpty()) { @@ -1871,30 +1544,33 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } } - + List artifacts = new ArrayList<>(); - List artifactsFromComponent = new ArrayList<>(); List artifactsIds = group.getArtifacts(); if (artifactsIds != null && !artifactsIds.isEmpty()) { - - for(String id: artifactsIds){ - Either artifactEither = artifactsOperation.getArtifactById(componentInstance.getComponentUid(), id); - if (artifactEither.isRight()) { - log.debug("Failed to get artifact {} . Status is {} ", id, artifactEither.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactEither.right().value())); - result = Either.right(responseFormat); - return result; - } - artifactsFromComponent.add(artifactEither.left().value()); - } - if (!artifactsFromComponent.isEmpty()) { - for (ArtifactDefinition artifactDefinition : artifactsFromComponent) { - ArtifactDefinitionInfo artifactDefinitionInfo = new ArtifactDefinitionInfo(artifactDefinition); - artifacts.add(artifactDefinitionInfo); + + List instances = component.getComponentInstances(); + if (instances != null) { + Optional findFirst = instances.stream().filter(i -> i.getUniqueId().equals(componentInstanceId)).findFirst(); + if (findFirst.isPresent()) { + ComponentInstance ci = findFirst.get(); + Map deploymentArtifacts = ci.getDeploymentArtifacts(); + for (String id : artifactsIds) { + Optional artOp = deploymentArtifacts.values().stream().filter(a -> a.getUniqueId().equals(id)).findFirst(); + if (artOp.isPresent()) { + artifacts.add(new ArtifactDefinitionInfo(artOp.get())); + } + } + List instArtifactsIds = group.getGroupInstanceArtifacts(); + for (String id : instArtifactsIds) { + Optional artOp = deploymentArtifacts.values().stream().filter(a -> a.getUniqueId().equals(id)).findFirst(); + if (artOp.isPresent()) { + artifacts.add(new ArtifactDefinitionInfo(artOp.get())); + } + } } + } - - } GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group); resultInfo.setIsBase(isBase); @@ -1905,7 +1581,6 @@ public class GroupBusinessLogic extends BaseBusinessLogic { return result; - } finally { if (false == inTransaction) { @@ -1922,250 +1597,230 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } } - + private Either, StorageOperationStatus> findComponentInstanceAndGroupInstanceOnComponent(Component component, String componentInstanceId, String groupInstId) { - - Either, StorageOperationStatus> result = null; - if(CollectionUtils.isNotEmpty(component.getComponentInstances())){ + + Either, StorageOperationStatus> result = null; + if (CollectionUtils.isNotEmpty(component.getComponentInstances())) { Optional foundGroup; Optional foundComponent = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstanceId)).findFirst(); - if(foundComponent.isPresent() && CollectionUtils.isNotEmpty(foundComponent.get().getGroupInstances())){ + if (foundComponent.isPresent() && CollectionUtils.isNotEmpty(foundComponent.get().getGroupInstances())) { foundGroup = foundComponent.get().getGroupInstances().stream().filter(gi -> gi.getUniqueId().equals(groupInstId)).findFirst(); - if(foundGroup.isPresent()){ + if (foundGroup.isPresent()) { result = Either.left(new ImmutablePair<>(foundComponent.get(), foundGroup.get())); } } } - if(result == null){ + if (result == null) { result = Either.right(StorageOperationStatus.NOT_FOUND); } return result; } - private int getLatestIntProperty(Map newValues, Map parentValues, - PropertyNames propertyKey) { + private int getLatestIntProperty(Map newValues, Map parentValues, PropertyNames propertyKey) { String value; - if( newValues.containsKey(propertyKey) ){ + if (newValues.containsKey(propertyKey)) { value = newValues.get(propertyKey); - } - else{ + } else { value = parentValues.get(propertyKey); } return Integer.valueOf(value); } - private boolean isPropertyChanged(Map newValues, Map parentValues, - final PropertyNames minInstances) { + private boolean isPropertyChanged(Map newValues, Map parentValues, final PropertyNames minInstances) { return newValues.containsKey(minInstances) && newValues.containsKey(minInstances) && !newValues.get(minInstances).equals(parentValues.get(minInstances)); } - private Either validateMinMaxAndInitialCountPropertyLogicVF( - Map newValues, Map parentValues) { - + private Either validateMinMaxAndInitialCountPropertyLogicVF(Map newValues, Map parentValues) { + int latestMaxInstances = getLatestIntProperty(newValues, parentValues, PropertyNames.MAX_INSTANCES); int latestInitialCount = getLatestIntProperty(newValues, parentValues, PropertyNames.INITIAL_COUNT); int latestMinInstances = getLatestIntProperty(newValues, parentValues, PropertyNames.MIN_INSTANCES); Either result = Either.left(true); - + if (isPropertyChanged(newValues, parentValues, PropertyNames.INITIAL_COUNT) && result.isLeft()) { if (latestInitialCount > latestMaxInstances || latestInitialCount < latestMinInstances) { - result = Either.right( - componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_INITIAL_COUNT_PROPERTY_VALUE, - PropertyNames.INITIAL_COUNT.getPropertyName(), String.valueOf(latestMinInstances), - String.valueOf(latestMaxInstances))); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_INITIAL_COUNT_PROPERTY_VALUE, PropertyNames.INITIAL_COUNT.getPropertyName(), String.valueOf(latestMinInstances), String.valueOf(latestMaxInstances))); } } if (isPropertyChanged(newValues, parentValues, PropertyNames.MAX_INSTANCES) && result.isLeft()) { if (latestMaxInstances < latestInitialCount) { - result = Either.right(componentsUtils.getResponseFormat( - ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER, - PropertyNames.MAX_INSTANCES.getPropertyName(), "higher", String.valueOf(latestInitialCount))); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER, PropertyNames.MAX_INSTANCES.getPropertyName(), "higher", String.valueOf(latestInitialCount))); } } if (isPropertyChanged(newValues, parentValues, PropertyNames.MIN_INSTANCES) && result.isLeft()) { if (latestMinInstances > latestInitialCount) { - result = Either.right(componentsUtils.getResponseFormat( - ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER, - PropertyNames.MIN_INSTANCES.getPropertyName(), "lower", String.valueOf(latestInitialCount))); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER, PropertyNames.MIN_INSTANCES.getPropertyName(), "lower", String.valueOf(latestInitialCount))); } } return result; } + private Either validateMinMaxAndInitialCountPropertyLogic(Map newValues, Map currValues, Map parentValues) { - + Either result; - for(Entry entry : newValues.entrySet()){ + for (Entry entry : newValues.entrySet()) { PropertyNames currPropertyName = entry.getKey(); - if(currPropertyName == PropertyNames.MIN_INSTANCES){ + if (currPropertyName == PropertyNames.MIN_INSTANCES) { String minValue = parentValues.get(PropertyNames.MIN_INSTANCES); String maxValue = newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MAX_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT); - result = validateValueInRange(new ImmutablePair(currPropertyName, entry.getValue()), - new ImmutablePair(PropertyNames.MIN_INSTANCES, minValue), + result = validateValueInRange(new ImmutablePair(currPropertyName, entry.getValue()), new ImmutablePair(PropertyNames.MIN_INSTANCES, minValue), new ImmutablePair(PropertyNames.MAX_INSTANCES, maxValue)); - if(result.isRight()){ + if (result.isRight()) { return result; } - } - else if(currPropertyName == PropertyNames.INITIAL_COUNT){ + } else if (currPropertyName == PropertyNames.INITIAL_COUNT) { String minValue = newValues.containsKey(PropertyNames.MIN_INSTANCES) ? newValues.get(PropertyNames.MIN_INSTANCES) : currValues.get(PropertyNames.MIN_INSTANCES); String maxValue = newValues.containsKey(PropertyNames.MAX_INSTANCES) ? newValues.get(PropertyNames.MAX_INSTANCES) : currValues.get(PropertyNames.MAX_INSTANCES); - result = validateValueInRange(new ImmutablePair(currPropertyName, entry.getValue()), - new ImmutablePair(PropertyNames.MIN_INSTANCES,minValue), + result = validateValueInRange(new ImmutablePair(currPropertyName, entry.getValue()), new ImmutablePair(PropertyNames.MIN_INSTANCES, minValue), new ImmutablePair(PropertyNames.MAX_INSTANCES, maxValue)); - if(result.isRight()){ + if (result.isRight()) { return result; } - } - else if(currPropertyName == PropertyNames.MAX_INSTANCES){ + } else if (currPropertyName == PropertyNames.MAX_INSTANCES) { String minValue = newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MIN_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT); String maxValue = parentValues.get(PropertyNames.MAX_INSTANCES); - result = validateValueInRange(new ImmutablePair(currPropertyName, entry.getValue()), - new ImmutablePair(PropertyNames.MIN_INSTANCES, minValue), + result = validateValueInRange(new ImmutablePair(currPropertyName, entry.getValue()), new ImmutablePair(PropertyNames.MIN_INSTANCES, minValue), new ImmutablePair(PropertyNames.MAX_INSTANCES, maxValue)); - if(result.isRight()){ + if (result.isRight()) { return result; } } } - return Either.left(true); + return Either.left(true); } - private Either validateValueInRange(ImmutablePair newValue, ImmutablePair min, ImmutablePair max) { + private Either validateValueInRange(ImmutablePair newValue, ImmutablePair min, ImmutablePair max) { Either result; final String warnMessage = "Failed to validate {} as property value of {}. It must be not higher than {}, and not lower than {}."; int newValueInt = parseIntValue(newValue.getValue(), newValue.getKey()); int minInt = parseIntValue(min.getValue(), min.getKey()); int maxInt = parseIntValue(max.getValue(), max.getKey()); - if(newValueInt < 0 || minInt < 0 || maxInt < 0){ + if (newValueInt < 0 || minInt < 0 || maxInt < 0) { result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY)); - } - else if (newValueInt < minInt || newValueInt > maxInt) { + } else if (newValueInt < minInt || newValueInt > maxInt) { log.debug(warnMessage, newValue.getValue(), newValue.getKey().getPropertyName(), min.getValue(), max.getValue()); - result = Either.right(componentsUtils.getResponseFormat( - ActionStatus.INVALID_GROUP_MIN_MAX_INSTANCES_PROPERTY_VALUE, - newValue.getKey().getPropertyName(), maxInt == Integer.MAX_VALUE ? Constants.UNBOUNDED : max.getValue(), min.getValue())); - }else{ + result = Either + .right(componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_MIN_MAX_INSTANCES_PROPERTY_VALUE, newValue.getKey().getPropertyName(), maxInt == Integer.MAX_VALUE ? Constants.UNBOUNDED : max.getValue(), min.getValue())); + } else { result = Either.left(true); } return result; } - - private int parseIntValue(String value, PropertyNames propertyName) { + + private int parseIntValue(String value, PropertyNames propertyName) { int result; - if(propertyName == PropertyNames.MAX_INSTANCES ){ + if (propertyName == PropertyNames.MAX_INSTANCES) { result = convertIfUnboundMax(value); } else if (NumberUtils.isNumber(value)) { result = Integer.parseInt(value); - } else{ + } else { result = -1; } return result; } -/** - * validates received new property values and updates group instance in case of success - * @param oldGroupInstance - * @param groupInstanceId - * @param newProperties - * @param inTransaction - * @return - */ + /** + * validates received new property values and updates group instance in case of success + * + * @param oldGroupInstance + * @param groupInstanceId + * @param newProperties + * @param inTransaction + * @return + */ public Either validateAndUpdateGroupInstancePropertyValues(String componentId, String instanceId, GroupInstance oldGroupInstance, List newProperties, boolean inTransaction) { - + Either actionResult = null; Either updateGroupInstanceResult = null; Either, ResponseFormat> validateRes = validateReduceGroupInstancePropertiesBeforeUpdate(oldGroupInstance, newProperties); - if(validateRes.isRight()){ + if (validateRes.isRight()) { log.debug("Failed to validate group instance {} properties before update. ", oldGroupInstance.getName()); - actionResult = Either.right(validateRes.right().value()); + actionResult = Either.right(validateRes.right().value()); } - if(actionResult == null){ + if (actionResult == null) { List validatedReducedNewProperties = validateRes.left().value(); updateGroupInstanceResult = groupsOperation.updateGroupInstancePropertyValuesOnGraph(componentId, instanceId, oldGroupInstance, validatedReducedNewProperties); - if(updateGroupInstanceResult.isRight()){ + if (updateGroupInstanceResult.isRight()) { log.debug("Failed to update group instance {} property values. ", oldGroupInstance.getName()); - actionResult = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateGroupInstanceResult.right().value()))); + actionResult = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateGroupInstanceResult.right().value()))); } } - if(actionResult == null){ + if (actionResult == null) { actionResult = Either.left(updateGroupInstanceResult.left().value()); } return actionResult; } - + private Either, ResponseFormat> validateReduceGroupInstancePropertiesBeforeUpdate(GroupInstance oldGroupInstance, List newProperties) { - + Either validationRes = null; Either, ResponseFormat> actionResult; - Map existingProperties = oldGroupInstance.convertToGroupInstancesProperties().stream().collect(Collectors.toMap(p->p.getName(),p->p)); + Map existingProperties = oldGroupInstance.convertToGroupInstancesProperties().stream().collect(Collectors.toMap(p -> p.getName(), p -> p)); Map newPropertyValues = new EnumMap<>(PropertyNames.class); List reducedProperties = new ArrayList<>(); String currPropertyName; - try{ - for(GroupInstanceProperty currNewProperty : newProperties){ + try { + for (GroupInstanceProperty currNewProperty : newProperties) { currPropertyName = currNewProperty.getName(); validationRes = handleAndAddProperty(reducedProperties, newPropertyValues, currNewProperty, existingProperties.get(currPropertyName)); - if(validationRes.isRight()){ + if (validationRes.isRight()) { log.debug("Failed to handle property {} of group instance {}. ", currPropertyName, oldGroupInstance.getName()); break; } } - if(validationRes == null || validationRes.isLeft()){ + if (validationRes == null || validationRes.isLeft()) { Map existingPropertyValues = new EnumMap<>(PropertyNames.class); Map parentPropertyValues = new EnumMap<>(PropertyNames.class); fillValuesAndParentValuesFromExistingProperties(existingProperties, existingPropertyValues, parentPropertyValues); validationRes = validateMinMaxAndInitialCountPropertyLogic(newPropertyValues, existingPropertyValues, parentPropertyValues); } - if(validationRes.isLeft()){ + if (validationRes.isLeft()) { actionResult = Either.left(reducedProperties); } else { actionResult = Either.right(validationRes.right().value()); } - } catch( Exception e){ + } catch (Exception e) { log.error("Exception occured during validation and reducing group instance properties. The message is {}", e.getMessage(), e); actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } return actionResult; } - private void fillValuesAndParentValuesFromExistingProperties(Map existingProperties, - Map propertyValues, Map parentPropertyValues) { + private void fillValuesAndParentValuesFromExistingProperties(Map existingProperties, Map propertyValues, Map parentPropertyValues) { PropertyNames[] allPropertyNames = PropertyNames.values(); - for(PropertyNames name : allPropertyNames){ - if(isUpdatable(name)){ + for (PropertyNames name : allPropertyNames) { + if (isUpdatable(name)) { propertyValues.put(name, String.valueOf(existingProperties.get(name.getPropertyName()).getValue())); parentPropertyValues.put(name, String.valueOf(existingProperties.get(name.getPropertyName()).getParentValue())); } } } - private Either handleAndAddProperty(List reducedProperties, Map newPropertyValues, - GroupInstanceProperty currNewProperty, GroupInstanceProperty currExistingProperty) { + private Either handleAndAddProperty(List reducedProperties, Map newPropertyValues, GroupInstanceProperty currNewProperty, GroupInstanceProperty currExistingProperty) { Either validationRes = null; String currPropertyName = currNewProperty.getName(); PropertyNames propertyName = PropertyNames.findName(currPropertyName); - try{ - if(currExistingProperty == null){ + try { + if (currExistingProperty == null) { log.warn("The value of property with the name {} cannot be updated. The property not found on group instance. ", currPropertyName); - } - else if(isUpdatable(propertyName)){ + } else if (isUpdatable(propertyName)) { validationRes = validateAndUpdatePropertyValue(currNewProperty, currExistingProperty); - if(validationRes.isRight()){ - log.debug("Failed to validate property value {} of property {}. ", currNewProperty.getValue() , currPropertyName); + if (validationRes.isRight()) { + log.debug("Failed to validate property value {} of property {}. ", currNewProperty.getValue(), currPropertyName); } else { addPropertyUpdatedValues(reducedProperties, propertyName, newPropertyValues, currNewProperty, currExistingProperty); } - } - else{ + } else { validateImmutableProperty(currExistingProperty, currNewProperty); } - if(validationRes == null){ + if (validationRes == null) { validationRes = Either.left(true); } - } catch( Exception e){ + } catch (Exception e) { log.error("Exception occured during handle and adding property. The message is {}", e.getMessage(), e); validationRes = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } @@ -2173,76 +1828,73 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } private boolean isUpdatable(PropertyNames updatablePropertyName) { - return updatablePropertyName != null && - updatablePropertyName.getUpdateBehavior().getLevelNumber() >= GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL.getLevelNumber(); + return updatablePropertyName != null && updatablePropertyName.getUpdateBehavior().getLevelNumber() >= GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL.getLevelNumber(); } - private void addPropertyUpdatedValues(List reducedProperties, PropertyNames propertyName, Map newPropertyValues, - GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) { - - String newValue = newProperty.getValue(); - if(!newValue.equals(String.valueOf(existingProperty.getValue()))){ + private void addPropertyUpdatedValues(List reducedProperties, PropertyNames propertyName, Map newPropertyValues, GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) { + + String newValue = newProperty.getValue(); + if (!newValue.equals(String.valueOf(existingProperty.getValue()))) { newProperty.setValueUniqueUid(existingProperty.getValueUniqueUid()); reducedProperties.add(newProperty); } - if(!isEmptyMinInitialCountValue(propertyName, newValue)){ + if (!isEmptyMinInitialCountValue(propertyName, newValue)) { newPropertyValues.put(propertyName, newValue); } } - + private boolean isEmptyMinInitialCountValue(PropertyNames propertyName, String newValue) { boolean result = false; - if((propertyName == PropertyNames.MIN_INSTANCES || propertyName == PropertyNames.INITIAL_COUNT) && !NumberUtils.isNumber(newValue)){ + if ((propertyName == PropertyNames.MIN_INSTANCES || propertyName == PropertyNames.INITIAL_COUNT) && !NumberUtils.isNumber(newValue)) { result = true; } return result; } private int convertIfUnboundMax(String value) { - + int result; - if(!NumberUtils.isNumber(value)){ + if (!NumberUtils.isNumber(value)) { result = Integer.MAX_VALUE; - } - else{ + } else { result = Integer.parseInt(value); } return result; } private Either validateAndUpdatePropertyValue(GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) { - + Either validationRes = null; String parentValue = existingProperty.getParentValue(); - + newProperty.setParentValue(parentValue); - if(StringUtils.isEmpty(newProperty.getValue())){ + if (StringUtils.isEmpty(newProperty.getValue())) { newProperty.setValue(parentValue); } - if(StringUtils.isEmpty(existingProperty.getValue())){ + if (StringUtils.isEmpty(existingProperty.getValue())) { existingProperty.setValue(parentValue); } - StorageOperationStatus status = groupOperation.validateAndUpdatePropertyValue(newProperty); - if(status != StorageOperationStatus.OK){ + StorageOperationStatus status = groupOperation.validateAndUpdatePropertyValue(newProperty); + if (status != StorageOperationStatus.OK) { log.debug("Failed to validate property value {} of property with name {}. Status is {}. ", newProperty.getValue(), newProperty.getName(), status); validationRes = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status))); } - if(validationRes == null){ + if (validationRes == null) { validationRes = Either.left(true); } return validationRes; } private void validateImmutableProperty(GroupProperty oldProperty, GroupProperty newProperty) { - if(oldProperty.getValue() == null && newProperty.getValue() != null || oldProperty.getValue()!=null && !oldProperty.getValue().equals(newProperty.getValue())){ - log.warn("The value of property with the name {} cannot be updated on service level. Going to ignore new property value {}. ",oldProperty.getName(), newProperty.getValue()); + if (oldProperty.getValue() == null && newProperty.getValue() != null || oldProperty.getValue() != null && !oldProperty.getValue().equals(newProperty.getValue())) { + log.warn("The value of property with the name {} cannot be updated on service level. Going to ignore new property value {}. ", oldProperty.getName(), newProperty.getValue()); } } public Either, ResponseFormat> createGroups(Component component, User user, ComponentTypeEnum componentType, List groupDefinitions) { - Map groups = new HashMap<>(); - //Map groupsPropertiesMap = new HashMap<>(); + Map groups = new HashMap<>(); + // Map groupsPropertiesMap = new HashMap<>(); Either, ResponseFormat> result = null; Either, StorageOperationStatus> createGroupsResult = null; Either, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); @@ -2253,38 +1905,37 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } - //handle groups and convert to tosca data + // handle groups and convert to tosca data if (groupDefinitions != null && !groupDefinitions.isEmpty()) { for (GroupDefinition groupDefinition : groupDefinitions) { - Either handleGroupRes = handleGroup(component, user, componentType, groupDefinition, allDataTypes.left().value()); + Either handleGroupRes = handleGroup(component, user, componentType, groupDefinition, allDataTypes.left().value()); if (handleGroupRes.isRight()) { result = Either.right(handleGroupRes.right().value()); break; } GroupDefinition handledGroup = handleGroupRes.left().value(); groups.put(handledGroup.getName(), new GroupDataDefinition(handledGroup)); - + } } - if(result == null){ + if (result == null) { createGroupsResult = groupsOperation.createGroups(component, user, componentType, groups); - if(createGroupsResult.isRight()){ + if (createGroupsResult.isRight()) { result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); } } - if(result == null){ + if (result == null) { result = Either.left(createGroupsResult.left().value()); } return result; } - + public Either, ResponseFormat> addGroups(Component component, User user, ComponentTypeEnum componentType, List groupDefinitions) { - Either, ResponseFormat> result = null; Either, StorageOperationStatus> createGroupsResult = null; List groups = new ArrayList<>(); - + Either, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); if (allDataTypes.isRight()) { TitanOperationStatus status = allDataTypes.right().value(); @@ -2293,10 +1944,10 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } - //handle groups and convert to tosca data + // handle groups and convert to tosca data if (groupDefinitions != null && !groupDefinitions.isEmpty()) { for (GroupDefinition groupDefinition : groupDefinitions) { - Either handleGroupRes = handleGroup(component, user, componentType, groupDefinition, allDataTypes.left().value()); + Either handleGroupRes = handleGroup(component, user, componentType, groupDefinition, allDataTypes.left().value()); if (handleGroupRes.isRight()) { result = Either.right(handleGroupRes.right().value()); break; @@ -2305,35 +1956,34 @@ public class GroupBusinessLogic extends BaseBusinessLogic { groups.add(new GroupDataDefinition(handledGroup)); } } - if(result == null){ + if (result == null) { createGroupsResult = groupsOperation.addGroups(component, user, componentType, groups); - if(createGroupsResult.isRight()){ + if (createGroupsResult.isRight()) { result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); } } - if(result == null){ + if (result == null) { result = Either.left(createGroupsResult.left().value()); } return result; } - + public Either, ResponseFormat> deleteGroups(Component component, User user, ComponentTypeEnum componentType, List groupDefinitions) { - Either, ResponseFormat> result = null; Either, StorageOperationStatus> createGroupsResult = null; - - createGroupsResult = groupsOperation.deleteGroups(component, user, componentType, groupDefinitions.stream().map(x-> new GroupDataDefinition(x)).collect(Collectors.toList())); - if(createGroupsResult.isRight()){ - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); - } - - if(result == null){ + + createGroupsResult = groupsOperation.deleteGroups(component, user, componentType, groupDefinitions.stream().map(x -> new GroupDataDefinition(x)).collect(Collectors.toList())); + if (createGroupsResult.isRight()) { + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); + } + + if (result == null) { result = Either.left(createGroupsResult.left().value()); } return result; } - + /** * Update specific group version * @@ -2341,34 +1991,34 @@ public class GroupBusinessLogic extends BaseBusinessLogic { * @param inTransaction * @return */ - public Either, ResponseFormat> updateGroups(Component component, ComponentTypeEnum componentType, List groupDefinitions) { + public Either, ResponseFormat> updateGroups(Component component, ComponentTypeEnum componentType, List groupDefinitions) { Either, ResponseFormat> result = null; Either, StorageOperationStatus> createGroupsResult = null; - - createGroupsResult = groupsOperation.updateGroups(component, componentType, groupDefinitions.stream().map(x-> new GroupDataDefinition(x)).collect(Collectors.toList())); - if(createGroupsResult.isRight()){ - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); - } - - if(result == null){ + + createGroupsResult = groupsOperation.updateGroups(component, componentType, groupDefinitions.stream().map(x -> new GroupDataDefinition(x)).collect(Collectors.toList())); + if (createGroupsResult.isRight()) { + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value()))); + } + + if (result == null) { result = Either.left(createGroupsResult.left().value()); } return result; } - + public Either handleGroup(Component component, User user, ComponentTypeEnum componentType, GroupDefinition groupDefinition, Map allDAtaTypes) { - + Either result = null; - - log.trace("Going to create group {}" , groupDefinition); + + log.trace("Going to create group {}", groupDefinition); // 3. verify group not already exist List groups = component.getGroups(); boolean found = false; if (groups != null && false == groups.isEmpty()) { - + GroupDefinition existGroupDef = groups.stream().filter(p -> p.getName().equalsIgnoreCase(groupDefinition.getName())).findFirst().orElse(null); - + found = existGroupDef != null; } if (true == found) { @@ -2413,7 +2063,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { return result; } List groupTypeProperties = groupTypeDefinition.getProperties(); - + List properties = groupDefinition.convertToGroupProperties(); List updatedGroupTypeProperties = new ArrayList<>(); if (properties != null && false == properties.isEmpty()) { @@ -2429,20 +2079,20 @@ public class GroupBusinessLogic extends BaseBusinessLogic { int i = 1; for (GroupProperty prop : properties) { addPropertyResult = handleProperty(prop, groupTypePropertiesMap.get(prop.getName()), i, allDAtaTypes); - if(addPropertyResult.isRight()){ + if (addPropertyResult.isRight()) { BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "failed to validate property", ErrorSeverity.INFO); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertyResult.right().value())))); } updatedGroupTypeProperties.add(addPropertyResult.left().value()); - + i++; } } - if(groupDefinition.getUniqueId() == null){ + if (groupDefinition.getUniqueId() == null) { String uid = UniqueIdBuilder.buildGroupingUid(component.getUniqueId(), groupDefinition.getName()); groupDefinition.setUniqueId(uid); } - groupDefinition.convertFromGroupProperties(updatedGroupTypeProperties); + groupDefinition.convertFromGroupProperties(updatedGroupTypeProperties); groupDefinition.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID()); groupDefinition.setGroupUUID(UniqueIdBuilder.generateUUID()); groupDefinition.setVersion(INITIAL_VERSION); @@ -2450,9 +2100,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic { return Either.left(groupDefinition); } - - - + public Either handleProperty(GroupProperty groupProperty, PropertyDefinition prop, Integer index, Map allDataTypes) { if (prop == null) { @@ -2471,7 +2119,6 @@ public class GroupBusinessLogic extends BaseBusinessLogic { String innerType = checkInnerType.left().value(); - log.debug("Before validateAndUpdatePropertyValue"); Either isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes); log.debug("After validateAndUpdatePropertyValue. isValid = {}", isValid); @@ -2490,24 +2137,19 @@ public class GroupBusinessLogic extends BaseBusinessLogic { } String uniqueId = UniqueIdBuilder.buildGroupPropertyValueUid((String) prop.getUniqueId(), index); - + groupProperty.setUniqueId(uniqueId); groupProperty.setValue(newValue); - groupProperty.setType(prop.getType()); + groupProperty.setType(prop.getType()); groupProperty.setDefaultValue(prop.getDefaultValue()); groupProperty.setDescription(prop.getDescription()); groupProperty.setSchema(prop.getSchema()); groupProperty.setPassword(prop.isPassword()); groupProperty.setParentUniqueId(prop.getUniqueId()); - log.debug("Before adding property value to graph {}", groupProperty); - return Either.left(groupProperty); } - - - - + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java index 33390e7e98..1ff22dd17f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java @@ -33,7 +33,6 @@ import java.util.function.Function; import org.apache.commons.lang3.StringEscapeUtils; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; -import org.openecomp.sdc.be.model.AttributeDefinition; import org.openecomp.sdc.be.model.HeatParameterDefinition; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.LifecycleStateEnum; @@ -103,7 +102,7 @@ public final class ImportUtils { } public enum ResultStatusEnum { - ELEMENT_NOT_FOUND, GENERAL_ERROR, OK, INVALID_PROPERTY_DEFAULT_VALUE, INVALID_PROPERTY_TYPE, INVALID_PROPERTY_VALUE, MISSING_ENTRY_SCHEMA_TYPE + ELEMENT_NOT_FOUND, GENERAL_ERROR, OK, INVALID_PROPERTY_DEFAULT_VALUE, INVALID_PROPERTY_TYPE, INVALID_PROPERTY_VALUE, MISSING_ENTRY_SCHEMA_TYPE, INVALID_PROPERTY_NAME } public enum ToscaElementTypeEnum { @@ -346,9 +345,9 @@ public final class ImportUtils { return inputDef; } - public static AttributeDefinition createModuleAttribute(Map attributeMap) { + public static PropertyDefinition createModuleAttribute(Map attributeMap) { - AttributeDefinition attributeDef = new AttributeDefinition(); + PropertyDefinition attributeDef = new PropertyDefinition(); ImportUtils.setField(attributeMap, ToscaTagNamesEnum.TYPE, type -> attributeDef.setType(type)); ImportUtils.setField(attributeMap, ToscaTagNamesEnum.DESCRIPTION, desc -> attributeDef.setDescription(desc)); ImportUtils.setField(attributeMap, ToscaTagNamesEnum.STATUS, status -> attributeDef.setStatus(status)); @@ -374,7 +373,7 @@ public final class ImportUtils { } - private static void setAttributeFieldStatus(Map propertyValue, AttributeDefinition propertyDef) { + private static void setAttributeFieldStatus(Map propertyValue, PropertyDefinition propertyDef) { Either propertyFieldIsStatus = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.STATUS); if (propertyFieldIsStatus.isLeft()) { propertyDef.setStatus(propertyFieldIsStatus.left().value()); @@ -392,7 +391,7 @@ public final class ImportUtils { } - private static void setAttributeScheme(Map propertyValue, AttributeDefinition propertyDefinition) { + private static void setAttributeScheme(Map propertyValue, PropertyDefinition propertyDefinition) { Either eitherSchema = getSchema(propertyValue); if (eitherSchema.isLeft()) { SchemaDefinition schemaDef = new SchemaDefinition(); @@ -465,7 +464,7 @@ public final class ImportUtils { return ResultStatusEnum.OK; } - private static ResultStatusEnum setAttributeFieldDefaultValue(Map propertyValue, AttributeDefinition dataDefinition) { + private static ResultStatusEnum setAttributeFieldDefaultValue(Map propertyValue, PropertyDefinition dataDefinition) { Either propertyFieldDefaultValue = findToscaElement(propertyValue, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL); Gson gson = GsonFactory.getGson(); if (propertyFieldDefaultValue.isLeft()) { @@ -519,7 +518,7 @@ public final class ImportUtils { } } - private static void setAttributeFieldType(Map propertyValue, AttributeDefinition dataDefinition) { + private static void setAttributeFieldType(Map propertyValue, PropertyDefinition dataDefinition) { Either propertyFieldType = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.TYPE); if (propertyFieldType.isLeft()) { dataDefinition.setType(propertyFieldType.left().value()); @@ -533,7 +532,7 @@ public final class ImportUtils { } } - private static void setAttributeFieldDescription(Map propertyValue, AttributeDefinition dataDefinition) { + private static void setAttributeFieldDescription(Map propertyValue, PropertyDefinition dataDefinition) { Either propertyFieldDescription = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.DESCRIPTION); if (propertyFieldDescription.isLeft()) { dataDefinition.setDescription(propertyFieldDescription.left().value()); @@ -556,9 +555,9 @@ public final class ImportUtils { } - public static Either, ResultStatusEnum> getAttributes(Map toscaJson) { - Function elementGenByName = elementName -> createAttribute(elementName); - Function, AttributeDefinition> func = map -> createModuleAttribute(map); + public static Either, ResultStatusEnum> getAttributes(Map toscaJson) { + Function elementGenByName = elementName -> createAttribute(elementName); + Function, PropertyDefinition> func = map -> createModuleAttribute(map); return getElements(toscaJson, ToscaTagNamesEnum.ATTRIBUTES, elementGenByName, func); } @@ -595,8 +594,8 @@ public final class ImportUtils { } - private static AttributeDefinition createAttribute(String name) { - AttributeDefinition attribute = new AttributeDefinition(); + private static PropertyDefinition createAttribute(String name) { + PropertyDefinition attribute = new PropertyDefinition(); attribute.setName(name); return attribute; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java index 8ffee1fd34..a2809b44cf 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java @@ -50,6 +50,7 @@ import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.CapabilityDefinition; import org.openecomp.sdc.be.model.ComponentInstInputsMap; @@ -551,7 +552,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic { return result; } - Either>, StorageOperationStatus> addciInputsEither = toscaOperationFacade.addComponentInstanceInputsToComponent(inputsValueToCreateMap, component.getUniqueId()); + Either>, StorageOperationStatus> addciInputsEither = toscaOperationFacade.addComponentInstanceInputsToComponent(component, inputsValueToCreateMap); if(addciInputsEither.isRight()){ log.debug("Failed to add inputs values under component {}. Status is {}", component.getUniqueId(), assotiateInputsEither.right().value()); result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(assotiateInputsEither.right().value()))); @@ -621,6 +622,8 @@ public class InputsBusinessLogic extends BaseBusinessLogic { input.setImmutable(oldInput.isImmutable()); input.setDefinition(oldInput.isDefinition()); input.setRequired(oldInput.isRequired()); + input.setOwnerId(null); + input.setParentUniqueId(null); inputsToCreate.put(input.getName(), input); @@ -739,7 +742,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic { } if (resourceProperties != null) { Map generatedInputs = resourceProperties.stream().collect(Collectors.toMap(i -> i.getName(), i -> i)); - Either, String> mergeEither = PropertyDataDefinition.mergeProperties(generatedInputs, inputs, false); + Either, String> mergeEither = ToscaDataDefinition.mergeDataMaps(generatedInputs, inputs); if(mergeEither.isRight()){ return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, mergeEither.right().value())); } @@ -808,6 +811,8 @@ public class InputsBusinessLogic extends BaseBusinessLogic { if (!optionalInput.isPresent()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.INPUT_IS_NOT_CHILD_OF_COMPONENT, inputId, componentId)); } + + InputDefinition inputForDelete = optionalInput.get(); // Lock component Either lockResultEither = lockComponent(componentId, component, "deleteInput"); @@ -818,8 +823,6 @@ public class InputsBusinessLogic extends BaseBusinessLogic { } // Delete input operations - - InputDefinition inputForDelete = optionalInput.get(); try { StorageOperationStatus status = toscaOperationFacade.deleteInputOfResource(component, inputForDelete.getName()); if(status != StorageOperationStatus.OK){ @@ -863,7 +866,9 @@ public class InputsBusinessLogic extends BaseBusinessLogic { resetInputName(mappedToscaTemplate, inputForDelete.getName()); - value = gson.toJson(mappedToscaTemplate); + value = ""; + if(!mappedToscaTemplate.isEmpty()) + value = gson.toJson(mappedToscaTemplate); propertyValue.setValue(value); String compInstId = propertyValue.getComponentInstanceId(); propertyValue.setRules(null); @@ -1159,6 +1164,8 @@ public class InputsBusinessLogic extends BaseBusinessLogic { if (properties != null && !properties.isEmpty()) { for (ComponentInstancePropInput propInput : properties) { + propInput.setOwnerId(null); + propInput.setParentUniqueId(null); Either createInputRes = createInputForComponentInstance(component, origComponent,ci, inputsToCreate, propertiesToCreate, dataTypes, inputName, propInput); if (createInputRes.isRight()) { @@ -1260,6 +1267,10 @@ public class InputsBusinessLogic extends BaseBusinessLogic { inputsToCreate.put(input.getName(), input); + List propertiesList = new ArrayList<>(); // adding the property with the new value for UI + propertiesList.add(prop); + input.setProperties(propertiesList); + return Either.left(input); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java index ffcb87c99c..587be4d169 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java @@ -74,7 +74,6 @@ import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.info.ArtifactTemplateInfo; import org.openecomp.sdc.be.info.MergedArtifactInfo; import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.AttributeDefinition; import org.openecomp.sdc.be.model.CapabilityDefinition; import org.openecomp.sdc.be.model.CapabilityTypeDefinition; import org.openecomp.sdc.be.model.Component; @@ -542,8 +541,15 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { try { Either, ResponseFormat> prepareForUpdate = null; Resource preparedResource = null; - - Either>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(csar.left().value(), csarUUID, yamlFileName, oldRresource, user, true); + Either uploadComponentInstanceInfoMap = parseResourceInfoFromYaml(yamlFileName, newRresource, toscaYamlCsarStatus.left().value().getValue(), user); + if (uploadComponentInstanceInfoMap.isRight()) { + ResponseFormat responseFormat = uploadComponentInstanceInfoMap.right().value(); + componentsUtils.auditResource(responseFormat, user, newRresource, "", "", updateResource, null); + result = Either.right(responseFormat); + return result; + } + Map instances = uploadComponentInstanceInfoMap.left().value().getInstances(); + Either>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(csar.left().value(), csarUUID, yamlFileName, oldRresource, user, true, instances); if (findNodeTypesArtifactsToHandleRes.isRight()) { log.debug("failed to find node types for update with artifacts during import csar {}. ", csarUUID); result = Either.right(findNodeTypesArtifactsToHandleRes.right().value()); @@ -571,14 +577,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return result; } - Either uploadComponentInstanceInfoMap = parseResourceInfoFromYaml(yamlFileName, preparedResource, yamlFileContents, user); - if (uploadComponentInstanceInfoMap.isRight()) { - ResponseFormat responseFormat = uploadComponentInstanceInfoMap.right().value(); - componentsUtils.auditResource(responseFormat, user, preparedResource, "", "", updateResource, null); - result = Either.right(responseFormat); - return result; - } - Map inputs = uploadComponentInstanceInfoMap.left().value().getInputs(); Either createInputsOnResource = createInputsOnResource(preparedResource, user, inputs, true); if (createInputsOnResource.isRight()) { @@ -590,7 +588,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } preparedResource = createInputsOnResource.left().value(); - Map instances = uploadComponentInstanceInfoMap.left().value().getInstances(); Either createResourcesInstancesEither = createResourceInstances(user, yamlFileName, preparedResource, instances, true, false, parseNodeTypeInfoYamlEither.left().value()); if (createResourcesInstancesEither.isRight()) { log.debug("failed to create resource instances status is {}", createResourcesInstancesEither.right().value()); @@ -677,7 +674,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } private Either>>, ResponseFormat> findNodeTypesArtifactsToHandle(Map csar, String csarUUID, String yamlFileName, Resource oldResource, User user, - boolean inTransaction) { + boolean inTransaction, Map uploadComponentInstanceInfoMap) { Map> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csar); Map>> nodeTypesArtifactsToHandle = new HashMap<>(); @@ -685,7 +682,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { try { nodeTypesArtifactsToHandleRes = Either.left(nodeTypesArtifactsToHandle); - List>, String>> extractedVfcToscaNames = extractVfcToscaNames(csar, yamlFileName, oldResource.getSystemName()); + List>, String>> extractedVfcToscaNames = extractVfcToscaNames(csar, yamlFileName, oldResource.getSystemName(), uploadComponentInstanceInfoMap); validateNodeTypeIdentifiers(extractedVfcsArtifacts, extractedVfcToscaNames); Either>, ResponseFormat> curNodeTypeArtifactsToHandleRes = null; EnumMap> curNodeTypeArtifactsToHandle = null; @@ -913,7 +910,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return handleNodeTypeArtifactsRes; } - private List>, String>> extractVfcToscaNames(Map csar, String yamlFileName, String vfResourceName) { + @SuppressWarnings("unchecked") + private List>, String>> extractVfcToscaNames(Map csar, String yamlFileName, String vfResourceName, Map uploadComponentInstanceInfoMap) { List>, String>> vfcToscaNames = new ArrayList<>(); Map nodeTypes; if (csar != null) { @@ -921,12 +919,20 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { putNodeTypesFromYaml(csar, yamlFileName, nodeTypes); putNodeTypesFromYaml(csar, Constants.GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE, nodeTypes); putNodeTypesFromYaml(csar, Constants.ABSTRACT_SUBSTITUTE_GLOBAL_TYPES_SERVICE_TEMPLATE, nodeTypes); - + Map nestedServiceTemplatesMap = new HashMap<>(); + for(UploadComponentInstanceInfo ci : uploadComponentInstanceInfoMap.values()){ + if(ci.getProperties() != null && ci.getProperties().containsKey("service_template_filter")){ + String tempName = CsarUtils.DEFINITIONS_PATH + ((Map)ci.getProperties().get("service_template_filter").get(0).getValue()).get("substitute_service_template"); + putNodeTypesFromYaml(csar,tempName, nodeTypes); + nestedServiceTemplatesMap.put(ci.getType(), tempName); + } + } + if (!nodeTypes.isEmpty()) { Iterator> nodesNameEntry = nodeTypes.entrySet().iterator(); while (nodesNameEntry.hasNext()) { Entry nodeType = nodesNameEntry.next(); - addVfcToscaNameFindSubstitutes(csar, vfResourceName, vfcToscaNames, nodeType.getKey()); + addVfcToscaNameFindSubstitutes(csar, vfResourceName, vfcToscaNames, nodeType.getKey(), nestedServiceTemplatesMap); } } } @@ -947,20 +953,23 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } } - private void addVfcToscaNameFindSubstitutes(Map csar, String vfResourceName, List>, String>> vfcToscaNames, String nodeTypeFullName) { + private void addVfcToscaNameFindSubstitutes(Map csar, String vfResourceName, List>, String>> vfcToscaNames, String nodeTypeFullName, Map nestedServiceTemplatesMap) { String toscaResourceName = buildNestedVfcToscaResourceName(vfResourceName, nodeTypeFullName); - String nodeTypeTemplateYamlName = buildNestedSubstituteYamlName(nodeTypeFullName); + String nodeTypeTemplateYamlName =null; + if(nestedServiceTemplatesMap.containsKey(nodeTypeFullName)){ + nodeTypeTemplateYamlName = nestedServiceTemplatesMap.get(nodeTypeFullName); + } List relatedVfcsToscaNameSpaces = new ArrayList<>(); relatedVfcsToscaNameSpaces.add(buildNestedVfcToscaNamespace(nodeTypeFullName)); - if (csar.containsKey(nodeTypeTemplateYamlName)) { - addSubstituteToscaNamespacesRecursively(csar, nodeTypeTemplateYamlName, relatedVfcsToscaNameSpaces); + if (nodeTypeTemplateYamlName!=null && csar.containsKey(nodeTypeTemplateYamlName)) { + addSubstituteToscaNamespacesRecursively(csar, nodeTypeTemplateYamlName, relatedVfcsToscaNameSpaces, nestedServiceTemplatesMap); } ImmutablePair> toscaNameSpacesHierarchy = new ImmutablePair<>(nodeTypeFullName, relatedVfcsToscaNameSpaces); vfcToscaNames.add(new ImmutablePair<>(toscaNameSpacesHierarchy, toscaResourceName)); } - private void addSubstituteToscaNamespacesRecursively(Map csar, String yamlFileName, List toscaNameSpaces) { + private void addSubstituteToscaNamespacesRecursively(Map csar, String yamlFileName, List toscaNameSpaces, Map nestedServiceTemplatesMap) { Map nodeTypes = new HashMap<>(); @@ -978,10 +987,13 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } toscaNameSpaces.add(toscaNameSpace); - String nodeTypeTemplateYamlName = buildNestedSubstituteYamlName(nodeTypeFullName); + String nodeTypeTemplateYamlName =null; + if(nestedServiceTemplatesMap.containsKey(nodeTypeFullName)){ + nodeTypeTemplateYamlName = nestedServiceTemplatesMap.get(nodeTypeFullName); + } - if (csar.containsKey(nodeTypeTemplateYamlName)) { - addSubstituteToscaNamespacesRecursively(csar, nodeTypeTemplateYamlName, toscaNameSpaces); + if (nodeTypeTemplateYamlName!=null && csar.containsKey(nodeTypeTemplateYamlName)) { + addSubstituteToscaNamespacesRecursively(csar, nodeTypeTemplateYamlName, toscaNameSpaces, nestedServiceTemplatesMap); } } } @@ -1651,7 +1663,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { Either result; Either createResourcesInstancesEither; - Map>> nodeTypesArtifactsToCreate = findNodeTypeArtifactsToCreate(csar, yamlName, resource); + Map>> nodeTypesArtifactsToCreate = findNodeTypeArtifactsToCreate(csar, yamlName, resource, uploadComponentInstanceInfoMap); log.debug("************* Going to create all nodes {}", yamlName); Either, ResponseFormat> createdResourcesFromdNodeTypeMap = this.handleNodeTypes(yamlName, resource, user, topologyTemplateYaml, csar, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts); @@ -1694,10 +1706,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return result; } - private Map>> findNodeTypeArtifactsToCreate(Map csar, String yamlName, Resource resource) { + private Map>> findNodeTypeArtifactsToCreate(Map csar, String yamlName, Resource resource, Map uploadComponentInstanceInfoMap) { Map> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csar); - List>, String>> extractedVfcToscaNames = extractVfcToscaNames(csar, yamlName, resource.getSystemName()); + List>, String>> extractedVfcToscaNames = extractVfcToscaNames(csar, yamlName, resource.getSystemName(), uploadComponentInstanceInfoMap); validateNodeTypeIdentifiers(extractedVfcsArtifacts, extractedVfcToscaNames); Map>> nodeTypesArtifactsToHandle = null; if (!extractedVfcsArtifacts.isEmpty() && !extractedVfcToscaNames.isEmpty()) { @@ -3429,7 +3441,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { Map>> instCapabilties = new HashMap<>(); Map>> instRequirements = new HashMap<>(); Map> instArtifacts = new HashMap<>(); - Map> instAttributes = new HashMap<>(); + Map> instAttributes = new HashMap<>(); Map originCompMap = new HashMap<>(); List relations = new ArrayList<>(); @@ -4321,7 +4333,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { List getInputList = (List) getInput; getInputInfo.setPropName(propName); getInputInfo.setInputName((String) getInputList.get(0)); - if (getInputList.size() >= 1) { + if (getInputList.size() > 1) { Object indexObj = getInputList.get(1); if (indexObj instanceof Integer) { getInputInfo.setIndexValue((Integer) indexObj); @@ -5838,7 +5850,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return Either.left(true); } - // Tal G for extending inheritance US815447 + // for extending inheritance US815447 private Either validateDerivedFromExtending(User user, Resource currentResource, Resource updateInfoResource, AuditingActionEnum actionEnum) { // If updated resource is not deriving, should fail validation /* @@ -6633,12 +6645,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { return toscaResourceName; } - private String buildNestedSubstituteYamlName(String nodeTypeFullName) { - String[] nodeTypeFullNameParsed = nodeTypeFullName.split("\\."); - String nodeTypeActualName = nodeTypeFullNameParsed[nodeTypeFullNameParsed.length - 1]; - return CsarUtils.DEFINITIONS_PATH + nodeTypeActualName + Constants.SERVICE_TEMPLATE_FILE_POSTFIX; - } - public ICacheMangerOperation getCacheManagerOperation() { return cacheManagerOperation; } @@ -6726,6 +6732,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { Either resourceResultEither = toscaOperationFacade.getToscaElement(resourceId, paramsToRetuen); if (resourceResultEither.isRight()) { + if(resourceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) { + log.debug("Failed to found resource with id {} ", resourceId); + Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId)); + } + log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn.toString()); return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceResultEither.right().value()), "")); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java index f35515f8fe..b157b635b4 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java @@ -31,6 +31,7 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.function.Function; +import java.util.regex.Pattern; import java.util.stream.Collectors; import javax.servlet.ServletContext; @@ -46,12 +47,12 @@ import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.AttributeDefinition; import org.openecomp.sdc.be.model.CapabilityDefinition; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.InterfaceDefinition; @@ -101,7 +102,9 @@ public class ResourceImportManager { @Autowired protected ResourceOperation resourceOperation; - + + public final static Pattern PROPERTY_NAME_PATTERN_IGNORE_LENGTH = Pattern + .compile("[\\w\\-\\_\\d\\:]+"); @Autowired protected CapabilityTypeOperation capabilityTypeOperation; @Autowired @@ -289,7 +292,9 @@ public class ResourceImportManager { eitherResult = setCapabilities(toscaJson, resource, parentResource); if (eitherResult.isRight()) return eitherResult; - setProperties(toscaJson, resource); + eitherResult = setProperties(toscaJson, resource); + if (eitherResult.isRight()) + return eitherResult; eitherResult = setRequirements(toscaJson, resource, parentResource); if (eitherResult.isRight()) return eitherResult; @@ -467,10 +472,10 @@ public class ResourceImportManager { return result; } - private ResultStatusEnum setProperties(Map toscaJson, Resource resource) { + private Either setProperties(Map toscaJson, Resource resource) { Map reducedToscaJson = new HashMap<>(toscaJson); ImportUtils.removeElementFromJsonMap(reducedToscaJson, "capabilities"); - ResultStatusEnum result = ResultStatusEnum.OK; + Either result = Either.left(true); Either, ResultStatusEnum> properties = ImportUtils.getProperties(reducedToscaJson); if (properties.isLeft()) { List propertiesList = new ArrayList<>(); @@ -478,28 +483,32 @@ public class ResourceImportManager { if (value != null) { for (Entry entry : value.entrySet()) { String name = entry.getKey(); + if(!PROPERTY_NAME_PATTERN_IGNORE_LENGTH.matcher(name).matches()){ + log.debug("The property with invalid name {} occured upon import resource {}. ", name, resource.getName()); + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromResultStatusEnum(ResultStatusEnum.INVALID_PROPERTY_NAME, JsonPresentationFields.PROPERTY))); + } PropertyDefinition propertyDefinition = entry.getValue(); propertyDefinition.setName(name); propertiesList.add(propertyDefinition); } } resource.setProperties(propertiesList); - } else { - result = properties.right().value(); + } else if(properties.right().value() != ResultStatusEnum.ELEMENT_NOT_FOUND){ + result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromResultStatusEnum(properties.right().value(), JsonPresentationFields.PROPERTY))); } return result; } private ResultStatusEnum setAttributes(Map toscaJson, Resource resource) { ResultStatusEnum result = ResultStatusEnum.OK; - Either, ResultStatusEnum> attributes = ImportUtils.getAttributes(toscaJson); + Either, ResultStatusEnum> attributes = ImportUtils.getAttributes(toscaJson); if (attributes.isLeft()) { - List attributeList = new ArrayList<>(); - Map value = attributes.left().value(); + List attributeList = new ArrayList<>(); + Map value = attributes.left().value(); if (value != null) { - for (Entry entry : value.entrySet()) { + for (Entry entry : value.entrySet()) { String name = entry.getKey(); - AttributeDefinition attributeDef = entry.getValue(); + PropertyDefinition attributeDef = entry.getValue(); attributeDef.setName(name); attributeList.add(attributeDef); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java index 1f481a7b5a..bc1c6e5910 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java @@ -1390,7 +1390,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } Collections.sort(vfModulePayloadForCurrVF, (art1, art2) -> VfModuleArtifactPayload.compareByGroupName(art1, art2)); // Update Payload With Heat Env - vfModulePayloadForCurrVF.stream().forEach(e -> addHeatEnvArtifactsToVFModulePayload(e, currVFInstance)); +// vfModulePayloadForCurrVF.stream().forEach(e -> addHeatEnvArtifactsToVFModulePayload(e, currVFInstance)); final Gson gson = new GsonBuilder().setPrettyPrinting().create(); @@ -1436,7 +1436,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { vfModuleAertifact = getVfModuleInstArtifactForCompInstance(currVFInstance, service, modifier, groupsForCurrVF, payloadWrapper, responseWrapper); } if (responseWrapper.isEmpty() && vfModuleAertifact != null) { - vfModuleAertifact = fillVfModulePayload(modifier, currVFInstance, vfModuleAertifact, shouldLock, payloadWrapper, responseWrapper); + vfModuleAertifact = fillVfModulePayload(modifier, currVFInstance, vfModuleAertifact, shouldLock, payloadWrapper, responseWrapper, service); } Either result; @@ -1449,21 +1449,21 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return result; } - private ArtifactDefinition fillVfModulePayload(User modifier, ComponentInstance currVF, ArtifactDefinition vfModuleArtifact, boolean shouldLock, Wrapper payloadWrapper, Wrapper responseWrapper) { + private ArtifactDefinition fillVfModulePayload(User modifier, ComponentInstance currVF, ArtifactDefinition vfModuleArtifact, boolean shouldLock, Wrapper payloadWrapper, Wrapper responseWrapper, Service service) { ArtifactDefinition result = null; - final Either eitherResource = toscaOperationFacade.getToscaElement(currVF.getComponentUid()); - if (eitherResource.isRight()) { - responseWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherResource.right().value()))); - } else if (!payloadWrapper.isEmpty()) { - Resource resource = eitherResource.left().value(); - Either eitherPayload = artifactsBusinessLogic.generateArtifactPayload(vfModuleArtifact, resource.getComponentType(), resource, currVF.getName(), modifier, shouldLock, () -> System.currentTimeMillis(), +// final Either eitherResource = toscaOperationFacade.getToscaElement(currVF.getComponentUid()); +// if (eitherResource.isRight()) { +// responseWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherResource.right().value()))); +// } else if (!payloadWrapper.isEmpty()) { +// Resource resource = eitherResource.left().value(); + Either eitherPayload = artifactsBusinessLogic.generateArtifactPayload(vfModuleArtifact, ComponentTypeEnum.RESOURCE_INSTANCE, service, currVF.getName(), modifier, shouldLock, () -> System.currentTimeMillis(), () -> Either.left(artifactsBusinessLogic.createEsArtifactData(vfModuleArtifact, payloadWrapper.getInnerElement().getBytes(StandardCharsets.UTF_8))), currVF.getUniqueId()); if (eitherPayload.isLeft()) { result = eitherPayload.left().value(); } else { responseWrapper.setInnerElement(eitherPayload.right().value()); } - } +// } if (result == null) { result = vfModuleArtifact; } @@ -1962,13 +1962,18 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return result; } - public Either getUiComponentDataTransferByComponentId(String resourceId, List dataParamsToReturn) { + public Either getUiComponentDataTransferByComponentId(String serviceId, List dataParamsToReturn) { ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn); - Either serviceResultEither = toscaOperationFacade.getToscaElement(resourceId, paramsToRetuen); + Either serviceResultEither = toscaOperationFacade.getToscaElement(serviceId, paramsToRetuen); if (serviceResultEither.isRight()) { - log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn.toString()); + if(serviceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) { + log.debug("Failed to found service with id {} ", serviceId); + Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceId)); + } + + log.debug("failed to get service by id {} with filters {}", serviceId, dataParamsToReturn.toString()); return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(serviceResultEither.right().value()), "")); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java index d6cbd3663c..14f54e4c19 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java @@ -21,7 +21,10 @@ package org.openecomp.sdc.be.components.lifecycle; import java.util.Arrays; +import java.util.Collection; import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; @@ -29,16 +32,22 @@ import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.jsongraph.TitanDao; import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementOperation; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -97,6 +106,7 @@ public class CheckoutTransition extends LifeCycleTransition { ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType); result = Either.right(responseFormat); } else { + Component clonedComponent = ModelConverter.convertFromToscaElement(checkoutResourceResult.left().value()); result = Either.left(clonedComponent); Either upgradeToLatestGeneric = componentBl.shouldUpgradeToLatestGeneric(clonedComponent); @@ -132,7 +142,7 @@ public class CheckoutTransition extends LifeCycleTransition { private StorageOperationStatus upgradeToLatestGenericData(Component clonedComponent) { - StorageOperationStatus updateStatus = null; + StorageOperationStatus updateStatus = StorageOperationStatus.OK; Either updateEither = toscaOperationFacade.updateToscaElement(clonedComponent); if (updateEither.isRight()) updateStatus = updateEither.right().value(); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java index 46505b843e..6edfe81fee 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java @@ -11,6 +11,7 @@ import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer; +import org.openecomp.sdc.be.ui.model.UiComponentMetadata; import org.openecomp.sdc.be.ui.model.UiResourceDataTransfer; import org.openecomp.sdc.be.ui.model.UiResourceMetadata; import org.openecomp.sdc.be.ui.model.UiServiceDataTransfer; @@ -215,4 +216,20 @@ public class UiComponentDataConverter { return dataTransfer; } + + public static UiComponentMetadata convertToUiComponentMetadata(Component component) { + + UiComponentMetadata uiComponentMetadata = null; + switch (component.getComponentType()) { + case RESOURCE: + Resource resource = (Resource)component; + uiComponentMetadata = new UiResourceMetadata(component.getCategories(), resource.getDerivedFrom(), (ResourceMetadataDataDefinition) resource.getComponentMetadataDefinition().getMetadataDataDefinition()); + break; + case SERVICE: + uiComponentMetadata = new UiServiceMetadata(component.getCategories(), (ServiceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()); + default: + + } + return uiComponentMetadata; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/EcompIntImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/EcompIntImpl.java index 7b49d3fcea..c88ec87d58 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/EcompIntImpl.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/EcompIntImpl.java @@ -26,7 +26,7 @@ import java.util.List; import javax.servlet.http.HttpServletRequest; import org.openecomp.portalsdk.core.onboarding.crossapi.IPortalRestAPIService; -import org.openecomp.portalsdk.core.onboarding.crossapi.PortalAPIException; +import org.openecomp.portalsdk.core.onboarding.exception.PortalAPIException; import org.openecomp.portalsdk.core.restful.domain.EcompRole; import org.openecomp.portalsdk.core.restful.domain.EcompUser; import org.openecomp.sdc.be.config.BeEcompErrorManager; @@ -37,6 +37,7 @@ import org.openecomp.sdc.be.ecomp.converters.EcompUserConverter; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -378,4 +379,28 @@ public class EcompIntImpl implements IPortalRestAPIService { UserBusinessLogic userBusinessLogic = (UserBusinessLogic) ctx.getBean("userBusinessLogic"); return userBusinessLogic; } + + /** + * Gets and returns the userId for the logged-in user based on the request. + * If any error occurs, the method should throw PortalApiException with an + * appropriate message. The FW library will catch the exception and send an + * appropriate response to Portal. + * + * As a guideline for AT&T specific implementation, see the sample apps + * repository + * https://codecloud.web.att.com/projects/EP_SDK/repos/ecomp_portal_sdk_third_party/ + * for a sample implementation for on-boarded applications using EPSDK-FW. + * However, the app can always choose to have a custom implementation of + * this method. For Open-source implementation, for example, the app will + * have a totally different implementation for this method. + * + * @param request + * @return true if the request contains appropriate credentials, else false. + * @throws PortalAPIException + * If an unexpected error occurs while processing the request. + */ + @Override + public String getUserId(HttpServletRequest request) throws PortalAPIException { + return request.getHeader(Constants.USER_ID_HEADER); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/AssetMetadataConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/AssetMetadataConverter.java new file mode 100644 index 0000000000..2e94dfc554 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/AssetMetadataConverter.java @@ -0,0 +1,391 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.ecomp.converters; + +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.distribution.servlet.DistributionCatalogServlet; +import org.openecomp.sdc.be.externalapi.servlet.representation.ArtifactMetadata; +import org.openecomp.sdc.be.externalapi.servlet.representation.AssetMetadata; +import org.openecomp.sdc.be.externalapi.servlet.representation.ResourceAssetDetailedMetadata; +import org.openecomp.sdc.be.externalapi.servlet.representation.ResourceAssetMetadata; +import org.openecomp.sdc.be.externalapi.servlet.representation.ResourceInstanceMetadata; +import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceAssetDetailedMetadata; +import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceAssetMetadata; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import fj.data.Either; + +@org.springframework.stereotype.Component("asset-metadata-utils") +public class AssetMetadataConverter { + private static Logger log = LoggerFactory.getLogger(DistributionCatalogServlet.class.getName()); + + @Autowired + private ComponentsUtils componentsUtils; + + @Autowired + protected ToscaOperationFacade toscaOperationFacade; + + /* + * Relative asset’s URL. Should be used in REST GET API to download the asset’s CSAR. https://{serverBaseURL}/{csarPath} can be obtained from (HttpServletRequest)request.getServerName() + */ + public Either, ResponseFormat> convertToAssetMetadata(List componentList, String serverBaseURL, boolean detailed) { + if (componentList == null || componentList.isEmpty()) { + return Either.left(new LinkedList<>()); + } + List retResList = new LinkedList<>(); + + for (Component curr : componentList) { + Either resMetaData = convertToSingleAssetMetadata(curr, serverBaseURL, detailed); + if (resMetaData.isRight()) { + return Either.right(resMetaData.right().value()); + } + retResList.add(resMetaData.left().value()); + } + + return Either.left(retResList); + + } + + public Either convertToSingleAssetMetadata(T component, String serverBaseURL, boolean detailed) { + ComponentTypeEnum componentType = component.getComponentType(); + Either resMetaData = convertToMetadata(componentType, serverBaseURL, detailed, component); + + if (resMetaData.isRight()) { + return Either.right(resMetaData.right().value()); + } + else{ + return Either.left(resMetaData.left().value()); + } + + } + + private Either convertToMetadata(ComponentTypeEnum componentType, String serverBaseURL, boolean detailed, Component curr) { + + switch (componentType) { + + case RESOURCE: + + return generateResourceMeatdata(serverBaseURL, detailed, curr); + + case SERVICE: + + return generateServiceMetadata(serverBaseURL, detailed, curr); + + // For future US's that include product + /* + * case PRODUCT: if (component instanceof Product) { List retResList = new LinkedList<>(); for (Component curr : componentList) { retResList.add(convertToProductAssetMetadata((Product) curr, serverBaseURL)); } return + * Either.left(retResList); + */ + default: + + ResponseFormat responseFormat = componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.COMPONENT_INVALID_CATEGORY); + return Either.right(responseFormat); + } + } + + private Either generateResourceMeatdata(String serverBaseURL, boolean detailed, Component curr) { + AssetMetadata metaData; + metaData = createMetadaObject(detailed, curr.getComponentType()); + metaData = convertToResourceMetadata((ResourceAssetMetadata) metaData, (Resource) curr, serverBaseURL, detailed); + + if (detailed) { + Either converted = convertToResourceDetailedMetadata((ResourceAssetDetailedMetadata) metaData, (Resource) curr, serverBaseURL); + if (converted.isRight()) { + ActionStatus storageResponse = componentsUtils.convertFromStorageResponse(converted.right().value(), ComponentTypeEnum.RESOURCE); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(storageResponse); + return Either.right(responseFormat); + } + } + + return Either.left(metaData); + } + + private AssetMetadata createMetadaObject(boolean detailed, ComponentTypeEnum type) { + AssetMetadata metaData = null; + switch (type) { + case SERVICE: + if (!detailed) { + metaData = new ServiceAssetMetadata(); + } else { + metaData = new ServiceAssetDetailedMetadata(); + } + break; + case RESOURCE: + if (!detailed) { + metaData = new ResourceAssetMetadata(); + } else { + metaData = new ResourceAssetDetailedMetadata(); + } + break; + default: + break; + } + return metaData; + } + + private Either generateServiceMetadata(String serverBaseURL, boolean detailed, Component curr) { + AssetMetadata metaData = createMetadaObject(detailed, curr.getComponentType()); + + metaData = convertToServiceAssetMetadata((ServiceAssetMetadata) metaData, (Service) curr, serverBaseURL, detailed); + + if (detailed) { + Either converted = convertToServiceDetailedMetadata((ServiceAssetDetailedMetadata) metaData, (Service) curr, serverBaseURL); + if (converted.isRight()) { + ActionStatus storageResponse = componentsUtils.convertFromStorageResponse(converted.right().value(), ComponentTypeEnum.RESOURCE); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(storageResponse); + return Either.right(responseFormat); + } + } + + return Either.left(metaData); + } + + private U convertToAsset(U asset, T component, String serverBaseURL, boolean detailed) { + asset.setUuid(component.getUUID()); + asset.setInvariantUUID(component.getInvariantUUID()); + asset.setName(component.getName()); + asset.setVersion(component.getVersion()); + if (!detailed) { + asset.setToscaModelURL(serverBaseURL + "/" + component.getUUID() + "/toscaModel"); + } else { + String toscaModelUrl = (new String(serverBaseURL)).replace("metadata", "toscaModel"); + asset.setToscaModelURL(toscaModelUrl); + } + + return asset; + } + + private T convertToResourceMetadata(T assetToPopulate, Resource resource, String serverBaseURL, boolean detailed) { + assetToPopulate = convertToAsset(assetToPopulate, resource, serverBaseURL, detailed); + CategoryDefinition categoryDefinition; + if(resource.getCategories() != null && !resource.getCategories().isEmpty()){ + categoryDefinition = resource.getCategories().iterator().next(); + assetToPopulate.setCategory(categoryDefinition.getName()); + assetToPopulate.setSubCategory(categoryDefinition.getSubcategories().iterator().next().getName()); + } + assetToPopulate.setResourceType(resource.getResourceType().name()); + assetToPopulate.setLifecycleState(resource.getLifecycleState().name()); + assetToPopulate.setLastUpdaterUserId(resource.getLastUpdaterUserId()); + + return (T) assetToPopulate; + } + + private T convertToServiceAssetMetadata(T assetToPopulate, Service service, String serverBaseURL, boolean detailed) { + assetToPopulate = convertToAsset(assetToPopulate, service, serverBaseURL, detailed); + + CategoryDefinition categoryDefinition = service.getCategories().iterator().next(); + + assetToPopulate.setCategory(categoryDefinition.getName()); + assetToPopulate.setLifecycleState(service.getLifecycleState().name()); + assetToPopulate.setLastUpdaterUserId(service.getLastUpdaterUserId()); + assetToPopulate.setDistributionStatus(service.getDistributionStatus().name()); + + return (T) assetToPopulate; + } + + private Either convertToResourceDetailedMetadata(T assetToPopulate, Resource resource, String serverBaseURL) { + + List componentInstances = resource.getComponentInstances(); + + if (componentInstances != null) { + Either, StorageOperationStatus> resourceInstanceMetadata = convertToResourceInstanceMetadata(componentInstances, ComponentTypeEnum.RESOURCE_PARAM_NAME, resource.getUUID()); + if (resourceInstanceMetadata.isRight()) { + return Either.right(resourceInstanceMetadata.right().value()); + } + + assetToPopulate.setResources(resourceInstanceMetadata.left().value()); + } + + Map deploymentArtifacts = resource.getDeploymentArtifacts(); + assetToPopulate = populateResourceWithArtifacts(assetToPopulate, resource, serverBaseURL, deploymentArtifacts); + + assetToPopulate.setLastUpdaterFullName(resource.getLastUpdaterFullName()); + assetToPopulate.setToscaResourceName(resource.getToscaResourceName()); + assetToPopulate.setDescription(resource.getDescription()); + return Either.left(assetToPopulate); + } + + private Either convertToServiceDetailedMetadata(T assetToPopulate, Service service, String serverBaseURL) { + + List componentInstances = service.getComponentInstances(); + + if (componentInstances != null) { + Either, StorageOperationStatus> resourceInstanceMetadata = convertToResourceInstanceMetadata(componentInstances, ComponentTypeEnum.SERVICE_PARAM_NAME, service.getUUID()); + if (resourceInstanceMetadata.isRight()) { + return Either.right(resourceInstanceMetadata.right().value()); + } + + assetToPopulate.setResources(resourceInstanceMetadata.left().value()); + } + + Map deploymentArtifacts = service.getDeploymentArtifacts(); + assetToPopulate = populateServiceWithArtifacts(assetToPopulate, service, deploymentArtifacts); + + assetToPopulate.setLastUpdaterFullName(service.getLastUpdaterFullName()); + + return Either.left(assetToPopulate); + } + + private T populateResourceWithArtifacts(T asset, Resource resource, String serverBaseURL, Map artifacts) { + + List artifactMetaList = populateAssetWithArtifacts(resource, artifacts); + + asset.setArtifacts(artifactMetaList); + + return asset; + } + + private T populateServiceWithArtifacts(T asset, Service service, Map artifacts) { + + List artifactMetaList = populateAssetWithArtifacts(service, artifacts); + + asset.setArtifacts(artifactMetaList); + + return asset; + } + + private List populateAssetWithArtifacts(Component component, Map artifacts) { + List artifactMetaList = new LinkedList<>(); + if (artifacts != null) { + Collection artefactDefList = artifacts.values(); + + for (ArtifactDefinition artifactDefinition : artefactDefList) { + if (artifactDefinition.getEsId() != null && !artifactDefinition.getEsId().isEmpty()) { + ArtifactMetadata convertedArtifactMetadata = convertToArtifactMetadata(artifactDefinition, ComponentTypeEnum.findParamByType(component.getComponentType()), component.getUUID(), null); + artifactMetaList.add(convertedArtifactMetadata); + } + } + } + return artifactMetaList.isEmpty() ? null : artifactMetaList; + } + + private ArtifactMetadata convertToArtifactMetadata(ArtifactDefinition artifact, String componentType, String componentUUID, String resourceInstanceName) { + // /sdc/v1/catalog/{services/resources}/{componentUUID}/artifacts/{artifactUUID} + final String COMPONENT_ARTIFACT_URL = "/sdc/v1/catalog/%s/%s/artifacts/%s"; + + // /sdc/v1/catalog/{services/resources}/{componentUUID}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID} + final String RESOURCE_INSTANCE_ARTIFACT_URL = "/sdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts/%s"; + + ArtifactMetadata metadata = new ArtifactMetadata(); + + metadata.setArtifactName(artifact.getArtifactName()); + metadata.setArtifactType(artifact.getArtifactType()); + + if (resourceInstanceName == null || resourceInstanceName.isEmpty()) { + metadata.setArtifactURL(String.format(COMPONENT_ARTIFACT_URL, componentType, componentUUID, artifact.getArtifactUUID())); + } else { + metadata.setArtifactURL(String.format(RESOURCE_INSTANCE_ARTIFACT_URL, componentType, componentUUID, resourceInstanceName, artifact.getArtifactUUID())); + } + + metadata.setArtifactDescription(artifact.getDescription()); + metadata.setArtifactTimeout(artifact.getTimeout() > 0 ? artifact.getTimeout() : null); + metadata.setArtifactChecksum(artifact.getArtifactChecksum()); + metadata.setArtifactUUID(artifact.getArtifactUUID()); + metadata.setArtifactVersion(artifact.getArtifactVersion()); + metadata.setGeneratedFromUUID(artifact.getGeneratedFromId()); + metadata.setArtifactLabel(artifact.getArtifactLabel()); + metadata.setArtifactGroupType(artifact.getArtifactGroupType().getType()); + return metadata; + } + + private Either, StorageOperationStatus> convertToResourceInstanceMetadata(List componentInstances, String componentType, String componentUUID) { + List retList = new LinkedList<>(); + Map> uuidDuplicatesMap = new HashMap<>(); + + for (ComponentInstance componentInstance : componentInstances) { + ResourceInstanceMetadata metadata = new ResourceInstanceMetadata(); + String componentUid = componentInstance.getComponentUid(); + String invariantUUID, resourceUUID; + + if (!uuidDuplicatesMap.containsKey(componentUid)) { + Either eitherResource = toscaOperationFacade.getToscaElement(componentInstance.getComponentUid()); + if (eitherResource.isRight()) { + log.debug("convertToResourceInstanceMetadata: Failed getting resource with Uid: {}", componentInstance.getComponentUid()); + return Either.right(eitherResource.right().value()); + } else { + final Resource resource = eitherResource.left().value(); + invariantUUID = resource.getInvariantUUID(); + resourceUUID = resource.getUUID(); + ImmutablePair uuidInvariantUUIDPair = new ImmutablePair<>(resourceUUID, invariantUUID); + uuidDuplicatesMap.put(componentUid, uuidInvariantUUIDPair); + } + } else { + invariantUUID = uuidDuplicatesMap.get(componentUid).getRight(); + resourceUUID = uuidDuplicatesMap.get(componentUid).getLeft(); + } + + metadata.setResourceInvariantUUID(invariantUUID); + metadata.setResourceUUID(resourceUUID); + metadata.setResourceInstanceName(componentInstance.getName()); + metadata.setResourceName(componentInstance.getComponentName()); + metadata.setResourceVersion(componentInstance.getComponentVersion()); + metadata.setResoucreType(componentInstance.getOriginType().getValue()); + + if(MapUtils.isNotEmpty(componentInstance.getDeploymentArtifacts())){ + LinkedList artifactMetaList = new LinkedList<>(); + Collection values = componentInstance.getDeploymentArtifacts().values(); + for (ArtifactDefinition artifactDefinition : values) { + ArtifactMetadata converted = convertToArtifactMetadata(artifactDefinition, componentType, componentUUID, componentInstance.getNormalizedName()); + artifactMetaList.add(converted); + } + metadata.setArtifacts(artifactMetaList); + } + retList.add(metadata); + } + return Either.left(retList); + } + + // For future US to support Product + /* + * private ProductAssetMetadata convertToProductAssetMetadata(Product product, String serverBaseURL) { ProductAssetMetadata retProdAsset = new ProductAssetMetadata(); + * + * retProdAsset = convertToAsset(retProdAsset, product, serverBaseURL); retProdAsset.setLifecycleState(product.getLifecycleState().name()); retProdAsset.setLastUpdaterUserId(product.getLastUpdaterUserId()); + * retProdAsset.setActive(product.getIsActive()); retProdAsset.setContacts(product.getContacts()); + * + * List categories = product.getCategories(); List categoryMetadataList = new LinkedList<>(); + * + * if (categories == null || categories.isEmpty()) { return retProdAsset; } else { for (CategoryDefinition categoryDefinition : categories) { String categoryName = categoryDefinition.getName(); List subcategories = + * categoryDefinition.getSubcategories(); for (SubCategoryDefinition subCategoryDefinition : subcategories) { String subCategoryName = subCategoryDefinition.getName(); List groups = product.getGroups(); for (GroupDefinition + * groupDefinition : groups) { String groupName = groupDefinition.getName(); categoryMetadataList.add(new ProductCategoryGroupMetadata(categoryName, subCategoryName, groupName)); } } } retProdAsset.setProductGroupings(categoryMetadataList); + * return retProdAsset; } } + */ +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetMetadataConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetMetadataConverter.java deleted file mode 100644 index 2c7de7032c..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetMetadataConverter.java +++ /dev/null @@ -1,392 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.externalapi.servlet; - -import java.util.Collection; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import org.apache.commons.collections.MapUtils; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.distribution.servlet.DistributionCatalogServlet; -import org.openecomp.sdc.be.externalapi.servlet.representation.ArtifactMetadata; -import org.openecomp.sdc.be.externalapi.servlet.representation.AssetMetadata; -import org.openecomp.sdc.be.externalapi.servlet.representation.ResourceAssetDetailedMetadata; -import org.openecomp.sdc.be.externalapi.servlet.representation.ResourceAssetMetadata; -import org.openecomp.sdc.be.externalapi.servlet.representation.ResourceInstanceMetadata; -import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceAssetDetailedMetadata; -import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceAssetMetadata; -import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.model.category.CategoryDefinition; -import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.ResourceOperation; -import org.openecomp.sdc.exception.ResponseFormat; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; - -import fj.data.Either; - -@org.springframework.stereotype.Component("asset-metadata-utils") -public class AssetMetadataConverter { - private static Logger log = LoggerFactory.getLogger(DistributionCatalogServlet.class.getName()); - - @Autowired - private ComponentsUtils componentsUtils; - - @Autowired - protected ToscaOperationFacade toscaOperationFacade; - - /* - * Relative asset’s URL. Should be used in REST GET API to download the asset’s CSAR. https://{serverBaseURL}/{csarPath} can be obtained from (HttpServletRequest)request.getServerName() - */ - public Either, ResponseFormat> convertToAssetMetadata(List componentList, String serverBaseURL, boolean detailed) { - if (componentList == null || componentList.isEmpty()) { - return Either.left(new LinkedList<>()); - } - List retResList = new LinkedList<>(); - - for (Component curr : componentList) { - Either resMetaData = convertToSingleAssetMetadata(curr, serverBaseURL, detailed); - if (resMetaData.isRight()) { - return Either.right(resMetaData.right().value()); - } - retResList.add(resMetaData.left().value()); - } - - return Either.left(retResList); - - } - - public Either convertToSingleAssetMetadata(T component, String serverBaseURL, boolean detailed) { - ComponentTypeEnum componentType = component.getComponentType(); - Either resMetaData = convertToMetadata(componentType, serverBaseURL, detailed, component); - - if (resMetaData.isRight()) { - return Either.right(resMetaData.right().value()); - } - else{ - return Either.left(resMetaData.left().value()); - } - - } - - private Either convertToMetadata(ComponentTypeEnum componentType, String serverBaseURL, boolean detailed, Component curr) { - - switch (componentType) { - - case RESOURCE: - - return generateResourceMeatdata(serverBaseURL, detailed, curr); - - case SERVICE: - - return generateServiceMetadata(serverBaseURL, detailed, curr); - - // For future US's that include product - /* - * case PRODUCT: if (component instanceof Product) { List retResList = new LinkedList<>(); for (Component curr : componentList) { retResList.add(convertToProductAssetMetadata((Product) curr, serverBaseURL)); } return - * Either.left(retResList); - */ - default: - - ResponseFormat responseFormat = componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.COMPONENT_INVALID_CATEGORY); - return Either.right(responseFormat); - } - } - - private Either generateResourceMeatdata(String serverBaseURL, boolean detailed, Component curr) { - AssetMetadata metaData; - metaData = createMetadaObject(detailed, curr.getComponentType()); - metaData = convertToResourceMetadata((ResourceAssetMetadata) metaData, (Resource) curr, serverBaseURL, detailed); - - if (detailed) { - Either converted = convertToResourceDetailedMetadata((ResourceAssetDetailedMetadata) metaData, (Resource) curr, serverBaseURL); - if (converted.isRight()) { - ActionStatus storageResponse = componentsUtils.convertFromStorageResponse(converted.right().value(), ComponentTypeEnum.RESOURCE); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(storageResponse); - return Either.right(responseFormat); - } - } - - return Either.left(metaData); - } - - private AssetMetadata createMetadaObject(boolean detailed, ComponentTypeEnum type) { - AssetMetadata metaData = null; - switch (type) { - case SERVICE: - if (!detailed) { - metaData = new ServiceAssetMetadata(); - } else { - metaData = new ServiceAssetDetailedMetadata(); - } - break; - case RESOURCE: - if (!detailed) { - metaData = new ResourceAssetMetadata(); - } else { - metaData = new ResourceAssetDetailedMetadata(); - } - break; - default: - break; - } - return metaData; - } - - private Either generateServiceMetadata(String serverBaseURL, boolean detailed, Component curr) { - AssetMetadata metaData = createMetadaObject(detailed, curr.getComponentType()); - - metaData = convertToServiceAssetMetadata((ServiceAssetMetadata) metaData, (Service) curr, serverBaseURL, detailed); - - if (detailed) { - Either converted = convertToServiceDetailedMetadata((ServiceAssetDetailedMetadata) metaData, (Service) curr, serverBaseURL); - if (converted.isRight()) { - ActionStatus storageResponse = componentsUtils.convertFromStorageResponse(converted.right().value(), ComponentTypeEnum.RESOURCE); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(storageResponse); - return Either.right(responseFormat); - } - } - - return Either.left(metaData); - } - - private U convertToAsset(U asset, T component, String serverBaseURL, boolean detailed) { - asset.setUuid(component.getUUID()); - asset.setInvariantUUID(component.getInvariantUUID()); - asset.setName(component.getName()); - asset.setVersion(component.getVersion()); - if (!detailed) { - asset.setToscaModelURL(serverBaseURL + "/" + component.getUUID() + "/toscaModel"); - } else { - String toscaModelUrl = (new String(serverBaseURL)).replace("metadata", "toscaModel"); - asset.setToscaModelURL(toscaModelUrl); - } - - return asset; - } - - private T convertToResourceMetadata(T assetToPopulate, Resource resource, String serverBaseURL, boolean detailed) { - assetToPopulate = convertToAsset(assetToPopulate, resource, serverBaseURL, detailed); - CategoryDefinition categoryDefinition; - if(resource.getCategories() != null && !resource.getCategories().isEmpty()){ - categoryDefinition = resource.getCategories().iterator().next(); - assetToPopulate.setCategory(categoryDefinition.getName()); - assetToPopulate.setSubCategory(categoryDefinition.getSubcategories().iterator().next().getName()); - } - assetToPopulate.setResourceType(resource.getResourceType().name()); - assetToPopulate.setLifecycleState(resource.getLifecycleState().name()); - assetToPopulate.setLastUpdaterUserId(resource.getLastUpdaterUserId()); - - return (T) assetToPopulate; - } - - private T convertToServiceAssetMetadata(T assetToPopulate, Service service, String serverBaseURL, boolean detailed) { - assetToPopulate = convertToAsset(assetToPopulate, service, serverBaseURL, detailed); - - CategoryDefinition categoryDefinition = service.getCategories().iterator().next(); - - assetToPopulate.setCategory(categoryDefinition.getName()); - assetToPopulate.setLifecycleState(service.getLifecycleState().name()); - assetToPopulate.setLastUpdaterUserId(service.getLastUpdaterUserId()); - assetToPopulate.setDistributionStatus(service.getDistributionStatus().name()); - - return (T) assetToPopulate; - } - - private Either convertToResourceDetailedMetadata(T assetToPopulate, Resource resource, String serverBaseURL) { - - List componentInstances = resource.getComponentInstances(); - - if (componentInstances != null) { - Either, StorageOperationStatus> resourceInstanceMetadata = convertToResourceInstanceMetadata(componentInstances, ComponentTypeEnum.RESOURCE_PARAM_NAME, resource.getUUID()); - if (resourceInstanceMetadata.isRight()) { - return Either.right(resourceInstanceMetadata.right().value()); - } - - assetToPopulate.setResources(resourceInstanceMetadata.left().value()); - } - - Map deploymentArtifacts = resource.getDeploymentArtifacts(); - assetToPopulate = populateResourceWithArtifacts(assetToPopulate, resource, serverBaseURL, deploymentArtifacts); - - assetToPopulate.setLastUpdaterFullName(resource.getLastUpdaterFullName()); - assetToPopulate.setToscaResourceName(resource.getToscaResourceName()); - assetToPopulate.setDescription(resource.getDescription()); - return Either.left(assetToPopulate); - } - - private Either convertToServiceDetailedMetadata(T assetToPopulate, Service service, String serverBaseURL) { - - List componentInstances = service.getComponentInstances(); - - if (componentInstances != null) { - Either, StorageOperationStatus> resourceInstanceMetadata = convertToResourceInstanceMetadata(componentInstances, ComponentTypeEnum.SERVICE_PARAM_NAME, service.getUUID()); - if (resourceInstanceMetadata.isRight()) { - return Either.right(resourceInstanceMetadata.right().value()); - } - - assetToPopulate.setResources(resourceInstanceMetadata.left().value()); - } - - Map deploymentArtifacts = service.getDeploymentArtifacts(); - assetToPopulate = populateServiceWithArtifacts(assetToPopulate, service, deploymentArtifacts); - - assetToPopulate.setLastUpdaterFullName(service.getLastUpdaterFullName()); - - return Either.left(assetToPopulate); - } - - private T populateResourceWithArtifacts(T asset, Resource resource, String serverBaseURL, Map artifacts) { - - List artifactMetaList = populateAssetWithArtifacts(resource, artifacts); - - asset.setArtifacts(artifactMetaList); - - return asset; - } - - private T populateServiceWithArtifacts(T asset, Service service, Map artifacts) { - - List artifactMetaList = populateAssetWithArtifacts(service, artifacts); - - asset.setArtifacts(artifactMetaList); - - return asset; - } - - private List populateAssetWithArtifacts(Component component, Map artifacts) { - List artifactMetaList = new LinkedList<>(); - if (artifacts != null) { - Collection artefactDefList = artifacts.values(); - - for (ArtifactDefinition artifactDefinition : artefactDefList) { - if (artifactDefinition.getEsId() != null && !artifactDefinition.getEsId().isEmpty()) { - ArtifactMetadata convertedArtifactMetadata = convertToArtifactMetadata(artifactDefinition, ComponentTypeEnum.findParamByType(component.getComponentType()), component.getUUID(), null); - artifactMetaList.add(convertedArtifactMetadata); - } - } - } - return artifactMetaList.isEmpty() ? null : artifactMetaList; - } - - private ArtifactMetadata convertToArtifactMetadata(ArtifactDefinition artifact, String componentType, String componentUUID, String resourceInstanceName) { - // /sdc/v1/catalog/{services/resources}/{componentUUID}/artifacts/{artifactUUID} - final String COMPONENT_ARTIFACT_URL = "/sdc/v1/catalog/%s/%s/artifacts/%s"; - - // /sdc/v1/catalog/{services/resources}/{componentUUID}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID} - final String RESOURCE_INSTANCE_ARTIFACT_URL = "/sdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts/%s"; - - ArtifactMetadata metadata = new ArtifactMetadata(); - - metadata.setArtifactName(artifact.getArtifactName()); - metadata.setArtifactType(artifact.getArtifactType()); - - if (resourceInstanceName == null || resourceInstanceName.isEmpty()) { - metadata.setArtifactURL(String.format(COMPONENT_ARTIFACT_URL, componentType, componentUUID, artifact.getArtifactUUID())); - } else { - metadata.setArtifactURL(String.format(RESOURCE_INSTANCE_ARTIFACT_URL, componentType, componentUUID, resourceInstanceName, artifact.getArtifactUUID())); - } - - metadata.setArtifactDescription(artifact.getDescription()); - metadata.setArtifactTimeout(artifact.getTimeout() > 0 ? artifact.getTimeout() : null); - metadata.setArtifactChecksum(artifact.getArtifactChecksum()); - metadata.setArtifactUUID(artifact.getArtifactUUID()); - metadata.setArtifactVersion(artifact.getArtifactVersion()); - metadata.setGeneratedFromUUID(artifact.getGeneratedFromId()); - metadata.setArtifactLabel(artifact.getArtifactLabel()); - metadata.setArtifactGroupType(artifact.getArtifactGroupType().getType()); - return metadata; - } - - private Either, StorageOperationStatus> convertToResourceInstanceMetadata(List componentInstances, String componentType, String componentUUID) { - List retList = new LinkedList<>(); - Map> uuidDuplicatesMap = new HashMap<>(); - - for (ComponentInstance componentInstance : componentInstances) { - ResourceInstanceMetadata metadata = new ResourceInstanceMetadata(); - String componentUid = componentInstance.getComponentUid(); - String invariantUUID, resourceUUID; - - if (!uuidDuplicatesMap.containsKey(componentUid)) { - Either eitherResource = toscaOperationFacade.getToscaElement(componentInstance.getComponentUid()); - if (eitherResource.isRight()) { - log.debug("convertToResourceInstanceMetadata: Failed getting resource with Uid: {}", componentInstance.getComponentUid()); - return Either.right(eitherResource.right().value()); - } else { - final Resource resource = eitherResource.left().value(); - invariantUUID = resource.getInvariantUUID(); - resourceUUID = resource.getUUID(); - ImmutablePair uuidInvariantUUIDPair = new ImmutablePair<>(resourceUUID, invariantUUID); - uuidDuplicatesMap.put(componentUid, uuidInvariantUUIDPair); - } - } else { - invariantUUID = uuidDuplicatesMap.get(componentUid).getRight(); - resourceUUID = uuidDuplicatesMap.get(componentUid).getLeft(); - } - - metadata.setResourceInvariantUUID(invariantUUID); - metadata.setResourceUUID(resourceUUID); - metadata.setResourceInstanceName(componentInstance.getName()); - metadata.setResourceName(componentInstance.getComponentName()); - metadata.setResourceVersion(componentInstance.getComponentVersion()); - metadata.setResoucreType(componentInstance.getOriginType().getValue()); - - if(MapUtils.isNotEmpty(componentInstance.getDeploymentArtifacts())){ - LinkedList artifactMetaList = new LinkedList<>(); - Collection values = componentInstance.getDeploymentArtifacts().values(); - for (ArtifactDefinition artifactDefinition : values) { - ArtifactMetadata converted = convertToArtifactMetadata(artifactDefinition, componentType, componentUUID, componentInstance.getNormalizedName()); - artifactMetaList.add(converted); - } - metadata.setArtifacts(artifactMetaList); - } - retList.add(metadata); - } - return Either.left(retList); - } - - // For future US to support Product - /* - * private ProductAssetMetadata convertToProductAssetMetadata(Product product, String serverBaseURL) { ProductAssetMetadata retProdAsset = new ProductAssetMetadata(); - * - * retProdAsset = convertToAsset(retProdAsset, product, serverBaseURL); retProdAsset.setLifecycleState(product.getLifecycleState().name()); retProdAsset.setLastUpdaterUserId(product.getLastUpdaterUserId()); - * retProdAsset.setActive(product.getIsActive()); retProdAsset.setContacts(product.getContacts()); - * - * List categories = product.getCategories(); List categoryMetadataList = new LinkedList<>(); - * - * if (categories == null || categories.isEmpty()) { return retProdAsset; } else { for (CategoryDefinition categoryDefinition : categories) { String categoryName = categoryDefinition.getName(); List subcategories = - * categoryDefinition.getSubcategories(); for (SubCategoryDefinition subCategoryDefinition : subcategories) { String subCategoryName = subCategoryDefinition.getName(); List groups = product.getGroups(); for (GroupDefinition - * groupDefinition : groups) { String groupName = groupDefinition.getName(); categoryMetadataList.add(new ProductCategoryGroupMetadata(categoryName, subCategoryName, groupName)); } } } retProdAsset.setProductGroupings(categoryMetadataList); - * return retProdAsset; } } - */ -} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServlet.java index 552ad163ec..b0947c67f9 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServlet.java @@ -68,6 +68,7 @@ import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.ecomp.converters.AssetMetadataConverter; import org.openecomp.sdc.be.externalapi.servlet.representation.AssetMetadata; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ComponentsUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ComponentsUtils.java index ea2582cd1b..a6415dc9b9 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ComponentsUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ComponentsUtils.java @@ -37,12 +37,14 @@ import org.codehaus.jackson.map.JsonDeserializer; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.module.SimpleModule; import org.openecomp.sdc.be.auditing.api.IAuditingManager; +import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; import org.openecomp.sdc.be.components.impl.ResponseFormatManager; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.graph.datatype.AdditionalInformationEnum; import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.CapabilityTypeDefinition; @@ -1254,6 +1256,31 @@ public class ComponentsUtils { log.debug("convert storage response {} to action response {}", storageResponse.name(), responseEnum.name()); return responseEnum; } + + public ActionStatus convertFromResultStatusEnum(ResultStatusEnum resultStatus, JsonPresentationFields elementType) { + ActionStatus responseEnum = ActionStatus.GENERAL_ERROR; + switch (resultStatus) { + case OK: + responseEnum = ActionStatus.OK; + break; + case ELEMENT_NOT_FOUND: + if(elementType!= null && elementType == JsonPresentationFields.PROPERTY){ + responseEnum = ActionStatus.PROPERTY_NOT_FOUND; + } + break; + case INVALID_PROPERTY_DEFAULT_VALUE: + case INVALID_PROPERTY_TYPE: + case INVALID_PROPERTY_VALUE: + case INVALID_PROPERTY_NAME: + case MISSING_ENTRY_SCHEMA_TYPE: + responseEnum = ActionStatus.INVALID_PROPERTY; + break; + default: + responseEnum = ActionStatus.GENERAL_ERROR; + break; + } + return responseEnum; + } public ResponseFormat getResponseFormatAdditionalProperty(ActionStatus actionStatus, AdditionalInfoParameterInfo additionalInfoParameterInfo, NodeTypeEnum nodeType, AdditionalInformationEnum labelOrValue) { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java b/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java index 38629ab7a1..436b2319e9 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java @@ -29,11 +29,7 @@ import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; -import org.openecomp.portalsdk.core.onboarding.ueb.UebException; -import org.openecomp.portalsdk.core.onboarding.ueb.UebManager; -import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.impl.DownloadArtifactLogic; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.operations.api.IResourceOperation; @@ -49,9 +45,7 @@ public class BEAppContextListener extends AppContextListener implements ServletC private static final String MANIFEST_FILE_NAME = "/META-INF/MANIFEST.MF"; private static Logger log = LoggerFactory.getLogger(BEAppContextListener.class.getName()); - - private static UebManager uebManager = null; - + public void contextInitialized(ServletContextEvent context) { super.contextInitialized(context); @@ -73,34 +67,10 @@ public class BEAppContextListener extends AppContextListener implements ServletC BeMonitoringService bms = new BeMonitoringService(context.getServletContext()); bms.start(configurationManager.getConfiguration().getSystemMonitoring().getProbeIntervalInSeconds(15)); - initUebManager(); - log.debug("After executing {}", this.getClass()); } - - private void initUebManager() { - try { - if (uebManager == null) { - uebManager = UebManager.getInstance(); - uebManager.initListener(null); - } - } catch (UebException ex) { - log.debug("Failed to initialize UebManager", ex); - BeEcompErrorManager.getInstance().logInternalConnectionError("InitUebManager", "Failed to initialize listener of UebManager", ErrorSeverity.ERROR); - } - log.debug("After init listener of UebManager"); - } - - public void contextDestroyed(ServletContextEvent context) { - if (uebManager != null) { - uebManager.shutdown(); - uebManager = null; - } - super.contextDestroyed(context); - - } - + private IResourceOperation getResourceOperationManager(Class clazz, WebApplicationContext webContext) { return webContext.getBean(clazz); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AbstractValidationsServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AbstractValidationsServlet.java index d8f834c970..6b16e71e82 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AbstractValidationsServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AbstractValidationsServlet.java @@ -278,7 +278,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { } else { if (!resourceAuthorityEnum.isBackEndImport()) { isValid = resourceInfoObject.getPayloadName() != null && !resourceInfoObject.getPayloadName().isEmpty(); - //Tal only resource name is checked + //only resource name is checked } else { isValid = true; } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AttributeServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AttributeServlet.java index c7bc481119..0c5961daeb 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AttributeServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AttributeServlet.java @@ -38,7 +38,7 @@ import javax.ws.rs.core.Response; import org.openecomp.sdc.be.components.impl.AttributeBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.model.AttributeDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.datastructure.Wrapper; @@ -96,13 +96,13 @@ public class AttributeServlet extends AbstractValidationsServlet { try { Wrapper errorWrapper = new Wrapper<>(); - Wrapper attributesWrapper = new Wrapper<>(); + Wrapper attributesWrapper = new Wrapper<>(); // convert json to AttributeDefinition buildAttributeFromString(data, attributesWrapper, errorWrapper); if (errorWrapper.isEmpty()) { AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class); - Either createAttribute = businessLogic.createAttribute(resourceId, attributesWrapper.getInnerElement(), userId); + Either createAttribute = businessLogic.createAttribute(resourceId, attributesWrapper.getInnerElement(), userId); if (createAttribute.isRight()) { errorWrapper.setInnerElement(createAttribute.right().value()); } else { @@ -115,7 +115,7 @@ public class AttributeServlet extends AbstractValidationsServlet { log.info("Failed to create Attribute. Reason - ", errorWrapper.getInnerElement()); response = buildErrorResponse(errorWrapper.getInnerElement()); } else { - AttributeDefinition createdAttDef = attributesWrapper.getInnerElement(); + PropertyDefinition createdAttDef = attributesWrapper.getInnerElement(); log.debug("Attribute {} created successfully with id {}", createdAttDef.getName(), createdAttDef.getUniqueId()); ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED); response = buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(createdAttDef)); @@ -165,14 +165,14 @@ public class AttributeServlet extends AbstractValidationsServlet { try { // convert json to PropertyDefinition Wrapper errorWrapper = new Wrapper<>(); - Wrapper attributesWrapper = new Wrapper<>(); + Wrapper attributesWrapper = new Wrapper<>(); // convert json to AttributeDefinition buildAttributeFromString(data, attributesWrapper, errorWrapper); if (errorWrapper.isEmpty()) { AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class); - Either eitherUpdateAttribute = businessLogic.updateAttribute(resourceId, attributeId, attributesWrapper.getInnerElement(), userId); + Either eitherUpdateAttribute = businessLogic.updateAttribute(resourceId, attributeId, attributesWrapper.getInnerElement(), userId); // update property if (eitherUpdateAttribute.isRight()) { errorWrapper.setInnerElement(eitherUpdateAttribute.right().value()); @@ -186,7 +186,7 @@ public class AttributeServlet extends AbstractValidationsServlet { log.info("Failed to update Attribute. Reason - ", errorWrapper.getInnerElement()); response = buildErrorResponse(errorWrapper.getInnerElement()); } else { - AttributeDefinition updatedAttribute = attributesWrapper.getInnerElement(); + PropertyDefinition updatedAttribute = attributesWrapper.getInnerElement(); log.debug("Attribute id {} updated successfully ", updatedAttribute.getUniqueId()); ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); response = buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(updatedAttribute)); @@ -232,12 +232,12 @@ public class AttributeServlet extends AbstractValidationsServlet { // delete the property AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class); - Either eitherAttribute = businessLogic.deleteAttribute(resourceId, attributeId, userId); + Either eitherAttribute = businessLogic.deleteAttribute(resourceId, attributeId, userId); if (eitherAttribute.isRight()) { log.debug("Failed to delete Attribute. Reason - ", eitherAttribute.right().value()); return buildErrorResponse(eitherAttribute.right().value()); } - AttributeDefinition attributeDefinition = eitherAttribute.left().value(); + PropertyDefinition attributeDefinition = eitherAttribute.left().value(); String name = attributeDefinition.getName(); log.debug("Attribute {} deleted successfully with id {}", name, attributeDefinition.getUniqueId()); @@ -253,11 +253,11 @@ public class AttributeServlet extends AbstractValidationsServlet { } } - private void buildAttributeFromString(String data, Wrapper attributesWrapper, Wrapper errorWrapper) { + private void buildAttributeFromString(String data, Wrapper attributesWrapper, Wrapper errorWrapper) { try { Gson gson = new GsonBuilder().setPrettyPrinting().create(); - final AttributeDefinition attribute = gson.fromJson(data, AttributeDefinition.class); + final PropertyDefinition attribute = gson.fromJson(data, PropertyDefinition.class); if (attribute == null) { log.info("Attribute content is invalid - {}", data); ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java index 2d5402f709..4278378bbc 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java @@ -49,7 +49,7 @@ import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.api.IElementDAO; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.externalapi.servlet.AssetMetadataConverter; +import org.openecomp.sdc.be.ecomp.converters.AssetMetadataConverter; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.User; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java index 6a7ecbb5fe..e509078c5c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java @@ -51,7 +51,6 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.info.CreateAndAssotiateInfo; import org.openecomp.sdc.be.info.GroupDefinitionInfo; import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceAttribute; import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.InputDefinition; @@ -191,7 +190,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { } - // TODO Tal New Multiple Instance API @POST @Path("/{containerComponentType}/{componentId}/resourceInstance/multipleComponentInstance") @Consumes(MediaType.APPLICATION_JSON) @@ -618,13 +616,13 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { Wrapper errorWrapper = new Wrapper<>(); Wrapper dataWrapper = new Wrapper<>(); - Wrapper attributeWrapper = new Wrapper<>(); + Wrapper attributeWrapper = new Wrapper<>(); Wrapper blWrapper = new Wrapper<>(); validateInputStream(request, dataWrapper, errorWrapper); if (errorWrapper.isEmpty()) { - validateClassParse(dataWrapper.getInnerElement(), attributeWrapper, () -> ComponentInstanceAttribute.class, errorWrapper); + validateClassParse(dataWrapper.getInnerElement(), attributeWrapper, () -> ComponentInstanceProperty.class, errorWrapper); } if (errorWrapper.isEmpty()) { @@ -635,7 +633,7 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { ComponentInstanceBusinessLogic componentInstanceLogic = blWrapper.getInnerElement(); ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); log.debug("Start handle request of ComponentInstanceAttribute. Received attribute is {}", attributeWrapper.getInnerElement()); - Either eitherAttribute = componentInstanceLogic.createOrUpdateAttributeValue(componentTypeEnum, componentId, componentInstanceId, attributeWrapper.getInnerElement(), userId); + Either eitherAttribute = componentInstanceLogic.createOrUpdateAttributeValue(componentTypeEnum, componentId, componentInstanceId, attributeWrapper.getInnerElement(), userId); if (eitherAttribute.isRight()) { errorWrapper.setInnerElement(eitherAttribute.right().value()); } else { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentServlet.java index b28700ace4..3a40e9626e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentServlet.java @@ -87,12 +87,12 @@ public class ComponentServlet extends BeGenericServlet { private static Logger log = LoggerFactory.getLogger(ComponentServlet.class.getName()); @GET - @Path("/{componentType}/{componentId}/conformanceLevelValidation") + @Path("/{componentType}/{componentUuid}/conformanceLevelValidation") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Validate Component Conformance Level", httpMethod = "GET", notes = "Returns the result according to conformance level in BE config", response = Resource.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) - public Response conformanceLevelValidation(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request, + public Response conformanceLevelValidation(@PathParam("componentType") final String componentType, @PathParam("componentUuid") final String componentUuid, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { Response response; ServletContext context = request.getSession().getServletContext(); @@ -103,7 +103,7 @@ public class ComponentServlet extends BeGenericServlet { ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); if (componentTypeEnum != null) { ComponentBusinessLogic compBL = getComponentBL(componentTypeEnum, context); - Either eitherConformanceLevel = compBL.validateConformanceLevel(componentId, componentTypeEnum, userId); + Either eitherConformanceLevel = compBL.validateConformanceLevel(componentUuid, componentTypeEnum, userId); if (eitherConformanceLevel.isRight()) { response = buildErrorResponse(eitherConformanceLevel.right().value()); } else { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/LifecycleServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/LifecycleServlet.java index 019a6ba8fd..d8b0a0ec39 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/LifecycleServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/LifecycleServlet.java @@ -39,11 +39,13 @@ import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoBase; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.LifeCycleTransitionEnum; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.ui.model.UiComponentMetadata; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.config.EcompErrorName; import org.openecomp.sdc.exception.ResponseFormat; @@ -138,7 +140,8 @@ public class LifecycleServlet extends BeGenericServlet { } log.debug("change state successful !!!"); - Object value = RepresentationUtils.toRepresentation(actionResponse.left().value()); + UiComponentMetadata componentMetatdata = UiComponentDataConverter.convertToUiComponentMetadata(actionResponse.left().value()); + Object value = RepresentationUtils.toRepresentation(componentMetatdata); response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), value); return response; } else { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/UserAdminServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/UserAdminServlet.java index a477bcf4fb..d1e3d02907 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/UserAdminServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/UserAdminServlet.java @@ -43,7 +43,6 @@ import javax.ws.rs.core.Response; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.model.FunctionalMenuInfo; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.user.UserBusinessLogic; @@ -474,41 +473,4 @@ public class UserAdminServlet extends BeGenericServlet { return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } } - - @GET - @Path("/{userId}/functionalmenu") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "retrieve user details", httpMethod = "GET", notes = "Returns user details according to userId", response = User.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns user Ok"), @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"), - @ApiResponse(code = 500, message = "Internal Server Error") }) - public Response getFunctionalMenu(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String userId, @Context final HttpServletRequest request) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}", url); - - UserBusinessLogic userAdminManager = getUserAdminManager(request.getSession().getServletContext()); - - try { - Either functionalMenuResp = userAdminManager.getFunctionalMenu(userId); - - if (functionalMenuResp.isRight()) { - return buildErrorResponse(getComponentsUtils().getResponseFormatByUserId(functionalMenuResp.right().value(), userId)); - } else { - FunctionalMenuInfo functionalMenuInfo = functionalMenuResp.left().value(); - if (functionalMenuInfo != null && functionalMenuInfo.getFunctionalMenu() != null) { - log.debug("Functional menu fetched is {}", functionalMenuInfo.getFunctionalMenu()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), functionalMenuInfo.getFunctionalMenu()); - } else { - log.debug("Functional menu is null"); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get User"); - log.debug("get user failed with unexpected error: {}", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java index 3c0c80666c..b18cbc9adc 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java @@ -20,16 +20,12 @@ package org.openecomp.sdc.be.tosca; -import java.io.File; +import java.io.BufferedOutputStream; +import java.io.ByteArrayInputStream; import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.EnumMap; -import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; @@ -41,13 +37,11 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.zip.ZipEntry; -import java.util.zip.ZipException; -import java.util.zip.ZipFile; +import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.digest.DigestUtils; -import org.apache.commons.io.IOUtils; import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.commons.lang.WordUtils; import org.apache.commons.lang3.tuple.ImmutablePair; @@ -79,7 +73,7 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.LifecycleOperation; import org.openecomp.sdc.be.resources.data.ESArtifactData; -import org.openecomp.sdc.be.resources.data.ESSdcSchemaFilesData; +import org.openecomp.sdc.be.resources.data.SdcSchemaFilesData; import org.openecomp.sdc.be.tosca.model.ToscaTemplate; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.api.ArtifactTypeEnum; @@ -143,8 +137,9 @@ public class CsarUtils { private static final String TOSCA_META_PATH_FILE_NAME = "TOSCA-Metadata/TOSCA.meta"; private static final String TOSCA_META_VERSION = "1.0"; private static final String CSAR_VERSION = "1.1"; - - public static final String VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS_PATH + ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + "([\\w\\_\\-\\.\\s]+)(/)([\\w\\_\\-\\.\\s]+)(/)([\\w\\_\\-\\.\\s\\/]+)"; + private static String versionFirstThreeOctates; + + public static final String VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS_PATH + ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + "([\\d\\w\\_\\-\\.\\s]+)(/)([\\d\\w\\_\\-\\.\\s]+)(/)([\\d\\w\\_\\-\\.\\s\\/]+)"; public static final String VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS_PATH + // Artifact Group (i.e Deployment/Informational) @@ -155,6 +150,16 @@ public class CsarUtils { "([\\w\\_\\-\\.\\s]+)"; public static final String ARTIFACT_CREATED_FROM_CSAR = "Artifact created from csar"; + public CsarUtils() { + if(SDC_VERSION != null && !SDC_VERSION.isEmpty()){ + Matcher matcher = Pattern.compile("(?!\\.)(\\d+(\\.\\d+)+)(?![\\d\\.])").matcher(SDC_VERSION); + matcher.find(); + versionFirstThreeOctates = matcher.group(0); + } else { + versionFirstThreeOctates = ""; + } + } + /** * * @param component @@ -301,39 +306,40 @@ public class CsarUtils { } //add inner components to CSAR - innerComponentsCache.forEach((childUid, innerComponentTriple) -> { - Component innerComponent = innerComponentTriple.getRight(); - String icFileName = innerComponentTriple.getMiddle(); - - try { - //add component to zip - Either entryData = getEntryData(innerComponentTriple.getLeft(), innerComponent); - byte[] content = entryData.left().value(); - zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + icFileName)); - zip.write(content); - - } catch (IOException e) { + + for (Entry> innerComponentTripleEntry : innerComponentsCache.entrySet()) { + + ImmutableTriple innerComponentTriple = innerComponentTripleEntry.getValue(); - } + Component innerComponent = innerComponentTriple.getRight(); + String icFileName = innerComponentTriple.getMiddle(); - //add component interface to zip - if(!ToscaUtils.isAtomicType(innerComponent)) { - writeComponentInterface(innerComponent, zip, icFileName); - } - }); + // add component to zip + Either entryData = getEntryData(innerComponentTriple.getLeft(), innerComponent); + byte[] content = entryData.left().value(); + zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + icFileName)); + zip.write(content); + + // add component interface to zip + if (!ToscaUtils.isAtomicType(innerComponent)) { + writeComponentInterface(innerComponent, zip, icFileName); + } + } } - /*Either latestSchemaFilesFromCassandra = getLatestSchemaFilesFromCassandra(); + //retrieve SDC.zip from Cassandra + Either latestSchemaFilesFromCassandra = getLatestSchemaFilesFromCassandra(); if(latestSchemaFilesFromCassandra.isRight()){ - return null; - }*/ + log.error("Error retrieving SDC Schema files from cassandra" ); + return Either.right(latestSchemaFilesFromCassandra.right().value()); + } - //TODO Tal G this is quick solution until Cassandra US is alligned - Either addSchemaFilesFromConfig = addSchemaFilesFromConfig(zip); + //add files from retireved SDC.zip to Definitions folder in CSAR + Either addSchemaFilesFromCassandra = addSchemaFilesFromCassandra(zip, latestSchemaFilesFromCassandra.left().value()); - if(addSchemaFilesFromConfig.isRight()){ - return addSchemaFilesFromConfig; + if(addSchemaFilesFromCassandra.isRight()){ + return addSchemaFilesFromCassandra; } // Artifact Generation @@ -371,36 +377,47 @@ public class CsarUtils { return writeAllFilesToScar(component, collectedComponentCsarDefinition.left().value(), zip, isInCertificationRequest); } - - private Either addSchemaFilesFromConfig(ZipOutputStream zip) throws ZipException, IOException { - final String pathAndFile = "config/SDC.zip"; + + private Either addSchemaFilesFromCassandra(ZipOutputStream zip, byte[] schemaFileZip){ - File file = new File(pathAndFile); - if(!file.exists()){ - log.debug("SDC.zip schema files archive not found"); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } + final int initSize = 2048; - try(ZipFile zipFile = new ZipFile(new File(pathAndFile));){ - Enumeration entries = zipFile.entries(); + log.debug("Starting coppy from Schema file zip to CSAR zip"); + + try (ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(schemaFileZip)); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + BufferedOutputStream bos = new BufferedOutputStream(out, initSize);) { - while(entries.hasMoreElements()){ - ZipEntry nextElement = entries.nextElement(); - InputStream inputStream = zipFile.getInputStream(nextElement); - byte[] byteArray = IOUtils.toByteArray(inputStream); - - zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + nextElement.getName())); - zip.write(byteArray); + ZipEntry entry = null; + + while ((entry = zipStream.getNextEntry()) != null) { + + String entryName = entry.getName(); + int readSize = initSize; + byte[] entryData = new byte[initSize]; + + while ((readSize = zipStream.read(entryData, 0, readSize)) != -1) { + bos.write(entryData, 0, readSize); + } + + bos.flush(); + out.flush(); + zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + entryName)); + zip.write(out.toByteArray()); + zip.flush(); + out.reset(); } - zipFile.close(); - }catch (Exception e) { - log.debug("Error in writing SDC.zip schema files to CSAR"); + } catch (IOException e) { + log.error("Error while writing the SDC schema file to the CSAR {}", e); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } + log.debug("Finished coppy from Schema file zip to CSAR zip"); + return Either.left(zip); } + private void insertInnerComponentsToCache(Map> componentCache, Component childComponent) { @@ -705,25 +722,24 @@ public class CsarUtils { return Either.left(content); } - private Either getLatestSchemaFilesFromCassandra() { - Matcher matcher = Pattern.compile("(?!\\.)(\\d+(\\.\\d+)+)(?![\\d\\.])").matcher(SDC_VERSION); - matcher.find(); - final String VERSION_FIRST_THREE_OCTATES = matcher.group(0); - Either, ActionStatus> specificSchemaFiles = sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(VERSION_FIRST_THREE_OCTATES, CONFORMANCE_LEVEL); + private Either getLatestSchemaFilesFromCassandra() { + Either, CassandraOperationStatus> specificSchemaFiles = sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(versionFirstThreeOctates, CONFORMANCE_LEVEL); - if(specificSchemaFiles.isRight()){ - log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", VERSION_FIRST_THREE_OCTATES, CONFORMANCE_LEVEL); - return Either.right(specificSchemaFiles.right().value()); + if(specificSchemaFiles.isRight()){ + log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", versionFirstThreeOctates, CONFORMANCE_LEVEL); + StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(specificSchemaFiles.right().value()); + ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus); + return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse)); } - List listOfSchemas = specificSchemaFiles.left().value(); + List listOfSchemas = specificSchemaFiles.left().value(); if(listOfSchemas.isEmpty()){ - log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", VERSION_FIRST_THREE_OCTATES, CONFORMANCE_LEVEL); - return Either.right(ActionStatus.GENERAL_ERROR); + log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", versionFirstThreeOctates, CONFORMANCE_LEVEL); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.TOSCA_SCHEMA_FILES_NOT_FOUND, versionFirstThreeOctates, CONFORMANCE_LEVEL)); } - ESSdcSchemaFilesData schemaFile = listOfSchemas.iterator().next(); + SdcSchemaFilesData schemaFile = listOfSchemas.iterator().next(); return Either.left(schemaFile.getPayloadAsArray()); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java index 072861ba3a..8be5b0b4b3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java @@ -336,10 +336,9 @@ public class ToscaExportHandler { Resource resource = (Resource) component; toscaMetadata.setType(resource.getResourceType().name()); toscaMetadata.setSubcategory(categoryDefinition.getSubcategories().get(0).getName()); - if (!isInstance) { - toscaMetadata.setResourceVendor(resource.getVendorName()); - toscaMetadata.setResourceVendorRelease(resource.getVendorRelease()); - } + toscaMetadata.setResourceVendor(resource.getVendorName()); + toscaMetadata.setResourceVendorRelease(resource.getVendorRelease()); + break; case SERVICE: toscaMetadata.setType(component.getComponentType().getValue()); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/user/IUserBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/user/IUserBusinessLogic.java index 54ba9bf571..6bec3fa938 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/user/IUserBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/user/IUserBusinessLogic.java @@ -25,7 +25,6 @@ import java.util.List; import javax.servlet.ServletContext; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.model.FunctionalMenuInfo; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.exception.ResponseFormat; @@ -50,7 +49,4 @@ public interface IUserBusinessLogic { public Either deActivateUser(User modifier, String userUniuqeIdToDeactive); public Either authorize(User authUser); - - public Either getFunctionalMenu(String userId); - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogic.java index c90cc6118f..7135bfb62e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogic.java @@ -28,18 +28,14 @@ import java.util.Map; import javax.annotation.Resource; import javax.servlet.ServletContext; -import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.tinkerpop.gremlin.structure.Edge; -import org.openecomp.portalsdk.core.onboarding.ueb.FunctionalMenu; -import org.openecomp.portalsdk.core.onboarding.ueb.UebException; import org.openecomp.sdc.be.config.BeEcompErrorManager; -import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.titan.TitanGenericDao; import org.openecomp.sdc.be.dao.utils.UserStatusEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.FunctionalMenuInfo; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation; @@ -249,16 +245,17 @@ public class UserBusinessLogic implements IUserBusinessLogic { // comment until admin will be able to do do check-in/check-out from the // UI - Either, StorageOperationStatus> userPendingTasksReq = getPandingUserPandingTasksWithCommit(userToUpdate); + Either, StorageOperationStatus> userPendingTasksReq = getPendingUserPendingTasksWithCommit(userToUpdate); if (userPendingTasksReq.isRight()) { - log.debug("updateUserRole method - failed to get user pending tasks list", userIdToUpdate); + log.debug("updateUserRole method - failed to get user pending tasks list userId {}", userIdToUpdate); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(userPendingTasksReq.right().value()))); } List userPendingTasks = userPendingTasksReq.left().value(); - if (userPendingTasks.size() > 0) { - log.debug("updateUserRole method - User canot be updated, user have panding projects", userIdToUpdate); - String userTasksStatusForErrorMessage = getUserPandingTaskStatusByRole(UserRoleEnum.valueOf(userToUpdate.getRole())); + if (!userPendingTasks.isEmpty()) { + log.debug("updateUserRole method - User canot be updated, user have pending projects userId {}", userIdToUpdate); + + String userTasksStatusForErrorMessage = getUserPendingTaskStatusByRole(UserRoleEnum.valueOf(userToUpdate.getRole())); String userInfo = userToUpdate.getFirstName() + " " + userToUpdate.getLastName() + '(' + userToUpdate.getUserId() + ')'; responseFormat = componentsUtils.getResponseFormat(ActionStatus.CANNOT_UPDATE_USER_WITH_ACTIVE_ELEMENTS, userInfo, userTasksStatusForErrorMessage); handleAuditing(modifier, userToUpdate, userToUpdate, responseFormat, AuditingActionEnum.UPDATE_USER); @@ -413,7 +410,7 @@ public class UserBusinessLogic implements IUserBusinessLogic { return Either.right(responseFormat); } - Either, StorageOperationStatus> userPendingTasksReq = getPandingUserPandingTasksWithCommit(userToDeactivate); + Either, StorageOperationStatus> userPendingTasksReq = getPendingUserPendingTasksWithCommit(userToDeactivate); if (userPendingTasksReq.isRight()) { log.debug("deActivateUser method - failed to get user pending tasks list", userUniuqeIdToDeactive); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(userPendingTasksReq.right().value()))); @@ -421,9 +418,9 @@ public class UserBusinessLogic implements IUserBusinessLogic { List userPendingTasks = userPendingTasksReq.left().value(); if (userPendingTasks.size() > 0) { - log.debug("deActivateUser method - User canot be deleted, user have panding projects", userUniuqeIdToDeactive); + log.debug("deActivateUser method - User canot be deleted, user have pending projects", userUniuqeIdToDeactive); - String userTasksStatusForErrorMessage = getUserPandingTaskStatusByRole(UserRoleEnum.valueOf(userToDeactivate.getRole())); + String userTasksStatusForErrorMessage = getUserPendingTaskStatusByRole(UserRoleEnum.valueOf(userToDeactivate.getRole())); String userInfo = userToDeactivate.getFirstName() + " " + userToDeactivate.getLastName() + '(' + userToDeactivate.getUserId() + ')'; responseFormat = componentsUtils.getResponseFormat(ActionStatus.CANNOT_DELETE_USER_WITH_ACTIVE_ELEMENTS, userInfo, userTasksStatusForErrorMessage); handleAuditing(modifier, userToDeactivate, userToDeactivate, responseFormat, AuditingActionEnum.DELETE_USER); @@ -589,7 +586,7 @@ public class UserBusinessLogic implements IUserBusinessLogic { return Either.left(updatedUser); } - private Either, StorageOperationStatus> getPandingUserPandingTasksWithCommit(User user) { + private Either, StorageOperationStatus> getPendingUserPendingTasksWithCommit(User user) { Either, StorageOperationStatus> result = null; @@ -601,21 +598,21 @@ public class UserBusinessLogic implements IUserBusinessLogic { case PRODUCT_STRATEGIST: case PRODUCT_MANAGER: properties.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); - return userAdminOperation.getUserPandingTasksList(user, properties); + return userAdminOperation.getUserPendingTasksList(user, properties); case TESTER: properties.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name()); - return userAdminOperation.getUserPandingTasksList(user, properties); + return userAdminOperation.getUserPendingTasksList(user, properties); case ADMIN: properties.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name()); properties.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); - return userAdminOperation.getUserPandingTasksList(user, properties); + return userAdminOperation.getUserPendingTasksList(user, properties); default: return Either.left(new ArrayList<>()); } } finally { // commit will be perform outside!!! if (result == null || result.isRight()) { - log.debug("getUserPandingTasksList failed to perform fetching"); + log.debug("getUserPendingTasksList failed to perform fetching"); titanDao.rollback(); } else { titanDao.commit(); @@ -623,7 +620,7 @@ public class UserBusinessLogic implements IUserBusinessLogic { } } - private String getUserPandingTaskStatusByRole(UserRoleEnum role) { + private String getUserPendingTaskStatusByRole(UserRoleEnum role) { switch (role) { case DESIGNER: @@ -639,77 +636,4 @@ public class UserBusinessLogic implements IUserBusinessLogic { return ""; } } - - /** - * return the functional menu of a given user - * - * @param userId - * @param inTransaction - * @return - */ - public Either getFunctionalMenu(String userId) { - - boolean toCommit = false; - - FunctionalMenuInfo functionalMenuInfo = new FunctionalMenuInfo(); - - try { - - Either, ActionStatus> userResult = userAdminOperation.getUserDataWithFunctionalMenu(userId); - if (userResult.isRight()) { - ActionStatus actionStatus = userResult.right().value(); - if (actionStatus == ActionStatus.USER_NOT_FOUND) { - actionStatus = ActionStatus.INVALID_USER_ID; - } - return Either.right(actionStatus); - } - - ImmutablePair immutablePair = userResult.left().value(); - FunctionalMenuInfo currentFunctionalMenu = immutablePair.right; - String currentMenuStr = currentFunctionalMenu != null ? currentFunctionalMenu.getFunctionalMenu() : null; - - String functionalMenu = getFunctionalMenuFromUeb(userId); - - // functionalMenu can be null or since we catch UebException - if (functionalMenu != null && false == functionalMenu.isEmpty()) { - functionalMenuInfo.setFunctionalMenu(functionalMenu); - if (false == functionalMenu.equals(currentMenuStr)) { - log.debug("Going to update functional menu of user {}. Functional menu is {}", userId, functionalMenu); - userAdminOperation.createOrUpdateFunctionalMenu(userId, functionalMenu); - } - } else { - String menu = currentMenuStr; - if (menu == null) { - menu = "[]"; - } - log.debug("Fetch functional menu from old request. Functional menu is {}", menu); - functionalMenuInfo.setFunctionalMenu(menu); - } - - toCommit = true; - - } finally { - if (toCommit) { - titanDao.commit(); - } else { - titanDao.rollback(); - } - } - - return Either.left(functionalMenuInfo); - } - - private String getFunctionalMenuFromUeb(String userId) { - String functionalMenu = null; - try { - log.debug("Before calling to FunctionalMenu method for user {}", userId); - functionalMenu = FunctionalMenu.get(userId); - log.debug("Functional menu fetched is {}", functionalMenu); - - } catch (UebException e) { - log.debug("Failed to fetch 'functional menu' of user {} from ecomp portal(via UEB)", userId, e); - BeEcompErrorManager.getInstance().logInternalFlowError("FetchFunctionalMenu", "Failed to fetch 'functional menu'", ErrorSeverity.ERROR); - } - return functionalMenu; - } } diff --git a/catalog-be/src/main/resources/application-context.xml b/catalog-be/src/main/resources/application-context.xml index 702c63ea81..6c44b270c2 100644 --- a/catalog-be/src/main/resources/application-context.xml +++ b/catalog-be/src/main/resources/application-context.xml @@ -57,7 +57,7 @@ - + diff --git a/catalog-be/src/main/resources/config/SDC.zip b/catalog-be/src/main/resources/config/SDC.zip index dfb4be85fb..674f6f86b4 100644 Binary files a/catalog-be/src/main/resources/config/SDC.zip and b/catalog-be/src/main/resources/config/SDC.zip differ diff --git a/catalog-be/src/main/resources/config/error-configuration.yaml b/catalog-be/src/main/resources/config/error-configuration.yaml index ef7a885678..0fb4e146d4 100644 --- a/catalog-be/src/main/resources/config/error-configuration.yaml +++ b/catalog-be/src/main/resources/config/error-configuration.yaml @@ -1765,7 +1765,7 @@ errors: # %4 – Artifact uuid ARTIFACT_PAYLOAD_NOT_FOUND_DURING_CSAR_CREATION: { code: 400, - message: " Error: CSAR packaging failed for %1 %2. Artifact %3 [%4] was not found", + message: "Error: CSAR packaging failed for %1 %2. Artifact %3 [%4] was not found", messageId: "SVC4659" } #---------SVC4660------------------------------ @@ -1776,3 +1776,11 @@ errors: message: "Creation of %1 failed. Generic type %2 was not found", messageId: "SVC4660" } +#---------SVC4661------------------------------ +# %1 - assetType +# %2 - matching generic node type name + TOSCA_SCHEMA_FILES_NOT_FOUND: { + code: 400, + message: "Error: CSAR packaging failed. TOSCA schema files for SDC-Version: %1 and Conformance-Level %2 were not found", + messageId: "SVC4661" + } \ No newline at end of file diff --git a/catalog-be/src/main/resources/config/logback.xml b/catalog-be/src/main/resources/config/logback.xml index 8ba0a31944..ba16783536 100644 --- a/catalog-be/src/main/resources/config/logback.xml +++ b/catalog-be/src/main/resources/config/logback.xml @@ -1,8 +1,8 @@ - - + + diff --git a/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.yml b/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.yml index b4c442f3df..63d70c699e 100644 --- a/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.yml +++ b/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.yml @@ -21,6 +21,19 @@ map: json: derived_from: tosca.datatypes.Root + +scalar-unit: + derived_from: tosca.datatypes.Root + +scalar-unit.size: + derived_from: scalar-unit + +scalar-unit.time: + derived_from: scalar-unit + +scalar-unit.frequency: + derived_from: scalar-unit + tosca.datatypes.Credential: derived_from: tosca.datatypes.Root diff --git a/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.zip b/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.zip index 4f3e269c69..9c5964df1d 100644 Binary files a/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.zip and b/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.zip differ diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java index 5bda32495b..6cb90d0920 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java @@ -40,8 +40,10 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.InjectMocks; +import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.ArtifactsResolver; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig; import org.openecomp.sdc.be.config.ConfigurationManager; @@ -96,7 +98,7 @@ public class ArtifactBusinessLogicTest { public static final ServiceOperation serviceOperation = Mockito.mock(ServiceOperation.class); public static final ArtifactCassandraDao artifactCassandraDao = Mockito.mock(ArtifactCassandraDao.class); public static final ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); - + // public static final InformationDeployedArtifactsBusinessLogic // informationDeployedArtifactsBusinessLogic = // Mockito.mock(InformationDeployedArtifactsBusinessLogic.class); diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactResolverTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactResolverTest.java new file mode 100644 index 0000000000..fd7717a769 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactResolverTest.java @@ -0,0 +1,91 @@ +package org.openecomp.sdc.be.components.impl; + +import org.junit.Before; +import org.junit.Test; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; + + +import java.util.Collections; +import java.util.Map; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + + +public class ArtifactResolverTest { + + private ArtifactResolverImpl testInstance = new ArtifactResolverImpl(); + private Service service, noArtifactsService; + private Resource resource, noArtifactsResource; + private ComponentInstance componentInstance, noArtifactsInstance; + + @Before + public void setUp() throws Exception { + noArtifactsService = new Service(); + noArtifactsResource = new Resource(); + resource = new Resource(); + service = new Service(); + componentInstance = new ComponentInstance(); + noArtifactsInstance = new ComponentInstance(); + + ArtifactDefinition artifact1 = new ArtifactDefinition(); + artifact1.setUniqueId("a1"); + + ArtifactDefinition artifact2 = new ArtifactDefinition(); + artifact2.setUniqueId("a2"); + + ArtifactDefinition artifact3 = new ArtifactDefinition(); + artifact3.setUniqueId("a3"); + + Map artifact1Map = Collections.singletonMap("key1", artifact1); + Map artifact2Map = Collections.singletonMap("key1", artifact2); + Map artifact3Map = Collections.singletonMap("key1", artifact3); + + resource.setDeploymentArtifacts(artifact1Map); + resource.setArtifacts(artifact2Map); + + service.setDeploymentArtifacts(artifact1Map); + service.setArtifacts(artifact2Map); + service.setServiceApiArtifacts(artifact3Map); + + componentInstance.setDeploymentArtifacts(artifact1Map); + componentInstance.setArtifacts(artifact2Map); + } + + @Test + public void findArtifactOnComponent_noArtifactsOnComponent() throws Exception { + assertNull(testInstance.findArtifactOnComponent(noArtifactsResource, ComponentTypeEnum.RESOURCE, "someId")); + assertNull(testInstance.findArtifactOnComponent(noArtifactsService, ComponentTypeEnum.SERVICE, "someId")); + } + + @Test + public void findArtifactOnComponent_resource() throws Exception { + assertNull(testInstance.findArtifactOnComponent(resource, ComponentTypeEnum.RESOURCE, "someId")); + assertNotNull(testInstance.findArtifactOnComponent(resource, ComponentTypeEnum.RESOURCE, "a1")); + assertNotNull(testInstance.findArtifactOnComponent(resource, ComponentTypeEnum.RESOURCE, "a2")); + } + + @Test + public void findArtifactOnComponent_service() throws Exception { + assertNull(testInstance.findArtifactOnComponent(service, ComponentTypeEnum.SERVICE, "someId")); + assertNotNull(testInstance.findArtifactOnComponent(service, ComponentTypeEnum.SERVICE, "a1")); + assertNotNull(testInstance.findArtifactOnComponent(service, ComponentTypeEnum.SERVICE, "a2")); + assertNotNull(testInstance.findArtifactOnComponent(service, ComponentTypeEnum.SERVICE, "a3")); + } + + @Test + public void findArtifactOnInstance_instanceHasNoArtifacts() throws Exception { + assertNull(testInstance.findArtifactOnComponentInstance(noArtifactsInstance, "someId")); + } + + @Test + public void findArtifactOnInstance() throws Exception { + assertNull(testInstance.findArtifactOnComponentInstance(componentInstance, "someId")); + assertNotNull(testInstance.findArtifactOnComponentInstance(componentInstance, "a1")); + assertNotNull(testInstance.findArtifactOnComponentInstance(componentInstance, "a2")); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java index 6dd19cce57..59d49de3a3 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java @@ -42,7 +42,6 @@ import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaElementTypeEnum; import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; -import org.openecomp.sdc.be.model.AttributeDefinition; import org.openecomp.sdc.be.model.HeatParameterDefinition; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.common.api.ArtifactTypeEnum; @@ -300,7 +299,7 @@ public class ImportUtilsTest { public void testGetAttributesFromYml() throws IOException { Map toscaJson = (Map) loadJsonFromFile("importToscaWithAttribute.yml"); - Either, ResultStatusEnum> actualAttributes = ImportUtils.getAttributes(toscaJson); + Either, ResultStatusEnum> actualAttributes = ImportUtils.getAttributes(toscaJson); assertTrue(actualAttributes.isLeft()); Map> expectedAttributes = getElements(toscaJson, ToscaTagNamesEnum.ATTRIBUTES); compareAttributes(expectedAttributes, actualAttributes.left().value()); @@ -318,10 +317,10 @@ public class ImportUtilsTest { } - private void compareAttributes(Map> expected, Map actual) { + private void compareAttributes(Map> expected, Map actual) { Map singleExpectedAttribute; - AttributeDefinition actualAttribute, expectedAttributeModel; + PropertyDefinition actualAttribute, expectedAttributeModel; // attributes of resource for (Map.Entry> expectedAttribute : expected.entrySet()) { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServletTest.java index 2aa061a890..d6808da5d6 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServletTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServletTest.java @@ -52,6 +52,7 @@ import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; import org.openecomp.sdc.be.components.impl.ResourceImportManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.ecomp.converters.AssetMetadataConverter; import org.openecomp.sdc.be.externalapi.servlet.representation.ResourceAssetMetadata; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.ServletUtils; -- cgit 1.2.3-korg