summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorvasraz <vasyl.razinkov@est.tech>2022-05-31 16:26:46 +0100
committerMichael Morris <michael.morris@est.tech>2022-06-02 21:18:06 +0000
commita2313b70009cae09db66ccc7b542ec4679e6a23a (patch)
tree9b5fe3345bdb70979bc8acb214b15d49ac2e71ff
parent3274debd73e079c795eff3b6536018efc078794c (diff)
Maintain VFC UI added properties after an upgrade
Signed-off-by: Vasyl Razinkov <vasyl.razinkov@est.tech> Change-Id: I3d4c06f3f27057a08a47683d289e87bc6cb90bfa Issue-ID: SDC-4012
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java11
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java956
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java141
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentPropertyServlet.java4
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java161
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java212
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java4625
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentPropertyServletTest.java3
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceProperty.java2
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaOperationFacade.java499
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PropertyDataDefinition.java6
11 files changed, 3401 insertions, 3219 deletions
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java
index bbdae470e1..602ca63ab4 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java
@@ -82,12 +82,11 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
* Create new property on component in graph
*
* @param componentId
- * @param propertyName
* @param newPropertyDefinition
* @param userId
* @return either properties or response format
*/
- public Either<EntryData<String, PropertyDefinition>, ResponseFormat> addPropertyToComponent(String componentId, String propertyName,
+ public Either<EntryData<String, PropertyDefinition>, ResponseFormat> addPropertyToComponent(String componentId,
PropertyDefinition newPropertyDefinition,
String userId) {
Either<EntryData<String, PropertyDefinition>, ResponseFormat> result = null;
@@ -107,6 +106,7 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
return result;
}
try {
+ final String propertyName = newPropertyDefinition.getName();
if (!ComponentValidationUtils.canWorkOnComponent(component, userId)) {
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
return result;
@@ -139,14 +139,13 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
innerType = prop.getType();
}
}
- String convertedValue = null;
if (newPropertyDefinition.getDefaultValue() != null) {
- convertedValue = converter.convert(newPropertyDefinition.getDefaultValue(), innerType, allDataTypes);
+ final String convertedValue = converter.convert(newPropertyDefinition.getDefaultValue(), innerType, allDataTypes);
newPropertyDefinition.setDefaultValue(convertedValue);
}
}
Either<PropertyDefinition, StorageOperationStatus> addPropertyEither = toscaOperationFacade
- .addPropertyToComponent(propertyName, newPropertyDefinition, component);
+ .addPropertyToComponent(newPropertyDefinition, component);
if (addPropertyEither.isRight()) {
log.info("Failed to add new property {}. Error - {}", componentId, addPropertyEither.right().value());
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -212,7 +211,7 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
copiedPropertyDefinition.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(componentId, propertyName));
copiedPropertyDefinition.setParentUniqueId(componentId);
final Either<PropertyDefinition, StorageOperationStatus> operationResult = toscaOperationFacade
- .addPropertyToComponent(propertyName, copiedPropertyDefinition, component);
+ .addPropertyToComponent(copiedPropertyDefinition, component);
if (operationResult.isRight()) {
final String error = String
.format("Failed to add copied property '%s' to component '%s'. Operation status: '%s'", propertyDefinition.getUniqueId(), componentId,
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 aa2ba31385..d916dc6f64 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
@@ -19,8 +19,36 @@
*/
package org.openecomp.sdc.be.components.impl;
+import static java.util.stream.Collectors.toList;
+import static java.util.stream.Collectors.toMap;
+import static java.util.stream.Collectors.toSet;
+import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
+import static org.apache.commons.collections.MapUtils.isEmpty;
+import static org.apache.commons.collections.MapUtils.isNotEmpty;
+import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaStringElement;
+import static org.openecomp.sdc.be.components.impl.ImportUtils.getPropertyJsonStringValue;
+import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN;
+import static org.openecomp.sdc.common.api.Constants.DEFAULT_GROUP_VF_MODULE;
+
import com.google.common.annotations.VisibleForTesting;
import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
@@ -162,35 +190,6 @@ import org.springframework.context.annotation.Lazy;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Objects;
-import java.util.Optional;
-import java.util.Set;
-import java.util.function.Function;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
-
-import static java.util.stream.Collectors.toList;
-import static java.util.stream.Collectors.toMap;
-import static java.util.stream.Collectors.toSet;
-import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
-import static org.apache.commons.collections.MapUtils.isEmpty;
-import static org.apache.commons.collections.MapUtils.isNotEmpty;
-import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaStringElement;
-import static org.openecomp.sdc.be.components.impl.ImportUtils.getPropertyJsonStringValue;
-import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN;
-import static org.openecomp.sdc.common.api.Constants.DEFAULT_GROUP_VF_MODULE;
-
@org.springframework.stereotype.Component("resourceBusinessLogic")
public class ResourceBusinessLogic extends ComponentBusinessLogic {
@@ -261,8 +260,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
final DataTypeBusinessLogic dataTypeBusinessLogic, final PolicyTypeBusinessLogic policyTypeBusinessLogic,
final ModelOperation modelOperation) {
super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic, interfaceOperation,
- interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation, componentContactIdValidator, componentNameValidator,
- componentTagsValidator, componentValidator, componentIconValidator, componentProjectCodeValidator, componentDescriptionValidator);
+ interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation, componentContactIdValidator, componentNameValidator,
+ componentTagsValidator, componentValidator, componentIconValidator, componentProjectCodeValidator, componentDescriptionValidator);
this.componentInstanceBusinessLogic = componentInstanceBusinessLogic;
this.resourceImportManager = resourceImportManager;
this.inputsBusinessLogic = inputsBusinessLogic;
@@ -388,7 +387,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
String userId) {
validateUserExists(userId);
Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
- .validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE);
+ .validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE);
// DE242223
janusGraphDao.commit();
if (dataModelResponse.isLeft()) {
@@ -398,7 +397,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(result);
}
ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
return Either.right(responseFormat);
}
@@ -407,7 +406,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
validateResourceBeforeCreate(resource, user, false);
String csarUUID = payloadName == null ? resource.getCsarUUID() : payloadName;
loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,
- "Starting to create resource from CSAR by user {} ", user.getUserId());
+ "Starting to create resource from CSAR by user {} ", user.getUserId());
if (StringUtils.isNotEmpty(csarUUID)) {
csarBusinessLogic.validateCsarBeforeCreate(resource, auditingAction, user, csarUUID);
log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID);
@@ -446,7 +445,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
updatedResource = updateResourceMetadata(resourceUniqueId, resource, oldResource, user, false);
} else {
updatedResource = updateResourceFromCsar(oldResource, resource, user, AuditingActionEnum.UPDATE_RESOURCE_METADATA, false,
- csarUIPayload, csarUUID);
+ csarUIPayload, csarUUID);
}
} else {
log.debug("Failed to update resource {}, csarUUID or payload name is missing", resource.getSystemName());
@@ -470,16 +469,16 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
// name
Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = toscaOperationFacade
- .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUUID, resource.getSystemName());
+ .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUUID, resource.getSystemName());
if (resourceLinkedToCsarRes.isRight()) {
if (StorageOperationStatus.NOT_FOUND != resourceLinkedToCsarRes.right().value()) {
log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID, resource.getSystemName());
throw new StorageException(resourceLinkedToCsarRes.right().value());
}
} else if (!resourceLinkedToCsarRes.left().value().getUniqueId().equals(oldResource.getUniqueId()) && !resourceLinkedToCsarRes.left().value()
- .getName().equals(oldResource.getName())) {
+ .getName().equals(oldResource.getName())) {
ResponseFormat errorResponse = componentsUtils
- .getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID, resourceLinkedToCsarRes.left().value().getName());
+ .getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID, resourceLinkedToCsarRes.left().value().getName());
componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
throw new ByActionStatusComponentException(ActionStatus.VSP_ALREADY_EXISTS, csarUUID, resourceLinkedToCsarRes.left().value().getName());
}
@@ -496,9 +495,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
String oldCsarUUID = oldResource.getCsarUUID();
if (oldCsarUUID != null && !oldCsarUUID.isEmpty() && !csarUUID.equals(oldCsarUUID)) {
log.debug("Failed to update resource with UniqueId {} using Csar {}, since the resource is linked to a different VSP {}",
- resourceUniqueId, csarUUID, oldCsarUUID);
+ resourceUniqueId, csarUUID, oldCsarUUID);
ResponseFormat errorResponse = componentsUtils
- .getResponseFormat(ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
+ .getResponseFormat(ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
throw new ByActionStatusComponentException(ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
}
@@ -531,16 +530,16 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
lockComponent(lockedResourceId, oldResource, "update Resource From Csar");
Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractTypesInfo();
Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
- nodeTypesInfo, csarInfo, oldResource);
+ nodeTypesInfo, csarInfo, oldResource);
if (findNodeTypesArtifactsToHandleRes.isRight()) {
log.debug("failed to find node types for update with artifacts during import csar {}. ", csarInfo.getCsarUUID());
throw new ByResponseFormatComponentException(findNodeTypesArtifactsToHandleRes.right().value());
}
Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes.left()
- .value();
+ .value();
try {
updatedResource = updateResourceFromYaml(oldResource, newResource, updateResource, createdArtifacts, csarInfo.getMainTemplateName(),
- csarInfo.getMainTemplateContent(), csarInfo, nodeTypesInfo, nodeTypesArtifactsToHandle, null, false);
+ csarInfo.getMainTemplateContent(), csarInfo, nodeTypesInfo, nodeTypesArtifactsToHandle, null, false);
} catch (ComponentException | StorageException e) {
rollback(inTransaction, newResource, createdArtifacts, null);
throw e;
@@ -554,9 +553,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
private void validateLifecycleState(Resource oldResource, User user) {
if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT == oldResource.getLifecycleState() && !oldResource.getLastUpdaterUserId()
- .equals(user.getUserId())) {
+ .equals(user.getUserId())) {
log.debug("#validateLifecycleState - Current user is not last updater, last updater userId: {}, current user userId: {}",
- oldResource.getLastUpdaterUserId(), user.getUserId());
+ oldResource.getLastUpdaterUserId(), user.getUserId());
throw new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION);
}
}
@@ -572,44 +571,44 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
ParsedToscaYamlInfo uploadComponentInstanceInfoMap;
try {
uploadComponentInstanceInfoMap = csarBusinessLogic
- .getParsedToscaYamlInfo(yamlFileContent, yamlFileName, nodeTypesInfo, csarInfo, nodeName, oldResource);
+ .getParsedToscaYamlInfo(yamlFileContent, yamlFileName, nodeTypesInfo, csarInfo, nodeName, oldResource);
Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.getInstances();
if (MapUtils.isEmpty(instances) && newResource.getResourceType() != ResourceTypeEnum.PNF) {
throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlFileName);
}
preparedResource = updateExistingResourceByImport(newResource, oldResource, csarInfo.getModifier(), inTransaction, shouldLock,
- isNested).left;
+ isNested).left;
log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent);
handleResourceGenericType(preparedResource, yamlFileContent, uploadComponentInstanceInfoMap,
- uploadComponentInstanceInfoMap.getSubstitutionMappingNodeType());
+ uploadComponentInstanceInfoMap.getSubstitutionMappingNodeType());
handleNodeTypes(yamlFileName, preparedResource, yamlFileContent, shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo,
- csarInfo, nodeName, newResource.getModel());
+ csarInfo, nodeName, newResource.getModel());
preparedResource = createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs());
Map<String, Resource> existingNodeTypesByResourceNames = new HashMap<>();
final Map<String, UploadComponentInstanceInfo> instancesToCreate = getInstancesToCreate(uploadComponentInstanceInfoMap,
- newResource.getModel());
+ newResource.getModel());
preparedResource = createResourceInstances(yamlFileName, preparedResource, oldResource, instancesToCreate, csarInfo.getCreatedNodes(),
- existingNodeTypesByResourceNames);
+ existingNodeTypesByResourceNames);
preparedResource = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, oldResource,
- instancesToCreate,
- existingNodeTypesByResourceNames);
+ instancesToCreate,
+ existingNodeTypesByResourceNames);
} catch (ComponentException e) {
ResponseFormat responseFormat =
- e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
+ e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
log.debug("#updateResourceFromYaml - failed to update newResource from yaml {} .The error is {}", yamlFileName, responseFormat);
componentsUtils
- .auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldResource : preparedResource, actionEnum);
+ .auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldResource : preparedResource, actionEnum);
throw e;
} catch (StorageException e) {
ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
log.debug("#updateResourceFromYaml - failed to update newResource from yaml {} .The error is {}", yamlFileName, responseFormat);
componentsUtils
- .auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldResource : preparedResource, actionEnum);
+ .auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldResource : preparedResource, actionEnum);
throw e;
}
Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
- .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.getGroups(), preparedResource.getSystemName());
+ .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.getGroups(), preparedResource.getSystemName());
if (validateUpdateVfGroupNamesRes.isRight()) {
throw new ByResponseFormatComponentException(validateUpdateVfGroupNamesRes.right().value());
}
@@ -625,7 +624,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
preparedResource = updateGroupsOnResource(preparedResource, groups);
NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToHandle);
Either<Resource, ResponseFormat> updateArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.UPDATE, createdArtifacts, yamlFileName,
- csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
+ csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
if (updateArtifactsEither.isRight()) {
log.debug("failed to update artifacts {}", updateArtifactsEither.right().value());
throw new ByResponseFormatComponentException(updateArtifactsEither.right().value());
@@ -651,7 +650,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Map<String, ArtifactDefinition> createdNewArtifacts = preparedResource.getDeploymentArtifacts();
if (DEFAULT_GROUP_VF_MODULE.equals(group.getType())) {
List<PropertyDataDefinition> volumePropList = group.getProperties().stream().filter(p -> "volume_group".equals(p.getName()))
- .collect(Collectors.toList());
+ .collect(Collectors.toList());
if (!volumePropList.isEmpty()) {
PropertyDataDefinition volumeProp = volumePropList.get(0);
if (volumeProp != null) {
@@ -671,14 +670,14 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
log.debug("Failed to update groups name : oldResource or preparedResource is null");
} else if (CollectionUtils.isNotEmpty(oldResource.getGroups()) && CollectionUtils.isNotEmpty(preparedResource.getGroups())) {
Map<String, String> oldGroups = oldResource.getGroups().stream()
- .collect(toMap(GroupDataDefinition::getInvariantName, GroupDataDefinition::getName));
+ .collect(toMap(GroupDataDefinition::getInvariantName, GroupDataDefinition::getName));
List<GroupDefinition> updatedGroups = preparedResource.getGroups().stream()
- .filter(group -> oldGroups.containsKey(group.getInvariantName()) && !group.getName().equals(oldGroups.get(group.getInvariantName())))
- .collect(toList());
+ .filter(group -> oldGroups.containsKey(group.getInvariantName()) && !group.getName().equals(oldGroups.get(group.getInvariantName())))
+ .collect(toList());
if (CollectionUtils.isNotEmpty(updatedGroups)) {
if (isTopologyChanged) {
updatedGroups.stream().filter(group -> !group.isVspOriginated())
- .forEach(group -> group.setName(oldGroups.get(group.getInvariantName())));
+ .forEach(group -> group.setName(oldGroups.get(group.getInvariantName())));
} else {
updatedGroups.forEach(group -> group.setName(oldGroups.get(group.getInvariantName())));
}
@@ -693,10 +692,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
} else {
if (CollectionUtils.isNotEmpty(oldResource.getComponentInstances())) {
Map<String, String> oldInstances = oldResource.getComponentInstances().stream()
- .collect(toMap(ComponentInstance::getInvariantName, ComponentInstance::getName));
+ .collect(toMap(ComponentInstance::getInvariantName, ComponentInstance::getName));
List<ComponentInstance> updatedInstances = preparedResource.getComponentInstances().stream()
- .filter(i -> oldInstances.containsKey(i.getInvariantName()) && !i.getName().equals(oldInstances.get(i.getInvariantName())))
- .collect(toList());
+ .filter(i -> oldInstances.containsKey(i.getInvariantName()) && !i.getName().equals(oldInstances.get(i.getInvariantName())))
+ .collect(toList());
if (CollectionUtils.isNotEmpty(updatedInstances)) {
if (isTopologyChanged) {
updatedInstances.stream().filter(i -> !i.isCreatedFromCsar()).forEach(i -> i.setName(oldInstances.get(i.getInvariantName())));
@@ -706,7 +705,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
}
componentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME, null, preparedResource.getUniqueId(),
- csarInfo.getModifier().getUserId(), preparedResource.getComponentInstances(), false);
+ csarInfo.getModifier().getUserId(), preparedResource.getComponentInstances(), false);
}
}
@@ -717,18 +716,18 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
String nodeName = nodeTypeInfoToUpdateArtifacts.getNodeName();
Resource resource = preparedResource;
Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts
- .getNodeTypesArtifactsToHandle();
+ .getNodeTypesArtifactsToHandle();
if (preparedResource.getResourceType() == ResourceTypeEnum.CVFC) {
if (nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null && !nodeTypesArtifactsToHandle.get(nodeName).isEmpty()) {
Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = handleNodeTypeArtifacts(preparedResource,
- nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(), inTransaction, true);
+ nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(), inTransaction, true);
if (handleNodeTypeArtifactsRes.isRight()) {
return Either.right(handleNodeTypeArtifactsRes.right().value());
}
}
} else {
Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource, csarInfo, createdArtifacts,
- new ArtifactOperationInfo(false, false, operation), shouldLock, inTransaction);
+ new ArtifactOperationInfo(false, false, operation), shouldLock, inTransaction);
log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
if (createdCsarArtifactsEither.isRight()) {
return createdCsarArtifactsEither;
@@ -751,15 +750,15 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
final ParsedToscaYamlInfo parsedToscaYamlInfo, final String substitutionMappingNodeType) {
if (processSubstitutableAsNodeType(resource, parsedToscaYamlInfo)) {
final Map<String, Object> substitutableAsNodeType = getSubstitutableAsNodeTypeFromTemplate(
- (Map<String, Object>) new Yaml().load(topologyTemplateYaml), substitutionMappingNodeType);
+ (Map<String, Object>) new Yaml().load(topologyTemplateYaml), substitutionMappingNodeType);
final Resource genericResource = fetchAndSetDerivedFromGenericType(resource,
- (String) substitutableAsNodeType.get(TypeUtils.ToscaTagNamesEnum.DERIVED_FROM.getElementName()));
+ (String) substitutableAsNodeType.get(TypeUtils.ToscaTagNamesEnum.DERIVED_FROM.getElementName()));
generatePropertiesFromGenericType(resource, genericResource);
generatePropertiesFromNodeType(resource, substitutableAsNodeType);
final String resourceId = resource.getUniqueId();
resource.getProperties().forEach(propertyDefinition -> propertyDefinition.setUniqueId(
- UniqueIdBuilder.buildPropertyUniqueId(resourceId, propertyDefinition.getName())));
+ UniqueIdBuilder.buildPropertyUniqueId(resourceId, propertyDefinition.getName())));
createResourcePropertiesOnGraph(resource);
return genericResource;
}
@@ -767,19 +766,19 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(
- final Map<String, NodeTypeInfo> nodeTypesInfo, final CsarInfo csarInfo, final Resource oldResource) {
+ final Map<String, NodeTypeInfo> nodeTypesInfo, final CsarInfo csarInfo, final Resource oldResource) {
final Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes = Either
- .left(nodeTypesArtifactsToHandle);
+ .left(nodeTypesArtifactsToHandle);
try {
final Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csarInfo.getCsar());
final Map<String, ImmutablePair<String, String>> extractedVfcToscaNames = extractVfcToscaNames(nodeTypesInfo, oldResource.getName(),
- csarInfo);
+ csarInfo);
log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ", oldResource.getName(),
- csarInfo.getCsarUUID());
+ csarInfo.getCsarUUID());
extractedVfcToscaNames.forEach(
- (namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo, nodeTypesArtifactsToHandle, oldResource,
- extractedVfcsArtifacts, namespace, vfcToscaNames));
+ (namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo, nodeTypesArtifactsToHandle, oldResource,
+ extractedVfcsArtifacts, namespace, vfcToscaNames));
} catch (Exception e) {
final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
@@ -809,8 +808,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
// delete all informational artifacts
artifactsToDelete.addAll(
- curNodeType.getArtifacts().values().stream().filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
- .collect(toList()));
+ curNodeType.getArtifacts().values().stream().filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
+ .collect(toList()));
// delete all deployment artifacts
artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values());
if (!artifactsToDelete.isEmpty()) {
@@ -827,12 +826,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (status != null && status != StorageOperationStatus.NOT_FOUND) {
log.debug("Error occurred during fetching node type with tosca name {}, error: {}", currVfcToscaName, status);
ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.CREATE_RESOURCE);
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
} else if (StringUtils.isNotEmpty(currVfcToscaName)) {
return (Resource) toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName, resource.getModel()).left()
- .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st));
+ .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st));
}
return null;
}
@@ -844,7 +843,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
processExistingNodeTypeArtifacts(extractedArtifacts, artifactsToUpload, artifactsToUpdate, artifactsToDelete,
- collectExistingArtifacts(curNodeType));
+ collectExistingArtifacts(curNodeType));
return putFoundArtifacts(artifactsToUpload, artifactsToUpdate, artifactsToDelete);
} catch (Exception e) {
log.debug("Exception occurred when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
@@ -883,7 +882,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
private void processNodeTypeArtifact(List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate,
Map<String, ArtifactDefinition> existingArtifacts, ArtifactDefinition currNewArtifact) {
Optional<ArtifactDefinition> foundArtifact = existingArtifacts.values().stream()
- .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst();
+ .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst();
if (foundArtifact.isPresent()) {
if (foundArtifact.get().getArtifactType().equals(currNewArtifact.getArtifactType())) {
updateFoundArtifact(artifactsToUpdate, currNewArtifact, foundArtifact.get());
@@ -892,7 +891,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
} else {
log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
- currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(), foundArtifact.get().getArtifactType());
+ currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(), foundArtifact.get().getArtifactType());
}
}
}
@@ -917,8 +916,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
if (MapUtils.isNotEmpty(curNodeType.getArtifacts())) {
existingArtifacts.putAll(
- curNodeType.getArtifacts().entrySet().stream().filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
- .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
+ curNodeType.getArtifacts().entrySet().stream().filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
+ .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
}
return existingArtifacts;
}
@@ -935,14 +934,14 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Either<Resource, ResponseFormat> checkoutResourceRes;
try {
if (!resource.getComponentMetadataDefinition().getMetadataDataDefinition().getState()
- .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
+ .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
log.debug("************* Going to change life cycle state of resource {} to not certified checked out. ", resource.getName());
Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic
- .changeComponentState(resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
- new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT, LifecycleChanceActionEnum.CREATE_FROM_CSAR), inTransaction, true);
+ .changeComponentState(resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
+ new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT, LifecycleChanceActionEnum.CREATE_FROM_CSAR), inTransaction, true);
if (checkoutRes.isRight()) {
log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ",
- resource.getComponentType().getNodeType(), resource.getUniqueId(), checkoutRes.right().value().getStatus());
+ resource.getComponentType().getNodeType(), resource.getUniqueId(), checkoutRes.right().value().getStatus());
checkoutResourceRes = Either.right(checkoutRes.right().value());
} else {
checkoutResourceRes = Either.left((Resource) checkoutRes.left().value());
@@ -988,8 +987,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) {
log.debug("************* Going to {} artifact to vfc {}", curOperation.name(), nodeTypeResource.getName());
handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic
- .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user, createdArtifacts,
- new ArtifactOperationInfo(false, ignoreLifecycleState, curOperation), false, inTransaction);
+ .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user, createdArtifacts,
+ new ArtifactOperationInfo(false, ignoreLifecycleState, curOperation), false, inTransaction);
if (ArtifactOperationEnum.isCreateOrLink(curOperation)) {
createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes);
}
@@ -1012,7 +1011,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (!nodes.isEmpty()) {
for (Entry<String, Object> nodeType : nodes.entrySet()) {
final ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName(ResourceTypeEnum.VFC.name(), vfResourceName,
- nodeType.getKey());
+ nodeType.getKey());
vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
}
}
@@ -1033,7 +1032,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) {
Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils
- .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
+ .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
if (eitherNodeTypes.isLeft()) {
nodes.putAll(eitherNodeTypes.left().value());
}
@@ -1042,8 +1041,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
public Resource createResourceFromCsar(Resource resource, User user, Map<String, byte[]> csarUIPayload, String csarUUID) {
log.trace("************* created successfully from YAML, resource TOSCA ");
loggerSupportability
- .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, StatusCode.STARTED, "Starting to create Resource From Csar by user {}",
- user.getUserId());
+ .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, StatusCode.STARTED, "Starting to create Resource From Csar by user {}",
+ user.getUserId());
CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(resource, null, user, csarUIPayload, csarUUID);
Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractTypesInfo();
final String model = resource.getModel();
@@ -1062,20 +1061,20 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
- nodeTypesInfo, csarInfo, resource);
+ nodeTypesInfo, csarInfo, resource);
if (findNodeTypesArtifactsToHandleRes.isRight()) {
log.debug("failed to find node types for update with artifacts during import csar {}. ", csarInfo.getCsarUUID());
loggerSupportability
- .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
- "error: {}", findNodeTypesArtifactsToHandleRes.right().value());
+ .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+ "error: {}", findNodeTypesArtifactsToHandleRes.right().value());
throw new ByResponseFormatComponentException(findNodeTypesArtifactsToHandleRes.right().value());
}
Resource vfResource = createResourceFromYaml(resource, csarInfo.getMainTemplateContent(), csarInfo.getMainTemplateName(), nodeTypesInfo,
- csarInfo, findNodeTypesArtifactsToHandleRes.left().value(), true, false, null);
+ csarInfo, findNodeTypesArtifactsToHandleRes.left().value(), true, false, null);
log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}", vfResource.getToscaResourceName());
loggerSupportability
- .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, StatusCode.COMPLETE, "Ended create Resource From Csar by user {}",
- user.getUserId());
+ .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, StatusCode.COMPLETE, "Ended create Resource From Csar by user {}",
+ user.getUserId());
return vfResource;
}
@@ -1099,27 +1098,27 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Resource createdResource;
try {
ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic
- .getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName, resource);
+ .getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName, resource);
if (MapUtils.isEmpty(parsedToscaYamlInfo.getInstances()) && resource.getResourceType() != ResourceTypeEnum.PNF) {
throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
}
log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", resource.getName());
loggerSupportability
- .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED, "");
+ .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED, "");
createdResource = createResourceAndRIsFromYaml(yamlName, resource, parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false,
- createdArtifacts, topologyTemplateYaml, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
+ createdArtifacts, topologyTemplateYaml, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
log.debug("#createResourceFromYaml - The resource {} has been created ", resource.getName());
loggerSupportability
- .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,
- "The resource has been created: {}", resource.getName());
+ .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,
+ "The resource has been created: {}", resource.getName());
} catch (ComponentException e) {
ResponseFormat responseFormat =
- e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
+ e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
throw e;
} catch (StorageException e) {
ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
throw e;
}
@@ -1140,7 +1139,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left().value());
final Map<String, Object> nodeTypes = getNodeTypesFromTemplate(mappedToscaTemplate, substitutableAsNodeType);
createNodeTypes(yamlName, resource, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, mapToConvert,
- nodeTypes);
+ nodeTypes);
return csarInfo.getCreatedNodes();
}
@@ -1173,7 +1172,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
final Map<String, Object> dataTypesToCreate = new HashMap<>();
for (final String dataType : dataTypes.keySet()) {
final Either<DataTypeDefinition, StorageOperationStatus> result =
- propertyOperation.getDataTypeByName(dataType, model);
+ propertyOperation.getDataTypeByName(dataType, model);
if (result.isRight() && result.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
dataTypesToCreate.put(dataType, dataTypes.get(dataType));
}
@@ -1185,7 +1184,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
final Map<String, Object> policyTypesToCreate = new HashMap<>();
for (final String policyType : policyTypes.keySet()) {
final Either<PolicyTypeDefinition, StorageOperationStatus> result =
- policyTypeOperation.getLatestPolicyTypeByType(policyType, model);
+ policyTypeOperation.getLatestPolicyTypeByType(policyType, model);
if (result.isRight() && result.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
policyTypesToCreate.put(policyType, policyTypes.get(policyType));
}
@@ -1202,17 +1201,17 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
while (nodesNameValueIter.hasNext()) {
Entry<String, Object> nodeType = nodesNameValueIter.next();
Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle =
- nodeTypesArtifactsToHandle == null || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey());
+ nodeTypesArtifactsToHandle == null || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey());
if (nodeTypesInfo.containsKey(nodeType.getKey())) {
log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
vfcCreated = handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
- nodeType.getKey());
+ nodeType.getKey());
log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
} else if (csarInfo.getCreatedNodesToscaResourceNames() != null && !csarInfo.getCreatedNodesToscaResourceNames()
- .containsKey(nodeType.getKey())) {
+ .containsKey(nodeType.getKey())) {
log.trace("************* Going to create node {}", nodeType.getKey());
ImmutablePair<Resource, ActionStatus> resourceCreated = createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(),
- mapToConvert, resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, csarInfo, true);
+ mapToConvert, resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, csarInfo, true);
log.debug("************* Finished to create node {}", nodeType.getKey());
vfcCreated = resourceCreated.getLeft();
csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(), vfcCreated.getToscaResourceName());
@@ -1231,7 +1230,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
log.debug("************* Going to create node types from yaml {}", yamlName);
createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts,
- Collections.emptyMap(), csarInfo, resource.getModel());
+ Collections.emptyMap(), csarInfo, resource.getModel());
log.debug("************* Finished to create node types from yaml {}", yamlName);
if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
@@ -1247,28 +1246,28 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Resource oldComplexVfc = null;
Resource newComplexVfc = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo);
Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade
- .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
+ .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
- buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName).getRight());
+ buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName).getRight());
}
if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ", newComplexVfc.getToscaResourceName(),
- oldComplexVfcRes.right().value());
+ oldComplexVfcRes.right().value());
throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
} else if (oldComplexVfcRes.isLeft()) {
log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
final Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(oldComplexVfcRes.left().value(),
- newComplexVfc, ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
+ newComplexVfc, ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
if (eitherValidation.isLeft()) {
oldComplexVfc = oldComplexVfcRes.left().value();
}
}
newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName, oldComplexVfc,
- newComplexVfc);
+ newComplexVfc);
csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
final LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
- LifecycleChanceActionEnum.CREATE_FROM_CSAR);
+ LifecycleChanceActionEnum.CREATE_FROM_CSAR);
log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
final Resource result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, true);
csarInfo.getCreatedNodes().put(nodeName, result);
@@ -1286,10 +1285,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
CsarInfo.markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
if (oldComplexVfc == null) {
handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo, csarInfo, nodesArtifactsToHandle,
- false, true, nodeName);
+ false, true, nodeName);
} else {
handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc, AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts,
- yamlContent, yamlName, csarInfo, newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true);
+ yamlContent, yamlName, csarInfo, newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true);
}
return handleComplexVfcRes;
}
@@ -1322,7 +1321,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
final String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.getResourceType(), csarInfo);
user = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock, nodeTypeArtifactsToHandle,
- nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeNameValue.getKey(), isNested);
+ nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeNameValue.getKey(), isNested);
}
private String buildNodeTypeYaml(final Entry<String, Object> nodeNameValue, final Map<String, Object> mapToConvert, final String nodeResourceType,
@@ -1335,7 +1334,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
final Yaml yaml = new Yaml(options);
final Map<String, Object> node = new HashMap<>();
node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey()).getLeft(),
- nodeNameValue.getValue());
+ nodeNameValue.getValue());
mapToConvert.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
return yaml.dumpAsMap(mapToConvert);
}
@@ -1352,11 +1351,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
boolean forceCertificationAllowed, CsarInfo csarInfo, String nodeName,
boolean isNested) {
LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
- LifecycleChanceActionEnum.CREATE_FROM_CSAR);
+ LifecycleChanceActionEnum.CREATE_FROM_CSAR);
Function<Resource, Boolean> validator = resource -> validateResourceCreationFromNodeType(resource, creator);
return resourceImportManager
- .importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, true, needLock,
- nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested);
+ .importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, true, needLock,
+ nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested);
}
/**
@@ -1391,7 +1390,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
final String namePrefix = nodeName.replace(actualName, "");
String resourceType = namePrefix.substring(nodeTypeNamePrefix.length());
log.debug("initial namePrefix:{} resourceType {}. nodeName {} , actualName {} prefix {}", namePrefix, resourceType, nodeName, actualName,
- nodeTypeNamePrefix);
+ nodeTypeNamePrefix);
// if we import from csar, the node_type name can be
// org.openecomp.resource.abstract.node_name - in this case we always
@@ -1498,30 +1497,30 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
try {
log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,
- "Starting to add inputs from yaml: {}", yamlName);
+ "Starting to add inputs from yaml: {}", yamlName);
if (processSubstitutableAsNodeType(resource, parsedToscaYamlInfo)) {
final Map<String, Object> substitutableAsNodeType = getSubstitutableAsNodeTypeFromTemplate(
- (Map<String, Object>) new Yaml().load(topologyTemplateYaml), parsedToscaYamlInfo.getSubstitutionMappingNodeType());
+ (Map<String, Object>) new Yaml().load(topologyTemplateYaml), parsedToscaYamlInfo.getSubstitutionMappingNodeType());
resource.setToscaResourceName(parsedToscaYamlInfo.getSubstitutionMappingNodeType());
final Resource genericResource = fetchAndSetDerivedFromGenericType(resource,
- (String) substitutableAsNodeType.get(TypeUtils.ToscaTagNamesEnum.DERIVED_FROM.getElementName()));
+ (String) substitutableAsNodeType.get(TypeUtils.ToscaTagNamesEnum.DERIVED_FROM.getElementName()));
resource = createResourceTransaction(resource, csarInfo.getModifier(), isNormative);
generatePropertiesFromGenericType(resource, genericResource);
generatePropertiesFromNodeType(resource, substitutableAsNodeType);
final String resourceId = resource.getUniqueId();
resource.getProperties().forEach(propertyDefinition -> propertyDefinition.setUniqueId(
- UniqueIdBuilder.buildPropertyUniqueId(resourceId, propertyDefinition.getName())));
+ UniqueIdBuilder.buildPropertyUniqueId(resourceId, propertyDefinition.getName())));
createResourcePropertiesOnGraph(resource);
final Map<String, UploadComponentInstanceInfo> instancesToCreate = getInstancesToCreate(parsedToscaYamlInfo, resource.getModel());
log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName);
loggerSupportability
- .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,
- "Start create nodes, RI and Relations from yaml: {}", yamlName);
+ .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,
+ "Start create nodes, RI and Relations from yaml: {}", yamlName);
resource = createRIAndRelationsFromYaml(yamlName, resource, instancesToCreate, topologyTemplateYaml,
- nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, nodeName,
- parsedToscaYamlInfo.getSubstitutionMappingNodeType());
+ nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, nodeName,
+ parsedToscaYamlInfo.getSubstitutionMappingNodeType());
} else {
final Resource genericResource = fetchAndSetDerivedFromGenericType(resource, null);
resource = createResourceTransaction(resource, csarInfo.getModifier(), isNormative);
@@ -1535,7 +1534,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
log.trace("************* Finish to add inputs from yaml {}", yamlName);
loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,
- "Finish to add inputs from yaml: {}", yamlName);
+ "Finish to add inputs from yaml: {}", yamlName);
if (resource.getResourceType() == ResourceTypeEnum.PNF) {
log.trace("************* Adding generic properties to PNF");
resource = (Resource) propertyBusinessLogic.copyPropertyToComponent(resource, genericResource.getProperties());
@@ -1543,23 +1542,23 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
softwareInformationBusinessLogic.setSoftwareInformation(resource, csarInfo);
log.trace("************* Removing non-mano software information file from PNF");
if (csarInfo.getSoftwareInformationPath().isPresent() && !softwareInformationBusinessLogic.removeSoftwareInformationFile(
- csarInfo)) {
+ csarInfo)) {
log.warn(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, ResourceBusinessLogic.class.getName(), "catalog-be",
- "Could not remove the software information file.");
+ "Could not remove the software information file.");
}
}
final Map<String, UploadComponentInstanceInfo> instancesToCreate = getInstancesToCreate(parsedToscaYamlInfo);
log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName);
loggerSupportability
- .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,
- "Start create nodes, RI and Relations from yaml: {}", yamlName);
+ .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,
+ "Start create nodes, RI and Relations from yaml: {}", yamlName);
resource = createRIAndRelationsFromYaml(yamlName, resource, instancesToCreate, topologyTemplateYaml,
- nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, nodeName, null);
+ nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, nodeName, null);
}
log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName);
loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,
- "Finished to create nodes, RI and Relation from yaml: {}", yamlName);
+ "Finished to create nodes, RI and Relation from yaml: {}", yamlName);
// validate update vf module group names
Optional<Map<String, GroupDefinition>> asdGroups = checkAndCreateAsdTypeVfModules(parsedToscaYamlInfo.getInstances());
Map<String, GroupDefinition> parsedGroups = parsedToscaYamlInfo.getGroups();
@@ -1567,7 +1566,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
parsedGroups.putAll(asdGroups.get());
}
final Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
- .validateUpdateVfGroupNames(parsedGroups, resource.getSystemName());
+ .validateUpdateVfGroupNames(parsedGroups, resource.getSystemName());
if (validateUpdateVfGroupNamesRes.isRight()) {
rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
throw new ByResponseFormatComponentException(validateUpdateVfGroupNamesRes.right().value());
@@ -1576,7 +1575,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
final Map<String, GroupDefinition> groups;
log.trace("************* Going to add groups from yaml {}", yamlName);
loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,
- "Start to add groups from yaml: {}", yamlName);
+ "Start to add groups from yaml: {}", yamlName);
if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
groups = validateUpdateVfGroupNamesRes.left().value();
} else {
@@ -1586,16 +1585,16 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (createGroupsOnResource.isRight()) {
rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
- "ERROR while adding groups from yaml: {}", yamlName);
+ "ERROR while adding groups from yaml: {}", yamlName);
throw new ByResponseFormatComponentException(createGroupsOnResource.right().value());
}
resource = createGroupsOnResource.left().value();
log.trace("************* Finished to add groups from yaml {}", yamlName);
loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS, resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,
- "Finished to add groups from yaml: {}", yamlName);
+ "Finished to add groups from yaml: {}", yamlName);
log.trace("************* Going to add artifacts from yaml {}", yamlName);
loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,
- "Started to add artifacts from yaml: {}", yamlName);
+ "Started to add artifacts from yaml: {}", yamlName);
log.trace("************* Starting to add policies from yaml {}", yamlName);
Map<String, PolicyDefinition> policies = parsedToscaYamlInfo.getPolicies();
if (MapUtils.isNotEmpty(policies)) {
@@ -1603,34 +1602,34 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
log.trace("************* Finished to add policies from yaml {}", yamlName);
final NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
- nodeTypesArtifactsToCreate);
+ nodeTypesArtifactsToCreate);
final Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.CREATE, createdArtifacts,
- yamlName, csarInfo, resource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
+ yamlName, csarInfo, resource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
if (createArtifactsEither.isRight()) {
rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
- "error happened {}", createArtifactsEither.right().value());
+ "error happened {}", createArtifactsEither.right().value());
throw new ByResponseFormatComponentException(createArtifactsEither.right().value());
}
loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS, resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,
- "Finished to add artifacts from yaml: " + resource.getToscaResourceName());
+ "Finished to add artifacts from yaml: " + resource.getToscaResourceName());
final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum);
ASDCKpiApi.countCreatedResourcesKPI();
return resource;
} catch (final BusinessLogicException e) {
log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, ResourceBusinessLogic.class.getName(),
- "An error has occurred during resource and resource instance creation", e);
+ "An error has occurred during resource and resource instance creation", e);
rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
throw new ByResponseFormatComponentException(e.getResponseFormat());
} catch (final ComponentException e) {
log.error(EcompLoggerErrorCode.SCHEMA_ERROR, ResourceBusinessLogic.class.getName(),
- "An error has occurred during resource and resource instance creation", e);
+ "An error has occurred during resource and resource instance creation", e);
rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
throw new ByResponseFormatComponentException(e.getResponseFormat());
} catch (final Exception e) {
log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, ResourceBusinessLogic.class.getName(),
- "An error has occurred during resource and resource instance creation", e);
+ "An error has occurred during resource and resource instance creation", e);
rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
} finally {
@@ -1649,9 +1648,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
for (Map.Entry<String, UploadComponentInstanceInfo> instance : instances.entrySet()) {
if (isNotEmpty(instance.getValue().getArtifacts()) || instance.getValue().getArtifacts() != null) {
Map<String, UploadArtifactInfo> artifactsMap = instance.getValue().getArtifacts()
- .get(ToscaTagNamesEnum.ARTIFACTS.getElementName());
+ .get(ToscaTagNamesEnum.ARTIFACTS.getElementName());
if (isNotEmpty(artifactsMap) || artifactsMap != null) {
- for (Map.Entry<String , UploadArtifactInfo> artifact : artifactsMap.entrySet()) {
+ for (Map.Entry<String, UploadArtifactInfo> artifact : artifactsMap.entrySet()) {
if (artifact.getValue().getType().equals(Constants.ASD_DEPLOYMENT_ITEM)) {
GroupDefinition groupDefinition = new GroupDefinition();
groupDefinition.setName(artifact.getKey());
@@ -1706,7 +1705,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
private boolean processSubstitutableAsNodeType(final Resource resource, final ParsedToscaYamlInfo parsedToscaYamlInfo) {
return !resource.getResourceType().isAtomicType() && StringUtils.isNotEmpty(resource.getModel())
- && parsedToscaYamlInfo.getSubstitutionMappingNodeType() != null;
+ && parsedToscaYamlInfo.getSubstitutionMappingNodeType() != null;
}
private Map<String, UploadComponentInstanceInfo> getInstancesToCreate(final ParsedToscaYamlInfo parsedToscaYamlInfo) {
@@ -1718,8 +1717,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return parsedToscaYamlInfo.getInstances();
}
return parsedToscaYamlInfo.getInstances().entrySet().stream()
- .filter(entry -> !parsedToscaYamlInfo.getSubstitutionMappingNodeType().equals(entry.getValue().getType()))
- .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
+ .filter(entry -> !parsedToscaYamlInfo.getSubstitutionMappingNodeType().equals(entry.getValue().getType()))
+ .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
private void rollback(boolean inTransaction, Resource resource, List<ArtifactDefinition> createdArtifacts,
@@ -1760,7 +1759,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
List<InputDefinition> inputs = resource.getInputs();
if (MapUtils.isNotEmpty(groups)) {
groups.values().stream().filter(g -> isNotEmpty(g.getProperties())).flatMap(g -> g.getProperties().stream())
- .forEach(p -> handleGetInputs(p, inputs));
+ .forEach(p -> handleGetInputs(p, inputs));
}
}
@@ -1774,7 +1773,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (inputs == null || inputs.isEmpty()) {
log.debug("Failed to add property {} to group. Inputs list is empty ", property);
rollbackWithException(ActionStatus.INPUTS_NOT_FOUND,
- property.getGetInputValues().stream().map(GetInputValueDataDefinition::getInputName).collect(toList()).toString());
+ property.getGetInputValues().stream().map(GetInputValueDataDefinition::getInputName).collect(toList()).toString());
}
ListIterator<GetInputValueDataDefinition> getInputValuesIter = property.getGetInputValues().listIterator();
while (getInputValuesIter.hasNext()) {
@@ -1868,7 +1867,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
List<GroupDefinition> groupsToDelete) {
for (GroupDefinition group : groupsFromResource) {
Optional<GroupDefinition> op = groupsAsList.stream().filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName()))
- .findAny();
+ .findAny();
if (op.isEmpty() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) {
groupsToDelete.add(group);
}
@@ -1879,7 +1878,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
List<GroupDefinition> groupsToUpdate, List<GroupDefinition> groupsToCreate) {
for (GroupDefinition group : groupsAsList) {
Optional<GroupDefinition> op = groupsFromResource.stream().filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName()))
- .findAny();
+ .findAny();
if (op.isPresent()) {
GroupDefinition groupToUpdate = op.get();
groupToUpdate.setMembers(group.getMembers());
@@ -1898,7 +1897,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, resource);
if (createInputs.isRight()) {
loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
- "failed to add inputs from yaml: {}", createInputs.right().value());
+ "failed to add inputs from yaml: {}", createInputs.right().value());
throw new ByResponseFormatComponentException(createInputs.right().value());
}
resource.setInputs(createInputs.left().value());
@@ -1929,13 +1928,13 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
final List<PropertyDefinition> resourceProperties = resource.getProperties();
for (PropertyDefinition propertyDefinition : resourceProperties) {
final Either<PropertyDefinition, StorageOperationStatus> addPropertyEither = toscaOperationFacade
- .addPropertyToComponent(propertyDefinition.getName(), propertyDefinition, resource);
+ .addPropertyToComponent(propertyDefinition, resource);
if (addPropertyEither.isRight()) {
final String error = String.format("failed to add properties from yaml: {}", addPropertyEither.right().value());
loggerSupportability.log(LoggerSupportabilityActions.CREATE_PROPERTIES, resource.getComponentMetadataForSupportLog(),
- StatusCode.ERROR,
- error);
+ StatusCode.ERROR,
+ error);
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addPropertyEither.right().value()), error);
}
}
@@ -1971,22 +1970,22 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (CollectionUtils.isEmpty(componentInstances)) {
String membersAstString = String.join(",", compInstancesNames);
log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", membersAstString,
- groupName, component.getNormalizedName());
+ groupName, component.getNormalizedName());
throw new ByActionStatusComponentException(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
- component.getNormalizedName(), getComponentTypeForResponse(component));
+ component.getNormalizedName(), getComponentTypeForResponse(component));
}
// Find all component instances with the member names
Map<String, String> memberNames = componentInstances.stream().collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> "")));
Map<String, String> relevantInstances = memberNames.entrySet().stream().filter(n -> compInstancesNames.contains(n.getKey()))
- .collect(toMap(Entry::getKey, Entry::getValue));
+ .collect(toMap(Entry::getKey, Entry::getValue));
if (relevantInstances.size() != compInstancesNames.size()) {
List<String> foundMembers = new ArrayList<>(relevantInstances.keySet());
foundMembers.forEach(compInstancesNames::remove);
String membersAstString = String.join(",", compInstancesNames);
log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, groupName, component.getNormalizedName());
throw new ByActionStatusComponentException(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
- component.getNormalizedName(), getComponentTypeForResponse(component));
+ component.getNormalizedName(), getComponentTypeForResponse(component));
}
updatedGroupDefinition.setMembers(relevantInstances);
}
@@ -2042,12 +2041,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
// are groups
List<String> currGroupFilteredMembers = currGroupMembers.stream().
- // Keep Only Elements of type group and not Resource Instances
- filter(allGroups::containsKey).
- // Add Filtered Elements to main Set
- peek(allGroupMembers::add).
- // Collect results
- collect(toList());
+ // Keep Only Elements of type group and not Resource Instances
+ filter(allGroups::containsKey).
+ // Add Filtered Elements to main Set
+ peek(allGroupMembers::add).
+ // Collect results
+ collect(toList());
// Recursively call the method for all the filtered group members
for (String innerGroupName : currGroupFilteredMembers) {
fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers);
@@ -2067,10 +2066,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (!stop) {
final Set<String> allMembers = allGroups.get(groupName).getMembers().keySet();
Set<String> membersOfTypeGroup = allMembers.stream().
- // Filter In Only Group members
- filter(allGroups::containsKey).
- // Collect
- collect(toSet());
+ // Filter In Only Group members
+ filter(allGroups::containsKey).
+ // Collect
+ collect(toSet());
stop = allGroupMembers.containsAll(membersOfTypeGroup);
}
return stop;
@@ -2084,16 +2083,16 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
String nodeName, final String substitutableAsNodeType) {
log.debug("************* Going to create all nodes {}", yamlName);
handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts, nodeTypesInfo,
- csarInfo, nodeName, substitutableAsNodeType);
+ csarInfo, nodeName, substitutableAsNodeType);
log.debug("************* Finished to create all nodes {}", yamlName);
log.debug("************* Going to create all resource instances {}", yamlName);
Map<String, Resource> existingNodeTypesByResourceNames = new HashMap<>();
resource = createResourceInstances(yamlName, resource, null, uploadComponentInstanceInfoMap, csarInfo.getCreatedNodes(),
- existingNodeTypesByResourceNames);
+ existingNodeTypesByResourceNames);
log.debug("************* Finished to create all resource instances {}", yamlName);
log.debug("************* Going to create all relations {}", yamlName);
resource = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, null, uploadComponentInstanceInfoMap,
- existingNodeTypesByResourceNames);
+ existingNodeTypesByResourceNames);
log.debug("************* Finished to create all relations {}", yamlName);
log.debug("************* Going to create positions {}", yamlName);
compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier().getUserId());
@@ -2121,7 +2120,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
for (Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
if (nodeTypeEntry.getValue().isNested() && !nodeTypeAlreadyExists(nodeTypeEntry.getKey(), resource.getModel())) {
handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
- nodeTypeEntry.getKey());
+ nodeTypeEntry.getKey());
log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
}
}
@@ -2133,15 +2132,15 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
}
createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle,
- nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, substitutableAsNodeType);
+ nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, substitutableAsNodeType);
} catch (ComponentException e) {
ResponseFormat responseFormat =
- e.getResponseFormat() != null ? e.getResponseFormat() : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
+ e.getResponseFormat() != null ? e.getResponseFormat() : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
throw e;
} catch (StorageException e) {
ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
throw e;
}
@@ -2172,31 +2171,31 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
// Specific Behavior for license artifacts
createOrUpdateSingleNonMetaArtifact(resource, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL,
- Constants.VENDOR_LICENSE_MODEL, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
- Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId,
- artifactOperation, null, true, shouldLock, inTransaction);
+ Constants.VENDOR_LICENSE_MODEL, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
+ Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId,
+ artifactOperation, null, true, shouldLock, inTransaction);
createOrUpdateSingleNonMetaArtifact(resource, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
- ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL,
- Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, artifactOperation, null, true, shouldLock,
- inTransaction);
+ ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL,
+ Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, artifactOperation, null, true, shouldLock,
+ inTransaction);
Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource, createdArtifacts, shouldLock,
- inTransaction, artifactOperation);
+ inTransaction, artifactOperation);
if (eitherCreateResult.isRight()) {
return Either.right(eitherCreateResult.right().value());
}
Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils
- .getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
+ .getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
if (artifacsMetaCsarStatus.isLeft()) {
String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
Either<Resource, ResponseFormat> createArtifactsFromCsar;
if (artifactOperation.isCreateOrLink()) {
createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic
- .createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts);
+ .createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts);
} else {
Either<Component, ResponseFormat> result = csarArtifactsAndGroupsBusinessLogic
- .updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock,
- inTransaction);
+ .updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock,
+ inTransaction);
if ((result.left().value() instanceof Resource) && result.isLeft()) {
Resource service1 = (Resource) result.left().value();
createArtifactsFromCsar = Either.left(service1);
@@ -2229,7 +2228,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (operation.isUpdate() || operation.isDelete()) {
if (isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) {
Either<ArtifactDefinition, ResponseFormat> handleDelete = artifactsBusinessLogic
- .handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), resource, shouldLock, inTransaction);
+ .handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), resource, shouldLock, inTransaction);
if (handleDelete.isRight()) {
result = Either.right(handleDelete.right().value());
} else {
@@ -2249,14 +2248,14 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
if (artifactFileBytes != null) {
Map<String, Object> vendorLicenseModelJson = ArtifactUtils
- .buildJsonForUpdateArtifact(artifactId, artifactFileName, artifactType, artifactGroupType, artifactLabel, artifactDisplayName,
- artifactDescription, artifactFileBytes, null, isFromCsar);
+ .buildJsonForUpdateArtifact(artifactId, artifactFileName, artifactType, artifactGroupType, artifactLabel, artifactDisplayName,
+ artifactDescription, artifactFileBytes, null, isFromCsar);
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic
- .createOrUpdateCsarArtifactFromJson(resource, csarInfo.getModifier(), vendorLicenseModelJson, operation);
+ .createOrUpdateCsarArtifactFromJson(resource, csarInfo.getModifier(), vendorLicenseModelJson, operation);
addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
if (eitherNonMetaArtifacts.isRight()) {
BeEcompErrorManager.getInstance().logInternalFlowError("UploadLicenseArtifact",
- "Failed to upload license artifact: " + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(), ErrorSeverity.WARNING);
+ "Failed to upload license artifact: " + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(), ErrorSeverity.WARNING);
return Either.right(eitherNonMetaArtifacts.right().value());
}
ArtifactDefinition artifactDefinition = eitherNonMetaArtifacts.left().value().left().value();
@@ -2296,8 +2295,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Either<List<NonMetaArtifactInfo>, String> artifactPathAndNameList = getValidArtifactNames(csarInfo, collectedWarningMessages);
if (artifactPathAndNameList.isRight()) {
return Either.right(
- getComponentsUtils().getResponseFormatByArtifactId(ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right().value(),
- VALID_CHARACTERS_ARTIFACT_NAME));
+ getComponentsUtils().getResponseFormatByArtifactId(ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right().value(),
+ VALID_CHARACTERS_ARTIFACT_NAME));
}
EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
if (artifactOperation.isCreateOrLink()) {
@@ -2305,7 +2304,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left().value());
} else {
Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(
- resource, artifactPathAndNameList.left().value(), csarInfo.getModifier());
+ resource, artifactPathAndNameList.left().value(), csarInfo.getModifier());
if (findVfCsarArtifactsToHandleRes.isRight()) {
resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value());
}
@@ -2334,21 +2333,21 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle) {
for (Entry<ArtifactOperationEnum, List<NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle.entrySet()) {
Optional<ResponseFormat> optionalCreateInDBError =
- // Stream of artifacts to be created
- currArtifactOperationPair.getValue().stream()
- // create each artifact
- .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(), e.getArtifactName(), e.getArtifactType(),
- e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(), CsarUtils.ARTIFACT_CREATED_FROM_CSAR,
- e.getArtifactUniqueId(), new ArtifactOperationInfo(false, false, currArtifactOperationPair.getKey()), createdArtifacts,
- e.isFromCsar(), shouldLock, inTransaction))
- // filter in only error
- .filter(Either::isRight).
- // Convert the error from either to
-
- // ResponseFormat
- map(e -> e.right().value()).
- // Check if an error occurred
- findAny();
+ // Stream of artifacts to be created
+ currArtifactOperationPair.getValue().stream()
+ // create each artifact
+ .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(), e.getArtifactName(), e.getArtifactType(),
+ e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(), CsarUtils.ARTIFACT_CREATED_FROM_CSAR,
+ e.getArtifactUniqueId(), new ArtifactOperationInfo(false, false, currArtifactOperationPair.getKey()), createdArtifacts,
+ e.isFromCsar(), shouldLock, inTransaction))
+ // filter in only error
+ .filter(Either::isRight).
+ // Convert the error from either to
+
+ // ResponseFormat
+ map(e -> e.right().value()).
+ // Check if an error occurred
+ findAny();
// Error found on artifact Creation
if (optionalCreateInDBError.isPresent()) {
resStatus = Either.right(optionalCreateInDBError.get());
@@ -2361,18 +2360,18 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
private Either<List<NonMetaArtifactInfo>, String> getValidArtifactNames(CsarInfo csarInfo,
Map<String, Set<List<String>>> collectedWarningMessages) {
List<NonMetaArtifactInfo> artifactPathAndNameList =
- // Stream of file paths contained in csar
- csarInfo.getCsar().entrySet().stream()
- // Filter in only VF artifact path location
- .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
- // Validate and add warnings
- .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), collectedWarningMessages))
- // Filter in Non Warnings
- .filter(Either::isLeft)
- // Convert from Either to NonMetaArtifactInfo
- .map(e -> e.left().value())
- // collect to List
- .collect(toList());
+ // Stream of file paths contained in csar
+ csarInfo.getCsar().entrySet().stream()
+ // Filter in only VF artifact path location
+ .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
+ // Validate and add warnings
+ .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), collectedWarningMessages))
+ // Filter in Non Warnings
+ .filter(Either::isLeft)
+ // Convert from Either to NonMetaArtifactInfo
+ .map(e -> e.left().value())
+ // collect to List
+ .collect(toList());
Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) {
@@ -2394,10 +2393,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
existingArtifacts.addAll(resource.getArtifacts().values());
}
existingArtifacts = existingArtifacts.stream()
- // filter MANDATORY artifacts, LICENSE artifacts and artifacts
+ // filter MANDATORY artifacts, LICENSE artifacts and artifacts
- // was created from HEAT.meta
- .filter(this::isNonMetaArtifact).collect(toList());
+ // was created from HEAT.meta
+ .filter(this::isNonMetaArtifact).collect(toList());
List<String> artifactsToIgnore = new ArrayList<>();
// collect IDs of Artifacts of VF which belongs to any group
if (resource.getGroups() != null) {
@@ -2408,8 +2407,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
});
}
existingArtifacts = existingArtifacts.stream()
- // filter artifacts which belongs to any group
- .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(toList());
+ // filter artifacts which belongs to any group
+ .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(toList());
return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user);
}
@@ -2419,7 +2418,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
private boolean isValidArtifactType(ArtifactDefinition artifact) {
return artifact.getArtifactType() != null && ArtifactTypeEnum.parse(artifact.getArtifactType()) != ArtifactTypeEnum.VENDOR_LICENSE
- && ArtifactTypeEnum.parse(artifact.getArtifactType()) != ArtifactTypeEnum.VF_LICENSE;
+ && ArtifactTypeEnum.parse(artifact.getArtifactType()) != ArtifactTypeEnum.VF_LICENSE;
}
private Resource createResourceInstancesRelations(User user, String yamlName, Resource resource, Resource oldResource,
@@ -2427,17 +2426,17 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Map<String, Resource> existingNodeTypesByResourceNames) {
log.debug("#createResourceInstancesRelations - Going to create relations ");
loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,
- "Start to create relations");
+ "Start to create relations");
List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
if (isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList) &&
- resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances {
+ resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances {
log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ",
- resource.getUniqueId(), yamlName);
+ resource.getUniqueId(), yamlName);
loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
- "No instances found in the resource: {}, is empty, yaml template file name: {}", resource.getName(), yamlName);
+ "No instances found in the resource: {}, is empty, yaml template file name: {}", resource.getName(), yamlName);
BeEcompErrorManager.getInstance()
- .logInternalDataError("createResourceInstancesRelations", "No instances found in a resource or nn yaml template. ",
- ErrorSeverity.ERROR);
+ .logInternalDataError("createResourceInstancesRelations", "No instances found in a resource or nn yaml template. ",
+ ErrorSeverity.ERROR);
throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
}
Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
@@ -2450,12 +2449,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
Resource finalResource = resource;
uploadResInstancesMap.values().forEach(
- i -> processComponentInstance(yamlName, finalResource, componentInstancesList,
- componentsUtils.getAllDataTypes(applicationDataTypeCache, resource.getModel()), instProperties, instCapabilities,
- instRequirements, instDeploymentArtifacts, instArtifacts, instAttributes, existingNodeTypesByResourceNames, instInputs, i));
+ i -> processComponentInstance(yamlName, finalResource, componentInstancesList,
+ componentsUtils.getAllDataTypes(applicationDataTypeCache, resource.getModel()), instProperties, instCapabilities,
+ instRequirements, instDeploymentArtifacts, instArtifacts, instAttributes, existingNodeTypesByResourceNames, instInputs, i));
resource.getComponentInstances().stream().filter(i -> !i.isCreatedFromCsar()).forEach(
- i -> processUiComponentInstance(oldResource, i, instCapabilities, instRequirements, instDeploymentArtifacts, instArtifacts,
- instProperties, instInputs, instAttributes));
+ i -> processUiComponentInstance(oldResource, i, instCapabilities, instRequirements, instDeploymentArtifacts, instArtifacts,
+ instProperties, instInputs, instAttributes));
associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties);
associateComponentInstanceInputsToComponent(yamlName, resource, instInputs);
associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts);
@@ -2467,14 +2466,14 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
handleSubstitutionMappings(resource, uploadResInstancesMap);
log.debug("************* in create relations, getResource start");
loggerSupportability
- .log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE, "create relations");
+ .log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE, "create relations");
Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaFullElement(resource.getUniqueId());
log.debug("************* in create relations, getResource end");
if (eitherGetResource.isRight()) {
loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
- "ERROR while create relations");
+ "ERROR while create relations");
throw new ByResponseFormatComponentException(
- componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource));
+ componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource));
}
return eitherGetResource.left().value();
}
@@ -2502,18 +2501,18 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
instArtifacts.put(instance.getUniqueId(), foundInstance.get().getArtifacts());
}
if (MapUtils.isNotEmpty(oldResource.getComponentInstancesProperties()) && CollectionUtils
- .isNotEmpty(oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId()))) {
+ .isNotEmpty(oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId()))) {
instProperties.put(instance.getUniqueId(), oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId()));
}
if (MapUtils.isNotEmpty(oldResource.getComponentInstancesInputs()) && CollectionUtils
- .isNotEmpty(oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId()))) {
+ .isNotEmpty(oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId()))) {
instInputs.put(instance.getUniqueId(), oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId()));
}
if (MapUtils.isNotEmpty(oldResource.getComponentInstancesAttributes()) && CollectionUtils
- .isNotEmpty(oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()))) {
+ .isNotEmpty(oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()))) {
instAttributes.put(instance.getUniqueId(),
- oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()).stream().map(AttributeDefinition::new)
- .collect(toList()));
+ oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()).stream().map(AttributeDefinition::new)
+ .collect(toList()));
}
}
}
@@ -2527,7 +2526,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
private void associateResourceInstances(String yamlName, Resource resource, List<RequirementCapabilityRelDef> relations) {
Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> relationsEither = toscaOperationFacade
- .associateResourceInstances(resource, resource.getUniqueId(), relations);
+ .associateResourceInstances(resource, resource.getUniqueId(), relations);
if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) {
StorageOperationStatus status = relationsEither.right().value();
log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(), status);
@@ -2580,7 +2579,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Map<String, List<ComponentInstanceInput>> instInputs) {
if (MapUtils.isNotEmpty(instInputs)) {
Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
- .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
+ .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
if (addInputToInst.isRight()) {
StorageOperationStatus addInputToInstError = addInputToInst.right().value();
log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(), addInputToInstError);
@@ -2602,11 +2601,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
private void associateComponentInstancePropertiesToComponent(String yamlName, Resource resource,
Map<String, List<ComponentInstanceProperty>> instProperties) {
Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
- .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
+ .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
if (addPropToInst.isRight()) {
loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
- "ERROR while associate compnent insatnce properties of resource: {} status is: {}", resource.getName(),
- addPropToInst.right().value());
+ "ERROR while associate compnent insatnce properties of resource: {} status is: {}", resource.getName(),
+ addPropToInst.right().value());
StorageOperationStatus storageOperationStatus = addPropToInst.right().value();
log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(), storageOperationStatus);
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageOperationStatus), yamlName);
@@ -2632,7 +2631,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
if (getResourceRes != null && getResourceRes.isRight()) {
ResponseFormat responseFormat = componentsUtils
- .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
throw new ByResponseFormatComponentException(responseFormat);
}
@@ -2652,8 +2651,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (currentCompInstance == null) {
log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), resource.getUniqueId());
BeEcompErrorManager.getInstance()
- .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, resource.getUniqueId(),
- ErrorSeverity.ERROR);
+ .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, resource.getUniqueId(),
+ ErrorSeverity.ERROR);
throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
}
ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
@@ -2682,12 +2681,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Map<String, List<ComponentInstanceInput>> instInputs,
UploadComponentInstanceInfo uploadComponentInstanceInfo) {
Optional<ComponentInstance> currentCompInstanceOpt = componentInstancesList.stream()
- .filter(i -> i.getName().equals(uploadComponentInstanceInfo.getName())).findFirst();
+ .filter(i -> i.getName().equals(uploadComponentInstanceInfo.getName())).findFirst();
if (currentCompInstanceOpt.isEmpty()) {
log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), resource.getUniqueId());
BeEcompErrorManager.getInstance()
- .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, resource.getUniqueId(),
- ErrorSeverity.ERROR);
+ .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, resource.getUniqueId(),
+ ErrorSeverity.ERROR);
throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
}
ComponentInstance currentCompInstance = currentCompInstanceOpt.get();
@@ -2710,7 +2709,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
if (originResource.getResourceType() != ResourceTypeEnum.CVFC) {
ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource, originResource,
- currentCompInstance, instProperties, allDataTypes);
+ currentCompInstance, instProperties, allDataTypes);
if (addPropertiesValueToRiRes.getStatus() != 200) {
throw new ByResponseFormatComponentException(addPropertiesValueToRiRes);
}
@@ -2723,12 +2722,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Resource originResource;
if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade
- .getToscaFullElement(currentCompInstance.getComponentUid());
+ .getToscaFullElement(currentCompInstance.getComponentUid());
if (getOriginResourceRes.isRight()) {
log.debug("failed to fetch resource with uniqueId {} and tosca component name {} status is {}", currentCompInstance.getComponentUid(),
- currentCompInstance.getToscaComponentName(), getOriginResourceRes);
+ currentCompInstance.getToscaComponentName(), getOriginResourceRes);
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()),
- currentCompInstance.getComponentUid());
+ currentCompInstance.getComponentUid());
}
originResource = getOriginResourceRes.left().value();
originCompMap.put(originResource.getUniqueId(), originResource);
@@ -2759,7 +2758,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Map<String, Map<String, UploadPropInfo>> newPropertiesMap,
Map<String, DataTypeDefinition> allDataTypes) {
originCapabilities.values().stream().flatMap(Collection::stream).filter(c -> newPropertiesMap.containsKey(c.getName()))
- .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()), allDataTypes));
+ .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()), allDataTypes));
}
private void addCapabilitiesProperties(Map<String, Map<String, UploadPropInfo>> newPropertiesMap, List<UploadCapInfo> capabilities) {
@@ -2807,17 +2806,17 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
StorageOperationStatus status = toscaOperationFacade.deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId());
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
log.debug("Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}",
- resource.getUniqueId(), status);
+ resource.getUniqueId(), status);
updateRes = Either.right(status);
}
if (updateRes == null) {
fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap, updatedInstCapabilities,
- updatedInstRequirements);
+ updatedInstRequirements);
status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements, resource);
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
log.debug(
- "Failed to associate capabilities and requirementss of resource {}, updated according to a substitution mapping. Status is {}",
- resource.getUniqueId(), status);
+ "Failed to associate capabilities and requirementss of resource {}, updated according to a substitution mapping. Status is {}",
+ resource.getUniqueId(), status);
updateRes = Either.right(status);
}
}
@@ -2839,11 +2838,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
});
final StorageOperationStatus status = toscaOperationFacade.updateCalculatedCapabilitiesRequirements(updatedInstCapabilities,
- updatedInstRequirements, resource);
+ updatedInstRequirements, resource);
if (status != StorageOperationStatus.OK) {
log.debug(
- "Failed to update capabilities and requirements of resource {}. Status is {}",
- resource.getUniqueId(), status);
+ "Failed to update capabilities and requirements of resource {}. Status is {}",
+ resource.getUniqueId(), status);
updateRes = Either.right(status);
}
@@ -2870,13 +2869,13 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (isNotEmpty(requirementsNamesToUpdate)) {
for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements().entrySet()) {
updatedRequirements.put(requirements.getKey(), requirements.getValue().stream().filter(
- r -> requirementsNamesToUpdate.containsKey(r.getName()) && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
- .map(r -> {
- r.setParentName(r.getName());
- r.setName(requirementsNamesToUpdate.get(r.getName()));
- updatedReqNames.add(r.getName());
- return r;
- }).collect(toList()));
+ r -> requirementsNamesToUpdate.containsKey(r.getName()) && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
+ .map(r -> {
+ r.setParentName(r.getName());
+ r.setName(requirementsNamesToUpdate.get(r.getName()));
+ updatedReqNames.add(r.getName());
+ return r;
+ }).collect(toList()));
}
}
if (isNotEmpty(updatedRequirements)) {
@@ -2885,22 +2884,22 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
private void setExternalRequirements(
- final Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements,
- final ComponentInstance instance, final Map<String, String> requirementsNamesToUpdate) {
+ final Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements,
+ final ComponentInstance instance, final Map<String, String> requirementsNamesToUpdate) {
final Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
final Set<String> updatedReqNames = new HashSet<>();
if (isNotEmpty(requirementsNamesToUpdate)) {
for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements().entrySet()) {
updatedRequirements.put(requirements.getKey(),
- requirements.getValue().stream()
- .filter(r -> requirementsNamesToUpdate.containsKey(r.getName())
- && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
- .map(r -> {
- r.setExternal(true);
- r.setExternalName(requirementsNamesToUpdate.get(r.getName()));
- updatedReqNames.add(r.getName());
- return r;
- }).collect(toList()));
+ requirements.getValue().stream()
+ .filter(r -> requirementsNamesToUpdate.containsKey(r.getName())
+ && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
+ .map(r -> {
+ r.setExternal(true);
+ r.setExternalName(requirementsNamesToUpdate.get(r.getName()));
+ updatedReqNames.add(r.getName());
+ return r;
+ }).collect(toList()));
}
}
if (isNotEmpty(updatedRequirements)) {
@@ -2909,22 +2908,22 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
private void setExternalCapabilities(
- final Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties,
- final ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
+ final Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties,
+ final ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
final Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
final Set<String> updatedCapNames = new HashSet<>();
if (isNotEmpty(capabilitiesNamesToUpdate)) {
for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities().entrySet()) {
updatedCapabilities.put(requirements.getKey(),
- requirements.getValue().stream()
- .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName())
- && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
- .map(c -> {
- c.setExternal(true);
- c.setExternalName(capabilitiesNamesToUpdate.get(c.getName()));
- updatedCapNames.add(c.getName());
- return c;
- }).collect(toList()));
+ requirements.getValue().stream()
+ .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName())
+ && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
+ .map(c -> {
+ c.setExternal(true);
+ c.setExternalName(capabilitiesNamesToUpdate.get(c.getName()));
+ updatedCapNames.add(c.getName());
+ return c;
+ }).collect(toList()));
}
}
if (isNotEmpty(updatedCapabilities)) {
@@ -2939,13 +2938,13 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (isNotEmpty(capabilitiesNamesToUpdate)) {
for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities().entrySet()) {
updatedCapabilities.put(requirements.getKey(), requirements.getValue().stream().filter(
- c -> capabilitiesNamesToUpdate.containsKey(c.getName()) && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
- .map(c -> {
- c.setParentName(c.getName());
- c.setName(capabilitiesNamesToUpdate.get(c.getName()));
- updatedCapNames.add(c.getName());
- return c;
- }).collect(toList()));
+ c -> capabilitiesNamesToUpdate.containsKey(c.getName()) && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
+ .map(c -> {
+ c.setParentName(c.getName());
+ c.setName(capabilitiesNamesToUpdate.get(c.getName()));
+ updatedCapNames.add(c.getName());
+ return c;
+ }).collect(toList()));
}
}
if (isNotEmpty(updatedCapabilities)) {
@@ -2966,8 +2965,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (currentCompInstance == null) {
log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), resource.getUniqueId());
BeEcompErrorManager.getInstance()
- .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE, resource.getUniqueId(),
- ErrorSeverity.ERROR);
+ .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE, resource.getUniqueId(),
+ ErrorSeverity.ERROR);
return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
}
String resourceInstanceId = currentCompInstance.getUniqueId();
@@ -2978,19 +2977,19 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
log.debug("Going to create relation {}", uploadRegInfo.getName());
loggerSupportability
- .log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,
- "Started to create relations on instance: {}", uploadRegInfo.getName());
+ .log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,
+ "Started to create relations on instance: {}", uploadRegInfo.getName());
String regName = uploadRegInfo.getName();
RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
regCapRelDef.setFromNode(resourceInstanceId);
log.debug("try to find available requirement {} ", regName);
Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName, yamlName, nodesInfoValue,
- currentCompInstance, uploadRegInfo.getCapabilityName());
+ currentCompInstance, uploadRegInfo.getCapabilityName());
if (eitherReqStatus.isRight()) {
log.debug("failed to find available requirement {} status is {}", regName, eitherReqStatus.right().value());
loggerSupportability
- .log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
- "ERROR while search available requirement {} status is: {}", regName, eitherReqStatus.right().value());
+ .log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+ "ERROR while search available requirement {} status is: {}", regName, eitherReqStatus.right().value());
return eitherReqStatus.right().value();
}
RequirementDefinition validReq = eitherReqStatus.left().value();
@@ -3015,11 +3014,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (currentCapCompInstance == null) {
log.debug("The component instance with name {} not found on resource {} ", uploadRegInfo.getNode(), resource.getUniqueId());
loggerSupportability
- .log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
- "ERROR component instance with name: {} not found on resource: {}", uploadRegInfo.getNode(), resource.getUniqueId());
+ .log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+ "ERROR component instance with name: {} not found on resource: {}", uploadRegInfo.getNode(), resource.getUniqueId());
BeEcompErrorManager.getInstance()
- .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE, resource.getUniqueId(),
- ErrorSeverity.ERROR);
+ .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE, resource.getUniqueId(),
+ ErrorSeverity.ERROR);
return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
}
regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
@@ -3027,14 +3026,14 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo);
if (aviableCapForRel == null) {
log.debug("aviable capability was not found. req name is {} component instance is {}", validReq.getName(),
- currentCapCompInstance.getUniqueId());
+ currentCapCompInstance.getUniqueId());
loggerSupportability
- .log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
- "ERROR available capability was not found. req name is: {} component instance is: {}", validReq.getName(),
- currentCapCompInstance.getUniqueId());
+ .log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+ "ERROR available capability was not found. req name is: {} component instance is: {}", validReq.getName(),
+ currentCapCompInstance.getUniqueId());
BeEcompErrorManager.getInstance().logInternalDataError(
- "aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance
- .getUniqueId(), resource.getUniqueId(), ErrorSeverity.ERROR);
+ "aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance
+ .getUniqueId(), resource.getUniqueId(), ErrorSeverity.ERROR);
return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
}
reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
@@ -3063,7 +3062,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (CollectionUtils.isEmpty(originResource.getInputs())) {
log.debug("failed to find properties ");
loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
- "ERROR while try to find properties");
+ "ERROR while try to find properties");
throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND);
}
originResource.getInputs().forEach(p -> addInput(currPropertiesMap, p));
@@ -3082,7 +3081,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
String propName = propertyInfo.getName();
if (!currPropertiesMap.containsKey(propName)) {
loggerSupportability.log(LoggerSupportabilityActions.PROPERTY, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
- "ERROR failed to find property: {}", propName);
+ "ERROR failed to find property: {}", propName);
log.debug("failed to find property {} ", propName);
throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, propName);
}
@@ -3109,16 +3108,16 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
List<InputDefinition> inputs = resource.getInputs();
if (CollectionUtils.isEmpty(inputs)) {
loggerSupportability.log(LoggerSupportabilityActions.PROPERTY, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
- "ERROR Failed to add property: " + propName + " to resource instance: {}. Inputs list is empty ",
- currentCompInstance.getUniqueId());
+ "ERROR Failed to add property: " + propName + " to resource instance: {}. Inputs list is empty ",
+ currentCompInstance.getUniqueId());
log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property,
- currentCompInstance.getUniqueId());
+ currentCompInstance.getUniqueId());
throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
}
Optional<InputDefinition> optional = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findAny();
if (optional.isEmpty()) {
loggerSupportability.log(LoggerSupportabilityActions.PROPERTY, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
- "ERROR Failed to find input: " + getInput.getInputName());
+ "ERROR Failed to find input: " + getInput.getInputName());
log.debug("Failed to find input {} ", getInput.getInputName());
// @@TODO error message
throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
@@ -3167,7 +3166,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
List<PropertyDefinition> listFromMap = originResource.getProperties();
if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) {
loggerSupportability.log(LoggerSupportabilityActions.PROPERTY, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
- "ERROR Failed to find properties");
+ "ERROR Failed to find properties");
log.debug("failed to find properties");
return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
}
@@ -3188,7 +3187,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (!currPropertiesMap.containsKey(propName)) {
log.debug("failed to find property {} ", propName);
loggerSupportability.log(LoggerSupportabilityActions.PROPERTY, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
- "ERROR Failed to find property: {}", propName);
+ "ERROR Failed to find property: {}", propName);
return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
}
PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
@@ -3215,10 +3214,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (inputs == null || inputs.isEmpty()) {
log.debug("Failed to add property {} to instance. Inputs list is empty ", property);
loggerSupportability
- .log(LoggerSupportabilityActions.PROPERTY, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
- "Failed to add property: {} to instance. Inputs list is empty", propName);
+ .log(LoggerSupportabilityActions.PROPERTY, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+ "Failed to add property: {} to instance. Inputs list is empty", propName);
rollbackWithException(ActionStatus.INPUTS_NOT_FOUND,
- property.getGetInputValues().stream().map(GetInputValueDataDefinition::getInputName).collect(toList()).toString());
+ property.getGetInputValues().stream().map(GetInputValueDataDefinition::getInputName).collect(toList()).toString());
}
Either<InputDefinition, RuntimeException> inputEither = findInputByName(inputs, getInput);
if (inputEither.isRight()) {
@@ -3261,7 +3260,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq, ComponentInstance currentCapCompInstance,
UploadReqInfo uploadReqInfo) {
if (null == uploadReqInfo.getCapabilityName() || validReq.getCapability()
- .equals(uploadReqInfo.getCapabilityName())) {// get
+ .equals(uploadReqInfo.getCapabilityName())) {// get
// by
@@ -3281,7 +3280,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return null;
}
Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability()).stream()
- .filter(p -> p.getName().equals(uploadReqInfo.getCapabilityName())).findAny();
+ .filter(p -> p.getName().equals(uploadReqInfo.getCapabilityName())).findAny();
if (capByName.isEmpty()) {
return null;
}
@@ -3382,8 +3381,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
if (validRegDef == null) {
ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(),
- uploadComponentInstanceInfo.getType());
+ .getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(),
+ uploadComponentInstanceInfo.getType());
return Either.right(responseFormat);
}
return Either.left(validRegDef);
@@ -3403,12 +3402,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
uploadResInstancesMap.values().forEach(
- i -> createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap, existingNodeTypesByResourceNames, resourcesInstancesMap));
+ i -> createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap, existingNodeTypesByResourceNames, resourcesInstancesMap));
if (oldResource != null && oldResource.getResourceType() != ResourceTypeEnum.CVFC && oldResource.getComponentInstances() != null) {
Map<String, Resource> existingNodeTypesByUids = existingNodeTypesByResourceNames.values().stream()
- .collect(toMap(Resource::getUniqueId, r -> r));
+ .collect(toMap(Resource::getUniqueId, r -> r));
oldResource.getComponentInstances().stream().filter(i -> !i.isCreatedFromCsar())
- .forEach(uiInst -> resourcesInstancesMap.put(uiInst, getOriginResource(existingNodeTypesByUids, uiInst)));
+ .forEach(uiInst -> resourcesInstancesMap.put(uiInst, getOriginResource(existingNodeTypesByUids, uiInst)));
}
if (isNotEmpty(resourcesInstancesMap)) {
try {
@@ -3417,14 +3416,14 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) {
log.debug("Failed to add component instances to container component {}", resource.getName());
ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(exp.getStorageOperationStatus()));
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(exp.getStorageOperationStatus()));
eitherResource = Either.right(responseFormat);
throw new ByResponseFormatComponentException(eitherResource.right().value());
}
}
}
if (CollectionUtils.isEmpty(resource.getComponentInstances()) &&
- resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
+ resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
log.debug("Error when create resource instance from csar. ComponentInstances list empty");
BeEcompErrorManager.getInstance().logBeDaoSystemError("Error when create resource instance from csar. ComponentInstances list empty");
throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
@@ -3454,32 +3453,32 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
UploadNodeFilterInfo uploadNodeFilterInfo = uploadComponentInstanceInfo.getUploadNodeFilterInfo();
if (uploadNodeFilterInfo != null) {
componentInstance
- .setNodeFilter(new CINodeFilterUtils().getNodeFilterDataDefinition(uploadNodeFilterInfo, componentInstance.getUniqueId()));
+ .setNodeFilter(new CINodeFilterUtils().getNodeFilterDataDefinition(uploadNodeFilterInfo, componentInstance.getUniqueId()));
}
ComponentTypeEnum containerComponentType = resource.getComponentType();
NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
if (containerNodeType == NodeTypeEnum.Resource && isNotEmpty(uploadComponentInstanceInfo.getCapabilities()) && isNotEmpty(
- refResource.getCapabilities())) {
+ refResource.getCapabilities())) {
setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
Map<String, List<CapabilityDefinition>> validComponentInstanceCapabilities = getValidComponentInstanceCapabilities(
- refResource.getUniqueId(), refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
+ refResource.getUniqueId(), refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
componentInstance.setCapabilities(validComponentInstanceCapabilities);
}
if (isNotEmpty(uploadComponentInstanceInfo.getArtifacts())) {
Map<String, Map<String, UploadArtifactInfo>> artifacts = uploadComponentInstanceInfo.getArtifacts();
Map<String, ToscaArtifactDataDefinition> toscaArtifacts = new HashMap<>();
Map<String, Map<String, UploadArtifactInfo>> arts = artifacts.entrySet().stream()
- .filter(e -> e.getKey().contains(TypeUtils.ToscaTagNamesEnum.ARTIFACTS.getElementName()))
- .collect(Collectors.toMap(Entry::getKey, Entry::getValue));
+ .filter(e -> e.getKey().contains(TypeUtils.ToscaTagNamesEnum.ARTIFACTS.getElementName()))
+ .collect(Collectors.toMap(Entry::getKey, Entry::getValue));
Map<String, UploadArtifactInfo> artifact = arts.get(TypeUtils.ToscaTagNamesEnum.ARTIFACTS.getElementName());
for (Map.Entry<String, UploadArtifactInfo> entry : artifact.entrySet()) {
ToscaArtifactDataDefinition to = new ToscaArtifactDataDefinition();
to.setFile(entry.getValue().getFile());
to.setType(entry.getValue().getType());
- if(isNotEmpty(entry.getValue().getProperties())) {
+ if (isNotEmpty(entry.getValue().getProperties())) {
Map<String, Object> newPropertiesMap = new HashMap<>();
List<UploadPropInfo> artifactPropsInfo = entry.getValue().getProperties();
- for(UploadPropInfo propInfo: artifactPropsInfo) {
+ for (UploadPropInfo propInfo : artifactPropsInfo) {
newPropertiesMap.put(propInfo.getName(), propInfo.getValue());
}
to.setProperties(newPropertiesMap);
@@ -3490,9 +3489,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
log.debug("createResourceInstances - not found lates version for resource instance with name {} and type {}",
- uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
+ uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(),
- uploadComponentInstanceInfo.getType());
+ uploadComponentInstanceInfo.getType());
}
Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
componentInstance.setName(uploadComponentInstanceInfo.getName());
@@ -3523,18 +3522,18 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
private Resource validateResourceInstanceBeforeCreate(String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo,
Map<String, Resource> nodeNamespaceMap, Resource resource) {
log.debug("validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type {} before create",
- uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
+ uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
Resource refResource;
if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType());
} else {
Either<Resource, StorageOperationStatus> findResourceEither = StringUtils.isEmpty(resource.getModel()) ?
- toscaOperationFacade.getByToscaResourceNameMatchingVendorRelease(uploadComponentInstanceInfo.getType(),
- ((ResourceMetadataDataDefinition) resource.getComponentMetadataDefinition().getMetadataDataDefinition()).getVendorRelease()):
- toscaOperationFacade.getLatestByToscaResourceNameAndModel(uploadComponentInstanceInfo.getType(), resource.getModel());
+ toscaOperationFacade.getByToscaResourceNameMatchingVendorRelease(uploadComponentInstanceInfo.getType(),
+ ((ResourceMetadataDataDefinition) resource.getComponentMetadataDefinition().getMetadataDataDefinition()).getVendorRelease()) :
+ toscaOperationFacade.getLatestByToscaResourceNameAndModel(uploadComponentInstanceInfo.getType(), resource.getModel());
if (findResourceEither.isRight()) {
log.debug("validateResourceInstanceBeforeCreate - not found latest version for resource instance with name {} and type {}",
- uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
+ uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
}
refResource = findResourceEither.left().value();
@@ -3543,15 +3542,15 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState();
if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
log.debug(
- "validateResourceInstanceBeforeCreate - component instance of component {} can not be created because the component is in an illegal state {}.",
- refResource.getName(), componentState);
+ "validateResourceInstanceBeforeCreate - component instance of component {} can not be created because the component is in an illegal state {}.",
+ refResource.getName(), componentState);
throw new ByActionStatusComponentException(ActionStatus.ILLEGAL_COMPONENT_STATE, refResource.getComponentType().getValue(),
- refResource.getName(), componentState);
+ refResource.getName(), componentState);
}
if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) {
log.debug("validateResourceInstanceBeforeCreate - ref resource type is {} ", refResource.getResourceType());
throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(),
- uploadComponentInstanceInfo.getType());
+ uploadComponentInstanceInfo.getType());
}
return refResource;
}
@@ -3561,7 +3560,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
boolean failed = false;
try {
if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed && lifecycleBusinessLogic
- .isFirstCertification(resource.getVersion())) {
+ .isFirstCertification(resource.getVersion())) {
nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
}
if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
@@ -3588,7 +3587,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
private Resource nodeFullCertification(String uniqueId, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction,
boolean needLock) {
Either<Resource, ResponseFormat> resourceResponse = lifecycleBusinessLogic
- .changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo, inTransaction, needLock);
+ .changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo, inTransaction, needLock);
if (resourceResponse.isRight()) {
throw new ByResponseFormatComponentException(resourceResponse.right().value());
}
@@ -3609,15 +3608,15 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
final boolean isNestedResource = isNestedResourceUpdate(csarInfo, nodeName);
final String resourceName = resource.getToscaResourceName();
final Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade
- .getLatestByToscaResourceNameAndModel(resourceName, resource.getModel());
+ .getLatestByToscaResourceNameAndModel(resourceName, resource.getModel());
if (latestByToscaName.isLeft() && Objects.nonNull(latestByToscaName.left().value())) {
final Resource foundResource = latestByToscaName.left().value();
// we don't allow updating names of top level types
if (!isNestedResource && !StringUtils.equals(resource.getName(), foundResource.getName())) {
BeEcompErrorManager.getInstance()
- .logBeComponentMissingError("Create / Update resource by import", ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
+ .logBeComponentMissingError("Create / Update resource by import", ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
log.debug("resource already exist new name={} old name={} same type={}", resource.getName(), foundResource.getName(),
- resource.getToscaResourceName());
+ resource.getToscaResourceName());
final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
throwComponentException(responseFormat);
@@ -3633,7 +3632,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
StorageOperationStatus status = latestByToscaName.right().value();
log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
ResponseFormat responseFormat = componentsUtils
- .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(latestByToscaName.right().value()), resource);
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(latestByToscaName.right().value()), resource);
componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
throwComponentException(responseFormat);
}
@@ -3649,12 +3648,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
final CsarInfo csarInfo, final boolean isNested,
final String nodeName) {
final Either<Component, StorageOperationStatus> latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(
- buildNestedToscaResourceName(resource.getResourceType().name(), csarInfo.getVfResourceName(), nodeName).getRight(), resource.getModel());
+ buildNestedToscaResourceName(resource.getResourceType().name(), csarInfo.getVfResourceName(), nodeName).getRight(), resource.getModel());
if (latestByToscaName.isLeft()) {
final Resource nestedResource = (Resource) latestByToscaName.left().value();
log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
final Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(nestedResource, resource,
- ValidationUtils.hasBeenCertified(nestedResource.getVersion()));
+ ValidationUtils.hasBeenCertified(nestedResource.getVersion()));
if (eitherValidation.isRight()) {
return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
}
@@ -3688,7 +3687,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
boolean inTransaction, boolean needLock, boolean isNested) {
String lockedResourceId = oldResource.getUniqueId();
log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId, oldResource.getVersion(),
- oldResource.getLifecycleState());
+ oldResource.getLifecycleState());
ImmutablePair<Resource, ActionStatus> resourcePair = null;
try {
lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import");
@@ -3749,7 +3748,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade.overrideComponent(newResource, oldResource);
if (overrideResource.isRight()) {
ResponseFormat responseFormat = componentsUtils
- .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(overrideResource.right().value()), newResource);
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(overrideResource.right().value()), newResource);
componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE);
throwComponentException(responseFormat);
}
@@ -3757,7 +3756,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
log.debug("Resource updated successfully!!!");
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
- ResourceVersionInfo.newBuilder().state(oldResource.getLifecycleState().name()).version(oldResource.getVersion()).build());
+ ResourceVersionInfo.newBuilder().state(oldResource.getLifecycleState().name()).version(oldResource.getVersion()).build());
resourcePair = new ImmutablePair<>(overrideResource.left().value(), ActionStatus.OK);
return resourcePair;
} finally {
@@ -3813,19 +3812,19 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
newResource.setGroups(groupForUpdate);
}
if (newResource.getResourceType().isAtomicType() && !newResource.getName().equals("Root")
- && newResource.getResourceType() != ResourceTypeEnum.CVFC) {
+ && newResource.getResourceType() != ResourceTypeEnum.CVFC) {
ResourceTypeEnum updatedResourceType = newResource.getResourceType();
Optional<Component> derivedFromResourceOptional = getParentComponent(newResource);
if (derivedFromResourceOptional.isPresent() && derivedFromResourceOptional.get().getComponentType() == ComponentTypeEnum.RESOURCE) {
Resource parentResource = (Resource) derivedFromResourceOptional.get();
if (!(parentResource.isAbstract() && (ResourceTypeEnum.VFC == parentResource.getResourceType()
- || ResourceTypeEnum.ABSTRACT == parentResource.getResourceType())) && parentResource.getResourceType() != updatedResourceType
- && oldResource.getResourceType() != updatedResourceType) {
+ || ResourceTypeEnum.ABSTRACT == parentResource.getResourceType())) && parentResource.getResourceType() != updatedResourceType
+ && oldResource.getResourceType() != updatedResourceType) {
BeEcompErrorManager.getInstance().logInternalDataError("mergeOldResourceMetadataWithNew",
- "resource type of the resource does not match to derived from resource type", ErrorSeverity.ERROR);
+ "resource type of the resource does not match to derived from resource type", ErrorSeverity.ERROR);
log.debug(
- "#mergeOldResourceMetadataWithNew - resource type {} of the resource {} does not match to derived from resource type {}",
- newResource.getResourceType(), newResource.getToscaResourceName(), parentResource.getResourceType());
+ "#mergeOldResourceMetadataWithNew - resource type {} of the resource {} does not match to derived from resource type {}",
+ newResource.getResourceType(), newResource.getToscaResourceName(), parentResource.getResourceType());
throw new ByActionStatusComponentException(ActionStatus.INVALID_RESOURCE_TYPE);
}
}
@@ -3838,10 +3837,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
String toscaResourceNameDerivedFrom = newResource.getDerivedFrom().get(0);
Either<Component, StorageOperationStatus> latestByToscaResourceName = toscaOperationFacade
- .getLatestByToscaResourceName(toscaResourceNameDerivedFrom, newResource.getModel());
+ .getLatestByToscaResourceName(toscaResourceNameDerivedFrom, newResource.getModel());
if (latestByToscaResourceName.isRight()) {
BeEcompErrorManager.getInstance()
- .logInternalDataError("mergeOldResourceMetadataWithNew", "derived from resource not found", ErrorSeverity.ERROR);
+ .logInternalDataError("mergeOldResourceMetadataWithNew", "derived from resource not found", ErrorSeverity.ERROR);
log.debug("#mergeOldResourceMetadataWithNew - derived from resource {} not found", toscaResourceNameDerivedFrom);
throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, toscaResourceNameDerivedFrom);
}
@@ -3852,8 +3851,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) {
// checkout
return lifecycleBusinessLogic
- .changeState(oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, new LifecycleChangeInfoWithAction("update by import"),
- inTransaction, needLock).left().on(response -> failOnChangeState(response, user, oldResource, newResource));
+ .changeState(oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, new LifecycleChangeInfoWithAction("update by import"),
+ inTransaction, needLock).left().on(response -> failOnChangeState(response, user, oldResource, newResource));
}
return oldResource;
}
@@ -3861,7 +3860,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
private Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) {
log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(), response.getFormattedMessage());
componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
- ResourceVersionInfo.newBuilder().state(oldResource.getLifecycleState().name()).version(oldResource.getVersion()).build());
+ ResourceVersionInfo.newBuilder().state(oldResource.getLifecycleState().name()).version(oldResource.getVersion()).build());
throw new ByResponseFormatComponentException(response);
}
@@ -3882,7 +3881,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
resourceSystemName = resource.getSystemName();
}
resource
- .setToscaResourceName(CommonBeUtils.generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
+ .setToscaResourceName(CommonBeUtils.generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
}
// Generate invariant UUID - must be here and not in operation since it
@@ -3917,7 +3916,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (eitherCapTypeFound.isRight()) {
if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
BeEcompErrorManager.getInstance()
- .logBeGraphObjectMissingError("Create Resource - validateLifecycleTypesCreate", "Interface", intType);
+ .logBeGraphObjectMissingError("Create Resource - validateLifecycleTypesCreate", "Interface", intType);
log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB", intType, resource.getName());
BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
log.debug("request to data model failed with error: {}", eitherCapTypeFound.right().value().name());
@@ -3938,7 +3937,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
log.debug("validate capability Types Exist - capabilities section");
for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities().entrySet()) {
eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum, eitherResult, typeEntry,
- inTransaction);
+ inTransaction);
if (eitherResult.isRight()) {
return Either.right(eitherResult.right().value());
}
@@ -3948,7 +3947,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
log.debug("validate capability Types Exist - requirements section");
for (String type : resource.getRequirements().keySet()) {
eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, resource.getRequirements().get(type), actionEnum,
- eitherResult, type, inTransaction);
+ eitherResult, type, inTransaction);
if (eitherResult.isRight()) {
return Either.right(eitherResult.right().value());
}
@@ -3962,7 +3961,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Resource resource, List<?> validationObjects, AuditingActionEnum actionEnum,
Either<Boolean, ResponseFormat> eitherResult, String type,
boolean inTransaction) {
- Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation.getCapabilityType(UniqueIdBuilder.buildCapabilityTypeUid(resource.getModel(), type), inTransaction);
+ Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation.getCapabilityType(
+ UniqueIdBuilder.buildCapabilityTypeUid(resource.getModel(), type), inTransaction);
if (eitherCapTypeFound.isRight()) {
if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", type);
@@ -3987,11 +3987,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Either<Boolean, ResponseFormat> eitherResult,
Entry<String, List<CapabilityDefinition>> typeEntry, boolean inTransaction) {
Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
- .getCapabilityType(UniqueIdBuilder.buildCapabilityTypeUid(resource.getModel(), typeEntry.getKey()), inTransaction);
+ .getCapabilityType(UniqueIdBuilder.buildCapabilityTypeUid(resource.getModel(), typeEntry.getKey()), inTransaction);
if (eitherCapTypeFound.isRight()) {
if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
BeEcompErrorManager.getInstance()
- .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", typeEntry.getKey());
+ .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", typeEntry.getKey());
log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", typeEntry.getKey(), resource.getName());
BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
}
@@ -4070,12 +4070,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
ASDCKpiApi.countCreatedResourcesKPI();
} catch (ComponentException e) {
ResponseFormat responseFormat =
- e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
+ e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
throw e;
} catch (StorageException e) {
ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
throw e;
} finally {
@@ -4092,20 +4092,20 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
final ResourceTypeEnum resourceType = resource.getResourceType();
final ComponentTypeEnum componentType = resource.getComponentType();
final Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade
- .validateComponentNameAndModelExists(resourceName, modelName, resourceType, componentType);
+ .validateComponentNameAndModelExists(resourceName, modelName, resourceType, componentType);
if (eitherValidation.isRight()) {
loggerSupportability.log(LoggerSupportabilityActions.VALIDATE_NAME, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
- "ERROR while validate component name {} Status is: {}", resource.getName(), eitherValidation.right().value());
+ "ERROR while validate component name {} Status is: {}", resource.getName(), eitherValidation.right().value());
log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(), eitherValidation.right().value());
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
}
if (eitherValidation.left().value()) {
log.debug("resource with name: {}, already exists", resource.getName());
loggerSupportability
- .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
- "resource with name: {} already exists", resource.getName());
+ .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+ "resource with name: {} already exists", resource.getName());
throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(),
- resource.getName());
+ resource.getName());
}
log.debug("send resource {} to dao for create", resource.getName());
createArtifactsPlaceHolderData(resource, user);
@@ -4147,7 +4147,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
artifactMap = new HashMap<>();
}
Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
- .getDeploymentResourceArtifacts();
+ .getDeploymentResourceArtifacts();
if (deploymentResourceArtifacts != null) {
Map<String, ArtifactDefinition> finalArtifactMap = artifactMap;
deploymentResourceArtifacts.forEach((k, v) -> processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k, v));
@@ -4168,7 +4168,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
if (artifactsBusinessLogic != null) {
ArtifactDefinition artifactDefinition = artifactsBusinessLogic
- .createArtifactPlaceHolderInfo(resource.getUniqueId(), k, (Map<String, Object>) v, user, ArtifactGroupTypeEnum.DEPLOYMENT);
+ .createArtifactPlaceHolderInfo(resource.getUniqueId(), k, (Map<String, Object>) v, user, ArtifactGroupTypeEnum.DEPLOYMENT);
if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
}
@@ -4185,7 +4185,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceCategory();
List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceType();
Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
- .getInformationalResourceArtifacts();
+ .getInformationalResourceArtifacts();
List<CategoryDefinition> categories = resource.getCategories();
boolean isCreateArtifact = true;
if (exludeResourceCategory != null) {
@@ -4201,8 +4201,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
for (String informationalResourceArtifactName : keys) {
Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts.get(informationalResourceArtifactName);
ArtifactDefinition artifactDefinition = artifactsBusinessLogic
- .createArtifactPlaceHolderInfo(resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
- ArtifactGroupTypeEnum.INFORMATIONAL);
+ .createArtifactPlaceHolderInfo(resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
+ ArtifactGroupTypeEnum.INFORMATIONAL);
artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
}
}
@@ -4254,7 +4254,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
* Deletes every version of the provided resource
*
* @param resourceId the resource identifier
- * @param user the user that performs the deletion
+ * @param user the user that performs the deletion
* @return
* @throws ComponentException if there is any error in the deletion of the resource operation
*/
@@ -4301,11 +4301,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
boolean failed = false;
try {
Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade
- .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version);
+ .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version);
if (resourceStatus.isRight()) {
log.debug("failed to get resource {} version {}", resourceName, version);
return componentsUtils
- .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), resourceName);
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), resourceName);
}
resource = resourceStatus.left().value();
} finally {
@@ -4343,11 +4343,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (storageStatus.isRight()) {
log.debug("failed to get resource by id {}", resourceId);
return Either.right(
- componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), resourceId));
+ componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), resourceId));
}
if (storageStatus.left().value() == null) {
return Either.right(componentsUtils
- .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId));
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId));
}
return Either.left(storageStatus.left().value());
}
@@ -4355,11 +4355,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion, String userId) {
validateUserExists(userId);
Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade
- .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion);
+ .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion);
if (getResource.isRight()) {
log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion);
return Either.right(
- componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResource.right().value()), resourceName));
+ componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResource.right().value()), resourceName));
}
return Either.left(getResource.left().value());
}
@@ -4383,7 +4383,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceIdToUpdate);
if (storageStatus.isRight()) {
throw new ByResponseFormatComponentException(
- componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
+ componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
}
currentResource = storageStatus.left().value();
}
@@ -4397,7 +4397,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
if (lockResult != StorageOperationStatus.OK) {
BeEcompErrorManager.getInstance()
- .logBeFailedLockObjectError("Upload Artifact - lock ", NodeTypeEnum.Resource.getName(), resourceIdToUpdate);
+ .logBeFailedLockObjectError("Upload Artifact - lock ", NodeTypeEnum.Resource.getName(), resourceIdToUpdate);
log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
throw new ByResponseFormatComponentException(responseFormat);
@@ -4421,7 +4421,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
newResource.setDerivedFrom(null);
}
Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource, user, currentResource, false,
- true);
+ true);
if (dataModelResponse.isRight()) {
log.debug("failed to update resource metadata!!!");
throw new ByResponseFormatComponentException(dataModelResponse.right().value());
@@ -4453,7 +4453,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
newResource.setHighestVersion(currentResource.isHighestVersion());
newResource.setCreationDate(currentResource.getCreationDate());
Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource, newResource, user.getUserId(),
- inTransaction);
+ inTransaction);
if (processUpdateOfDerivedFrom.isRight()) {
log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate);
return Either.right(processUpdateOfDerivedFrom.right().value());
@@ -4463,15 +4463,15 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
for (GroupDefinition group : newResource.getGroups()) {
if (DEFAULT_GROUP_VF_MODULE.equals(group.getType())) {
groupBusinessLogic
- .validateAndUpdateGroupMetadata(newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId(), user,
- newResource.getComponentType(), group, true, false);
+ .validateAndUpdateGroupMetadata(newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId(), user,
+ newResource.getComponentType(), group, true, false);
}
}
}
Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade.updateToscaElement(newResource);
if (dataModelResponse.isRight()) {
ResponseFormat responseFormat = componentsUtils
- .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), newResource);
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), newResource);
return Either.right(responseFormat);
} else if (dataModelResponse.left().value() == null) {
log.debug("No response from updateResource");
@@ -4483,7 +4483,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
private void updateVfModuleGroupsNames(Resource currentResource, Resource newResource) {
if (currentResource.getGroups() != null && !currentResource.getName().equals(newResource.getName())) {
List<GroupDefinition> updatedGroups = currentResource.getGroups().stream()
- .map(group -> getUpdatedGroup(group, currentResource.getName(), newResource.getName())).collect(toList());
+ .map(group -> getUpdatedGroup(group, currentResource.getName(), newResource.getName())).collect(toList());
newResource.setGroups(updatedGroups);
}
}
@@ -4657,7 +4657,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
// instances that were created without the "Cvfc" suffix
return currentResource.getResourceType() == ResourceTypeEnum.CVFC && resourceNameUpdated
- .equals(addCvfcSuffixToResourceName(resourceNameCurrent));
+ .equals(addCvfcSuffixToResourceName(resourceNameCurrent));
}
private String addCvfcSuffixToResourceName(String resourceName) {
@@ -4733,7 +4733,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
validateDerivedFromExist(null, updateInfoResource, null);
} else {
Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null, currentResource, updateInfoResource,
- null);
+ null);
if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
return validateDerivedFromExtending;
@@ -4771,7 +4771,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
validateDerivedFromExist(null, updateInfoResource, null);
} else {
Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null, currentResource, updateInfoResource,
- null);
+ null);
if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
return validateDerivedFromExtending;
@@ -4792,7 +4792,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist");
log.debug("request to data model failed with error: {}", storageStatus);
ResponseFormat responseFormat = componentsUtils
- .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
log.trace("audit before sending response");
componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus));
@@ -4810,12 +4810,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
String currentTemplateName = currentResource.getDerivedFrom().get(0);
String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0);
Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
- .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName, currentResource.getModel());
+ .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName, currentResource.getModel());
if (dataModelResponse.isRight()) {
StorageOperationStatus storageStatus = dataModelResponse.right().value();
BeEcompErrorManager.getInstance().logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
ResponseFormat responseFormat = componentsUtils
- .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
log.trace("audit before sending response");
componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
return Either.right(responseFormat);
@@ -4832,7 +4832,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
public void validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
log.debug("validate resource derivedFrom field");
if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty()) || (resource.getDerivedFrom().get(0)) == null || (resource
- .getDerivedFrom().get(0).trim().isEmpty())) {
+ .getDerivedFrom().get(0).trim().isEmpty())) {
log.info("derived from (template) field is missing for the resource");
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
@@ -4842,11 +4842,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
private void validateResourceNameUniqueness(Resource resource) {
Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade
- .validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType());
+ .validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType());
if (resourceOperationResponse.isLeft() && resourceOperationResponse.left().value()) {
log.debug("resource with name: {}, already exists", resource.getName());
throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(),
- resource.getName());
+ resource.getName());
} else if (resourceOperationResponse.isRight()) {
log.debug("error while validateResourceNameExists for resource: {}", resource.getName());
throw new StorageException(resourceOperationResponse.right().value());
@@ -4858,7 +4858,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (CollectionUtils.isEmpty(categories)) {
log.debug(CATEGORY_IS_EMPTY);
ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
+ .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
}
@@ -4880,14 +4880,14 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
log.debug(CATEGORY_IS_EMPTY);
ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
+ .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
}
if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
log.debug(CATEGORY_IS_EMPTY);
ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
+ .getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
}
@@ -4914,10 +4914,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return; // explisite output even if failOnInvalidCategory throw an exception
}
Optional<SubCategoryDefinition> foundSubcategory = foundCategory.get().getSubcategories().stream()
- .filter(subcat -> subcat.getName().equals(subcategory.getName())).findFirst();
+ .filter(subcat -> subcat.getName().equals(subcategory.getName())).findFirst();
if (foundSubcategory.isEmpty()) {
log.debug("SubCategory {} is not part of resource category group. Resource subcategory valid values are {}", subcategory,
- foundCategory.get().getSubcategories());
+ foundCategory.get().getSubcategories());
failOnInvalidCategory(user, resource, actionEnum);
}
}
@@ -4947,7 +4947,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
log.info("vendor release exceds limit.");
ResponseFormat errorResponse = componentsUtils
- .getResponseFormat(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
+ .getResponseFormat(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
throw new ByActionStatusComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
}
@@ -4976,7 +4976,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (!ValidationUtils.validateVendorNameLength(vendorName)) {
log.info("vendor name exceds limit.");
ResponseFormat errorResponse = componentsUtils
- .getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
+ .getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
throw new ByActionStatusComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
}
@@ -4995,10 +4995,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
log.info("resource vendor model number exceeds limit.");
ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
- "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
+ "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
throw new ByActionStatusComponentException(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
- "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
+ "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
}
// resource vendor model number is currently validated as vendor
@@ -5060,10 +5060,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (implementation != null) {
String uniqueId = implementation.getUniqueId();
log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}", uniqueId,
- operationEntry.getKey(), interfaceType);
+ operationEntry.getKey(), interfaceType);
// only thing that transacts and locks here
Either<ArtifactDefinition, ResponseFormat> deleteArtifactByInterface = artifactsBusinessLogic
- .deleteArtifactByInterface(resourceId, userId, uniqueId, true);
+ .deleteArtifactByInterface(resourceId, userId, uniqueId, true);
if (deleteArtifactByInterface.isRight()) {
log.debug("Couldn't remove artifact definition with id {}", uniqueId);
if (!inTransaction) {
@@ -5082,14 +5082,14 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
log.debug("2. Removing properties");
Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = propertyOperation
- .deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId);
+ .deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId);
if (findPropertiesOfNode.isRight() && findPropertiesOfNode.right().value() != StorageOperationStatus.OK) {
log.debug("Failed to remove all properties of resource");
if (!inTransaction) {
janusGraphDao.rollback();
}
return Either
- .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right().value())));
+ .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right().value())));
}
} else {
log.debug("Derived from wasn't changed during update");
@@ -5146,7 +5146,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
ResponseFormat responseFormat;
if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, property.getName(), type, innerType,
- property.getDefaultValue());
+ property.getDefaultValue());
}
throw new ByActionStatusComponentException(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type, property.getDefaultValue());
}
@@ -5189,7 +5189,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
// get resource from csar uuid
Either<Resource, StorageOperationStatus> either = toscaOperationFacade
- .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, "");
+ .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, "");
if (either.isRight()) {
ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND, csarUuid);
return Either.right(resp);
@@ -5255,7 +5255,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
UploadCapInfo uploadedCapability) {
List<ComponentInstanceProperty> validProperties = new ArrayList<>();
Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties().stream()
- .collect(toMap(PropertyDefinition::getName, Function.identity()));
+ .collect(toMap(PropertyDefinition::getName, Function.identity()));
List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
for (UploadPropInfo property : uploadedProperties) {
String propertyName = property.getName().toLowerCase();
@@ -5281,11 +5281,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(
- List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle, Resource resource, User user) {
+ List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle, Resource resource, User user) {
EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either
- .left(nodeTypeArtifactsToHandle);
+ .left(nodeTypeArtifactsToHandle);
try {
// add all found Csar artifacts to list to upload
List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
@@ -5295,7 +5295,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
ArtifactDefinition foundArtifact;
if (!existingArtifactsToHandle.isEmpty()) {
foundArtifact = existingArtifactsToHandle.stream().filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName()))
- .findFirst().orElse(null);
+ .findFirst().orElse(null);
if (foundArtifact != null) {
if (foundArtifact.getArtifactType().equals(currNewArtifact.getArtifactType())) {
if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
@@ -5322,14 +5322,14 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
} else {
log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
ResponseFormat responseFormat = ResponseFormatManager.getInstance()
- .getResponseFormat(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(),
- currNewArtifact.getArtifactType(), foundArtifact.getArtifactType());
+ .getResponseFormat(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(),
+ currNewArtifact.getArtifactType(), foundArtifact.getArtifactType());
AuditingActionEnum auditingAction = artifactsBusinessLogic
- .detectAuditingType(new ArtifactOperationInfo(false, false, ArtifactOperationEnum.CREATE),
- foundArtifact.getArtifactChecksum());
+ .detectAuditingType(new ArtifactOperationInfo(false, false, ArtifactOperationEnum.CREATE),
+ foundArtifact.getArtifactChecksum());
artifactsBusinessLogic
- .handleAuditing(auditingAction, resource, resource.getUniqueId(), user, null, null, foundArtifact.getUniqueId(),
- responseFormat, resource.getComponentType(), null);
+ .handleAuditing(auditingAction, resource, resource.getUniqueId(), user, null, null, foundArtifact.getUniqueId(),
+ responseFormat, resource.getComponentType(), null);
responseWrapper.setInnerElement(responseFormat);
break;
}
@@ -5340,10 +5340,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
for (ArtifactDefinition currArtifact : existingArtifactsToHandle) {
if (currArtifact.getIsFromCsar()) {
artifactsToDelete.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, currArtifact.getArtifactType(),
- currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
+ currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
} else {
artifactsToUpdate.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, currArtifact.getArtifactType(),
- currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
+ currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
}
}
}
@@ -5384,8 +5384,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
try {
final String nodeTypeNamePrefix = getNodeTypeNamePrefix(nodeTypeFullName);
log.debug("####### buildNestedToscaResourceName nodeResourceType {}, vfResourceName {}, "
- + "nodeTypeFullName {}, actualType {}, vfResourceName {} ", nodeResourceType, vfResourceName, nodeTypeFullName, actualType,
- vfResourceName);
+ + "nodeTypeFullName {}, actualType {}, vfResourceName {} ", nodeResourceType, vfResourceName, nodeTypeFullName, actualType,
+ vfResourceName);
final StringBuilder toscaResourceName = new StringBuilder(nodeTypeNamePrefix);
if (!nodeTypeFullName.contains(nodeTypeNamePrefix)) {
nameWithouNamespacePrefix = nodeTypeFullName;
@@ -5403,16 +5403,16 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
toscaResourceName.append(nodeResourceType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName));
} else {
toscaResourceName.append(actualType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName)).append('.')
- .append(Constants.ABSTRACT);
+ .append(Constants.ABSTRACT);
}
final StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName);
final String[] actualNames = actualName.split("\\.");
if (actualNames.length < 3) {
return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
- previousToscaResourceName.append(actualName).toString());
+ previousToscaResourceName.append(actualName).toString());
}
return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
- previousToscaResourceName.append(actualName.substring(actualNames[1].length() + 1).toLowerCase()).toString());
+ previousToscaResourceName.append(actualName.substring(actualNames[1].length() + 1).toLowerCase()).toString());
} catch (final Exception e) {
log.debug("Exception occured when buildNestedToscaResourceName, error is:{}", e.getMessage(), e);
throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfResourceName);
@@ -5449,7 +5449,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn);
return Either.right(
- componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceResultEither.right().value()), ""));
+ componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceResultEither.right().value()), ""));
}
Resource resource = resourceResultEither.left().value();
if (dataParamsToReturn.contains(ComponentFieldsEnum.INPUTS.getValue())) {
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 0681dd495e..8fe742af50 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
@@ -27,18 +27,22 @@ import static org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaElementO
import fj.data.Either;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Comparator;
+import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
+import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.servlet.ServletContext;
import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
@@ -58,8 +62,12 @@ import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphDao;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
@@ -81,6 +89,7 @@ import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
import org.openecomp.sdc.be.model.mapper.NodeTypeMetadataMapper;
import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
@@ -97,14 +106,13 @@ import org.openecomp.sdc.common.util.ThreadLocalsHolder;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import org.yaml.snakeyaml.Yaml;
-@Component("resourceImportManager")
+@org.springframework.stereotype.Component("resourceImportManager")
public class ResourceImportManager {
- static final Pattern PROPERTY_NAME_PATTERN_IGNORE_LENGTH = Pattern.compile("['\\w\\s\\-\\_\\d\\:]+");
+ static final Pattern PROPERTY_NAME_PATTERN_IGNORE_LENGTH = Pattern.compile("['\\w\\s\\-\\:]+");
private static final Logger log = Logger.getLogger(ResourceImportManager.class);
private final InterfaceDefinitionHandler interfaceDefinitionHandler;
private final ComponentsUtils componentsUtils;
@@ -148,7 +156,7 @@ public class ResourceImportManager {
lifecycleChangeInfo.setUserRemarks("certification on import");
Function<Resource, Boolean> validator = resource -> resourceBusinessLogic.validatePropertiesDefaultValues(resource);
return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, createNewVersion,
- needLock, null, null, false, null, null, false);
+ needLock, null, null, false, null, null, false);
}
public void importAllNormativeResource(final String resourcesYaml, final NodeTypesMetadataList nodeTypesMetadataList, final User user,
@@ -171,7 +179,7 @@ public class ResourceImportManager {
final Map<String, Object> nodeTypeMap = (Map<String, Object>) nodeTypesMap.get(nodeTypeToscaName);
if (nodeTypeMap == null) {
log.warn(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, ResourceImportManager.class.getName(),
- "Could not find given node type '{}'. The node will not be created.", new Object[]{nodeTypeToscaName});
+ "Could not find given node type '{}'. The node will not be created.", nodeTypeToscaName);
} else {
final Map<String, Map<String, Map<String, Object>>> nodeTypeDefinitionMap =
Map.of(ToscaTagNamesEnum.NODE_TYPES.getElementName(),
@@ -273,7 +281,8 @@ public class ResourceImportManager {
final Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resource.getName(), model);
if (latestByName.isLeft() && toscaOperationFacade.isNodeAssociatedToModel(model, resource)) {
if (model == null) {
- throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, resource.getName());
+ throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
+ resource.getResourceType().name(), resource.getName());
}
throw new ByActionStatusComponentException(ActionStatus.COMPONENT_WITH_MODEL_ALREADY_EXIST, resource.getName(), model);
}
@@ -328,15 +337,13 @@ public class ResourceImportManager {
try {
setMetaDataFromJson(resourceMetaData, resource);
populateResourceFromYaml(resourceYml, resource);
- // currently import VF isn't supported. In future will be supported
-
- // import VF only with CSAR file!!
+ // currently import VF isn't supported. In future will be supported import VF only with CSAR file!!
if (ResourceTypeEnum.VF == resource.getResourceType()) {
log.debug("Now import VF isn't supported. It will be supported in future with CSAR file only");
throw new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION);
}
resourceBusinessLogic.validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
- Boolean validatePropertiesTypes = resourceBusinessLogic.validatePropertiesDefaultValues(resource);
+ resourceBusinessLogic.validatePropertiesDefaultValues(resource);
responsePair = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, false, isInTransaction, true, null, null, false);
} catch (RuntimeException e) {
handleImportResourceException(resourceMetaData, creator, false, e);
@@ -344,17 +351,16 @@ public class ResourceImportManager {
return responsePair;
}
- private void populateResourceFromYaml(String resourceYml, Resource resource) {
+ private void populateResourceFromYaml(final String resourceYml, Resource resource) {
@SuppressWarnings("unchecked") Object ymlObj = new Yaml().load(resourceYml);
if (ymlObj instanceof Map) {
- Map<String, Object> toscaJsonAll = (Map<String, Object>) ymlObj;
+ final Either<Resource, StorageOperationStatus> existingResource = getExistingResource(resource);
+ final Map<String, Object> toscaJsonAll = (Map<String, Object>) ymlObj;
Map<String, Object> toscaJson = toscaJsonAll;
// Checks if exist and builds the node_types map
- if (toscaJsonAll.containsKey(ToscaTagNamesEnum.NODE_TYPES.getElementName())
- && resource.getResourceType() != ResourceTypeEnum.CVFC) {
+ if (toscaJsonAll.containsKey(ToscaTagNamesEnum.NODE_TYPES.getElementName()) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
toscaJson = new HashMap<>();
- toscaJson.put(ToscaTagNamesEnum.NODE_TYPES.getElementName(),
- toscaJsonAll.get(ToscaTagNamesEnum.NODE_TYPES.getElementName()));
+ toscaJson.put(ToscaTagNamesEnum.NODE_TYPES.getElementName(), toscaJsonAll.get(ToscaTagNamesEnum.NODE_TYPES.getElementName()));
}
final List<Object> foundElements = new ArrayList<>();
final Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils
@@ -366,12 +372,12 @@ public class ResourceImportManager {
}
}
// Derived From
- Resource parentResource = setDerivedFrom(toscaJson, resource);
+ final Resource parentResource = setDerivedFrom(toscaJson, resource);
if (StringUtils.isEmpty(resource.getToscaResourceName())) {
setToscaResourceName(toscaJson, resource);
}
setCapabilities(toscaJson, resource, parentResource);
- setProperties(toscaJson, resource);
+ setProperties(toscaJson, resource, existingResource);
setAttributes(toscaJson, resource);
setRequirements(toscaJson, resource, parentResource);
setInterfaceLifecycle(toscaJson, resource);
@@ -380,6 +386,45 @@ public class ResourceImportManager {
}
}
+ private Either<Resource, StorageOperationStatus> getExistingResource(final Resource resource) {
+ final Either<List<GraphVertex>, JanusGraphOperationStatus> byCriteria = janusGraphDao.getByCriteria(
+ getVertexTypeEnum(resource.getResourceType()), propertiesToMatch(resource), propertiesToNotMatch(),
+ JsonParseFlagEnum.ParseAll, resource.getModel(), false);
+ if (byCriteria.isLeft() && CollectionUtils.isNotEmpty(byCriteria.left().value())) {
+ final List<GraphVertex> graphVertexList = byCriteria.left().value();
+ if (graphVertexList.size() == 1) {
+ return toscaOperationFacade.getToscaElement(graphVertexList.get(0).getUniqueId());
+ } else {
+ final Optional<GraphVertex> vertex = graphVertexList.stream()
+ .max(Comparator.comparing(graphVertex -> (String) graphVertex.getMetadataProperties().get(GraphPropertyEnum.VERSION)));
+ if (vertex.isPresent()) {
+ return toscaOperationFacade.getToscaElement(vertex.get().getUniqueId());
+ }
+ }
+ }
+ return Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+
+ private VertexTypeEnum getVertexTypeEnum(final ResourceTypeEnum resourceType) {
+ return ModelConverter.isAtomicComponent(resourceType) ? VertexTypeEnum.NODE_TYPE : VertexTypeEnum.TOPOLOGY_TEMPLATE;
+ }
+
+ private Map<GraphPropertyEnum, Object> propertiesToMatch(final Resource resource) {
+ final Map<GraphPropertyEnum, Object> graphProperties = new EnumMap<>(GraphPropertyEnum.class);
+ graphProperties.put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normaliseComponentName(resource.getName()));
+ graphProperties.put(GraphPropertyEnum.COMPONENT_TYPE, resource.getComponentType().name());
+ graphProperties.put(GraphPropertyEnum.RESOURCE_TYPE, resource.getResourceType().name());
+ graphProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ return graphProperties;
+ }
+
+ private Map<GraphPropertyEnum, Object> propertiesToNotMatch() {
+ final Map<GraphPropertyEnum, Object> graphProperties = new EnumMap<>(GraphPropertyEnum.class);
+ graphProperties.put(GraphPropertyEnum.IS_DELETED, true);
+ graphProperties.put(GraphPropertyEnum.IS_ARCHIVED, true);
+ return graphProperties;
+ }
+
private void setToscaResourceName(Map<String, Object> toscaJson, Resource resource) {
Either<Map<String, Object>, ResultStatusEnum> toscaElement = ImportUtils
.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.NODE_TYPES);
@@ -395,7 +440,8 @@ public class ResourceImportManager {
if (toscaInterfaces.isLeft()) {
Map<String, InterfaceDefinition> moduleInterfaces = new HashMap<>();
for (final Entry<String, Object> interfaceNameValue : toscaInterfaces.left().value().entrySet()) {
- final Either<InterfaceDefinition, ResultStatusEnum> eitherInterface = createModuleInterface(interfaceNameValue.getValue(), resource.getModel());
+ final Either<InterfaceDefinition, ResultStatusEnum> eitherInterface = createModuleInterface(interfaceNameValue.getValue(),
+ resource.getModel());
if (eitherInterface.isRight()) {
log.info("error when creating interface:{}, for resource:{}", interfaceNameValue.getKey(), resource.getName());
} else {
@@ -438,9 +484,7 @@ public class ResourceImportManager {
Map<String, List<RequirementDefinition>> moduleRequirements = new HashMap<>();
// Checking for name duplication
Set<String> reqNames = new HashSet<>();
- // Getting flattened list of capabilities of parent node - cap name
-
- // to cap type
+ // Getting flattened list of capabilities of parent node - cap name to cap type
Map<String, String> reqName2TypeMap = getReqName2Type(parentResource);
for (Object jsonRequirementObj : jsonRequirements) {
// Requirement
@@ -504,33 +548,51 @@ public class ResourceImportManager {
return requirement;
}
- private void setProperties(Map<String, Object> toscaJson, Resource resource) {
- Map<String, Object> reducedToscaJson = new HashMap<>(toscaJson);
+ private void setProperties(final Map<String, Object> toscaJson, final Resource resource,
+ final Either<Resource, StorageOperationStatus> existingResource) {
+ final Map<String, Object> reducedToscaJson = new HashMap<>(toscaJson);
ImportUtils.removeElementFromJsonMap(reducedToscaJson, "capabilities");
- Either<Map<String, PropertyDefinition>, ResultStatusEnum> properties = ImportUtils.getProperties(reducedToscaJson);
+ final Either<Map<String, PropertyDefinition>, ResultStatusEnum> properties = ImportUtils.getProperties(reducedToscaJson);
if (properties.isLeft()) {
- List<PropertyDefinition> propertiesList = new ArrayList<>();
- Map<String, PropertyDefinition> value = properties.left().value();
- if (value != null) {
- for (Entry<String, PropertyDefinition> 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());
- throw new ByActionStatusComponentException(
- componentsUtils.convertFromResultStatusEnum(ResultStatusEnum.INVALID_PROPERTY_NAME, JsonPresentationFields.PROPERTY));
+ final Map<String, PropertyDefinition> propertyDefinitionMap = properties.left().value();
+ if (MapUtils.isNotEmpty(propertyDefinitionMap)) {
+ final List<PropertyDefinition> propertiesList = new ArrayList<>();
+ for (final Entry<String, PropertyDefinition> entry : propertyDefinitionMap.entrySet()) {
+ addPropertyToList(resource.getName(), propertiesList, entry);
+ }
+ if (existingResource.isLeft()) {
+ final List<PropertyDefinition> userCreatedResourceProperties =
+ existingResource.left().value().getProperties().stream()
+ .filter(PropertyDataDefinition::isUserCreated)
+ .filter(propertyDefinition -> !propertyDefinitionMap.containsKey(propertyDefinition.getName()))
+ .collect(Collectors.toList());
+ if (CollectionUtils.isNotEmpty(userCreatedResourceProperties)) {
+ propertiesList.addAll(userCreatedResourceProperties);
}
- PropertyDefinition propertyDefinition = entry.getValue();
- propertyDefinition.setName(name);
- propertiesList.add(propertyDefinition);
}
+
+ resource.setProperties(propertiesList);
}
- resource.setProperties(propertiesList);
} else if (properties.right().value() != ResultStatusEnum.ELEMENT_NOT_FOUND) {
throw new ByActionStatusComponentException(
componentsUtils.convertFromResultStatusEnum(properties.right().value(), JsonPresentationFields.PROPERTY));
}
}
+ private void addPropertyToList(final String resourceName,
+ final List<PropertyDefinition> propertiesList,
+ final Entry<String, PropertyDefinition> entry) {
+ final String propertyName = entry.getKey();
+ if (!PROPERTY_NAME_PATTERN_IGNORE_LENGTH.matcher(propertyName).matches()) {
+ log.debug("The property with invalid name {} occured upon import resource {}. ", propertyName, resourceName);
+ throw new ByActionStatusComponentException(
+ componentsUtils.convertFromResultStatusEnum(ResultStatusEnum.INVALID_PROPERTY_NAME, JsonPresentationFields.PROPERTY));
+ }
+ final PropertyDefinition propertyDefinition = entry.getValue();
+ propertyDefinition.setName(propertyName);
+ propertiesList.add(propertyDefinition);
+ }
+
private void setAttributes(final Map<String, Object> originalToscaJsonMap, final Resource resource) {
final Map<String, Object> toscaJsonMap = new HashMap<>(originalToscaJsonMap);
ImportUtils.removeElementFromJsonMap(toscaJsonMap, "capabilities");
@@ -569,7 +631,8 @@ public class ResourceImportManager {
String derivedFrom = toscaDerivedFromElement.left().value();
log.debug("Derived from TOSCA name is {}", derivedFrom);
resource.setDerivedFrom(Arrays.asList(new String[]{derivedFrom}));
- Either<Resource, StorageOperationStatus> latestByToscaResourceName = toscaOperationFacade.getLatestByToscaResourceName(derivedFrom, resource.getModel());
+ Either<Resource, StorageOperationStatus> latestByToscaResourceName = toscaOperationFacade.getLatestByToscaResourceName(derivedFrom,
+ resource.getModel());
if (latestByToscaResourceName.isRight()) {
StorageOperationStatus operationStatus = latestByToscaResourceName.right().value();
if (operationStatus == StorageOperationStatus.NOT_FOUND) {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentPropertyServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentPropertyServlet.java
index b411a97a87..101f10df19 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentPropertyServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentPropertyServlet.java
@@ -275,9 +275,9 @@ public class ComponentPropertyServlet extends BeGenericServlet {
Map.Entry<String, PropertyDefinition> entry = properties.entrySet().iterator().next();
PropertyDefinition newPropertyDefinition = entry.getValue();
newPropertyDefinition.setParentUniqueId(componentId);
- String propertyName = newPropertyDefinition.getName();
+ newPropertyDefinition.setUserCreated(true);
Either<EntryData<String, PropertyDefinition>, ResponseFormat> addPropertyEither = propertyBusinessLogic
- .addPropertyToComponent(componentId, propertyName, newPropertyDefinition, userId);
+ .addPropertyToComponent(componentId, newPropertyDefinition, userId);
if (addPropertyEither.isRight()) {
return buildErrorResponse(addPropertyEither.right().value());
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java
index e6457c9de7..71cb08c9da 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -22,9 +22,34 @@
package org.openecomp.sdc.be.components;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.hasItems;
+import static org.hamcrest.Matchers.hasSize;
+import static org.hamcrest.Matchers.instanceOf;
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.notNullValue;
+import static org.hamcrest.Matchers.nullValue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyObject;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.when;
+
import fj.data.Either;
-import org.junit.Before;
-import org.junit.Test;
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import javax.servlet.ServletContext;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
@@ -60,32 +85,7 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.openecomp.sdc.test.utils.InterfaceOperationTestUtils;
import org.springframework.web.context.WebApplicationContext;
-import javax.servlet.ServletContext;
-import java.lang.reflect.Field;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.hasItems;
-import static org.hamcrest.Matchers.hasSize;
-import static org.hamcrest.Matchers.instanceOf;
-import static org.hamcrest.Matchers.is;
-import static org.hamcrest.Matchers.notNullValue;
-import static org.hamcrest.Matchers.nullValue;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyObject;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.when;
-
-public class PropertyBusinessLogicTest extends BaseBusinessLogicMock {
+class PropertyBusinessLogicTest extends BaseBusinessLogicMock {
@Mock
private ServletContext servletContext;
@@ -104,9 +104,9 @@ public class PropertyBusinessLogicTest extends BaseBusinessLogicMock {
@Mock
private UserValidations userValidations;
@Mock
- IGraphLockOperation graphLockOperation;
+ private IGraphLockOperation graphLockOperation;
@Mock
- JanusGraphDao janusGraphDao;
+ private JanusGraphDao janusGraphDao;
@InjectMocks
private PropertyBusinessLogic propertyBusinessLogic = new PropertyBusinessLogic(elementDao, groupOperation, groupInstanceOperation,
@@ -118,7 +118,7 @@ public class PropertyBusinessLogicTest extends BaseBusinessLogicMock {
private static final String operationType = "operationType";
private static final String operationId = "operationId";
- @Before
+ @BeforeEach
public void setup() {
MockitoAnnotations.openMocks(this);
ExternalConfiguration.setAppName("catalog-be");
@@ -131,18 +131,17 @@ public class PropertyBusinessLogicTest extends BaseBusinessLogicMock {
user.setRole(Role.ADMIN.name());
when(mockUserAdmin.getUser("jh003", false)).thenReturn(user);
- when(userValidations.validateUserExists(eq("jh003"))).thenReturn(user);
+ when(userValidations.validateUserExists("jh003")).thenReturn(user);
// Servlet Context attributes
when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
when(servletContext.getAttribute(Constants.PROPERTY_OPERATION_MANAGER)).thenReturn(propertyOperation);
when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
-// when(servletContext.getAttribute(Constants.RESOURCE_OPERATION_MANAGER)).thenReturn(resourceOperation);
when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext);
}
@Test
- public void getProperty_propertyNotFound() throws Exception {
+ void getProperty_propertyNotFound() throws Exception {
Resource resource = new Resource();
PropertyDefinition property1 = createPropertyObject("someProperty", "someResource");
PropertyDefinition property2 = createPropertyObject("someProperty2", "myResource");
@@ -158,7 +157,7 @@ public class PropertyBusinessLogicTest extends BaseBusinessLogicMock {
}
@Test
- public void getProperty_propertyNotBelongsToResource() throws Exception {
+ void getProperty_propertyNotBelongsToResource() throws Exception {
Resource resource = new Resource();
PropertyDefinition property1 = createPropertyObject("someProperty", "someResource");
resource.setProperties(Arrays.asList(property1));
@@ -173,7 +172,7 @@ public class PropertyBusinessLogicTest extends BaseBusinessLogicMock {
}
@Test
- public void getProperty() throws Exception {
+ void getProperty() throws Exception {
Resource resource = new Resource();
resource.setUniqueId(resourceId);
PropertyDefinition property1 = createPropertyObject("someProperty", null);
@@ -187,7 +186,7 @@ public class PropertyBusinessLogicTest extends BaseBusinessLogicMock {
}
@Test
- public void testGetPropertyFromService() {
+ void testGetPropertyFromService() {
Service service = new Service();
service.setUniqueId(serviceId);
@@ -203,7 +202,7 @@ public class PropertyBusinessLogicTest extends BaseBusinessLogicMock {
}
@Test
- public void testPropertyNotFoundOnService() {
+ void testPropertyNotFoundOnService() {
Service service = new Service();
service.setUniqueId(serviceId);
@@ -218,7 +217,7 @@ public class PropertyBusinessLogicTest extends BaseBusinessLogicMock {
}
@Test
- public void isPropertyUsedByComponentInterface(){
+ void isPropertyUsedByComponentInterface() {
Service service = new Service();
service.setUniqueId(serviceId);
service.setInterfaces(InterfaceOperationTestUtils.createMockInterfaceDefinitionMap(interfaceType, operationId, operationType));
@@ -234,9 +233,11 @@ public class PropertyBusinessLogicTest extends BaseBusinessLogicMock {
}
@Test
- public void isPropertyUsedByComponentInstanceInterface(){
- Map<String, InterfaceDefinition> newInterfaceDefinition = InterfaceOperationTestUtils.createMockInterfaceDefinitionMap(interfaceType, operationId, operationType);
- ComponentInstanceInterface componentInstanceInterface = new ComponentInstanceInterface(interfaceType, newInterfaceDefinition.get(interfaceType));
+ void isPropertyUsedByComponentInstanceInterface() {
+ Map<String, InterfaceDefinition> newInterfaceDefinition = InterfaceOperationTestUtils.createMockInterfaceDefinitionMap(interfaceType,
+ operationId, operationType);
+ ComponentInstanceInterface componentInstanceInterface = new ComponentInstanceInterface(interfaceType,
+ newInterfaceDefinition.get(interfaceType));
Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces = new HashMap<>();
componentInstanceInterfaces.put("Test", Arrays.asList(componentInstanceInterface));
@@ -256,9 +257,11 @@ public class PropertyBusinessLogicTest extends BaseBusinessLogicMock {
}
@Test
- public void isPropertyUsedByComponentParentComponentInstanceInterface(){
- Map<String, InterfaceDefinition> newInterfaceDefinition = InterfaceOperationTestUtils.createMockInterfaceDefinitionMap(interfaceType, operationId, operationType);
- ComponentInstanceInterface componentInstanceInterface = new ComponentInstanceInterface(interfaceType, newInterfaceDefinition.get(interfaceType));
+ void isPropertyUsedByComponentParentComponentInstanceInterface() {
+ Map<String, InterfaceDefinition> newInterfaceDefinition = InterfaceOperationTestUtils.createMockInterfaceDefinitionMap(interfaceType,
+ operationId, operationType);
+ ComponentInstanceInterface componentInstanceInterface = new ComponentInstanceInterface(interfaceType,
+ newInterfaceDefinition.get(interfaceType));
Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces = new HashMap<>();
componentInstanceInterfaces.put("Test", Arrays.asList(componentInstanceInterface));
@@ -295,15 +298,15 @@ public class PropertyBusinessLogicTest extends BaseBusinessLogicMock {
}
@Test
- public void deleteProperty_CONNECTION_FAILURE() {
+ void deleteProperty_CONNECTION_FAILURE() {
StorageOperationStatus lockResult = StorageOperationStatus.CONNECTION_FAILURE;
when(graphLockOperation.lockComponent(any(), any())).thenReturn(lockResult);
when(toscaOperationFacade.getToscaElement(anyString())).thenReturn(Either.left(new Resource()));
- assertTrue(propertyBusinessLogic.deletePropertyFromComponent("resourceforproperty.0.1", "someProperty","i726").isRight());
+ assertTrue(propertyBusinessLogic.deletePropertyFromComponent("resourceforproperty.0.1", "someProperty", "i726").isRight());
}
@Test
- public void deleteProperty_RESOURCE_NOT_FOUND() throws Exception {
+ void deleteProperty_RESOURCE_NOT_FOUND() throws Exception {
Resource resource = new Resource();
PropertyDefinition property1 = createPropertyObject("someProperty", "someResource");
@@ -322,19 +325,19 @@ public class PropertyBusinessLogicTest extends BaseBusinessLogicMock {
StorageOperationStatus lockResult = StorageOperationStatus.OK;
when(graphLockOperation.lockComponent(any(), any())).thenReturn(lockResult);
- Component resourcereturn= new Resource();
+ Component resourcereturn = new Resource();
resourcereturn.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
resourcereturn.setIsDeleted(false);
resourcereturn.setLastUpdaterUserId("USR01");
- Either<Component, StorageOperationStatus> toscastatus=Either.left(resource);
+ Either<Component, StorageOperationStatus> toscastatus = Either.left(resource);
when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus);
- assertTrue(propertyBusinessLogic.deletePropertyFromComponent("RES01", "someProperty","i726").isRight());
+ assertTrue(propertyBusinessLogic.deletePropertyFromComponent("RES01", "someProperty", "i726").isRight());
}
@Test
- public void deleteProperty_RESTRICTED_OPERATION() throws Exception {
+ void deleteProperty_RESTRICTED_OPERATION() throws Exception {
Resource resource = new Resource();
PropertyDefinition property1 = createPropertyObject("someProperty", "someResource");
@@ -356,15 +359,14 @@ public class PropertyBusinessLogicTest extends BaseBusinessLogicMock {
resource.setIsDeleted(false);
resource.setLastUpdaterUserId("USR01");
- Either<Component, StorageOperationStatus> toscastatus=Either.left(resource);
+ Either<Component, StorageOperationStatus> toscastatus = Either.left(resource);
when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus);
-
- assertTrue(propertyBusinessLogic.deletePropertyFromComponent("RES01", "someProperty","i726").isRight());
+ assertTrue(propertyBusinessLogic.deletePropertyFromComponent("RES01", "someProperty", "i726").isRight());
}
@Test
- public void deleteProperty_RESTRICTED_() throws Exception {
+ void deleteProperty_RESTRICTED_() throws Exception {
final PropertyDefinition property1 = createPropertyObject("PROP", "RES01");
final Resource resource = new Resource();
final String resourceId = "myResource";
@@ -388,11 +390,11 @@ public class PropertyBusinessLogicTest extends BaseBusinessLogicMock {
when(toscaOperationFacade.deletePropertyOfComponent(anyObject(), anyString())).thenReturn(StorageOperationStatus.OK);
when(toscaOperationFacade.getParentComponents(anyString())).thenReturn(Either.left(new ArrayList<>()));
- assertTrue(propertyBusinessLogic.deletePropertyFromComponent("RES01", "PROP","USR01").isRight());
+ assertTrue(propertyBusinessLogic.deletePropertyFromComponent("RES01", "PROP", "USR01").isRight());
}
@Test
- public void findComponentByIdTest() throws BusinessLogicException {
+ void findComponentByIdTest() throws BusinessLogicException {
//give
final Resource resource = new Resource();
resource.setUniqueId(resourceId);
@@ -405,17 +407,19 @@ public class PropertyBusinessLogicTest extends BaseBusinessLogicMock {
actualResource.getUniqueId(), is(equalTo(resource.getUniqueId())));
}
- @Test(expected = BusinessLogicException.class)
- public void findComponentById_resourceNotFoundTest() throws BusinessLogicException {
+ @Test
+ void findComponentById_resourceNotFoundTest() throws BusinessLogicException {
//given
Mockito.when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.right(null));
Mockito.when(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")).thenReturn(new ResponseFormat());
//when
- propertyBusinessLogic.findComponentById(resourceId);
+ assertThrows(BusinessLogicException.class, () -> {
+ propertyBusinessLogic.findComponentById(resourceId);
+ });
}
@Test
- public void updateComponentPropertyTest() throws BusinessLogicException {
+ void updateComponentPropertyTest() throws BusinessLogicException {
//given
final Resource resource = new Resource();
resource.setUniqueId(resourceId);
@@ -433,8 +437,8 @@ public class PropertyBusinessLogicTest extends BaseBusinessLogicMock {
actualPropertyDefinition.getName(), is(equalTo(propertyDefinition.getName())));
}
- @Test(expected = BusinessLogicException.class)
- public void updateComponentProperty_updateFailedTest() throws BusinessLogicException {
+ @Test
+ void updateComponentProperty_updateFailedTest() throws BusinessLogicException {
//given
final Resource resource = new Resource();
resource.setUniqueId(resourceId);
@@ -444,11 +448,13 @@ public class PropertyBusinessLogicTest extends BaseBusinessLogicMock {
when(componentsUtils.getResponseFormatByResource(Mockito.any(), Mockito.anyString())).thenReturn(new ResponseFormat());
when(componentsUtils.convertFromStorageResponse(Mockito.any())).thenReturn(null);
//when
- propertyBusinessLogic.updateComponentProperty(resourceId, propertyDefinition);
+ assertThrows(BusinessLogicException.class, () -> {
+ propertyBusinessLogic.updateComponentProperty(resourceId, propertyDefinition);
+ });
}
@Test
- public void copyPropertyToComponentTest() throws ToscaOperationException {
+ void copyPropertyToComponentTest() throws ToscaOperationException {
//given
final Resource expectedResource = new Resource();
expectedResource.setUniqueId(resourceId);
@@ -466,10 +472,10 @@ public class PropertyBusinessLogicTest extends BaseBusinessLogicMock {
expectedResource.addProperty(copiedProperty2);
Mockito.when(toscaOperationFacade
- .addPropertyToComponent(eq(property1.getName()), Mockito.any(PropertyDefinition.class), eq(expectedResource)))
+ .addPropertyToComponent(Mockito.any(PropertyDefinition.class), eq(expectedResource)))
.thenReturn(Either.left(copiedProperty1));
Mockito.when(toscaOperationFacade
- .addPropertyToComponent(eq(property2.getName()), Mockito.any(PropertyDefinition.class), eq(expectedResource)))
+ .addPropertyToComponent(Mockito.any(PropertyDefinition.class), eq(expectedResource)))
.thenReturn(Either.left(copiedProperty2));
Mockito.when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(expectedResource));
//when
@@ -479,11 +485,12 @@ public class PropertyBusinessLogicTest extends BaseBusinessLogicMock {
assertThat("Actual component should be an instance of Resource", actualComponent, is(instanceOf(Resource.class)));
assertThat("Actual component should have the expected id", actualComponent.getUniqueId(), is(equalTo(expectedResource.getUniqueId())));
assertThat("Actual component should have 2 properties", actualComponent.getProperties(), hasSize(2));
- assertThat("Actual component should have the expected properties", actualComponent.getProperties(), hasItems(copiedProperty1, copiedProperty2));
+ assertThat("Actual component should have the expected properties", actualComponent.getProperties(),
+ hasItems(copiedProperty1, copiedProperty2));
}
@Test
- public void copyPropertyToComponent1() throws ToscaOperationException {
+ void copyPropertyToComponent1() throws ToscaOperationException {
//given
final Resource expectedResource = new Resource();
expectedResource.setUniqueId(resourceId);
@@ -496,8 +503,8 @@ public class PropertyBusinessLogicTest extends BaseBusinessLogicMock {
assertThat("Actual component should have no properties", actualComponent.getProperties(), is(nullValue()));
}
- @Test(expected = ToscaOperationException.class)
- public void copyPropertyToComponent_copyFailed() throws ToscaOperationException {
+ @Test
+ void copyPropertyToComponent_copyFailed() throws ToscaOperationException {
//given
final Resource expectedResource = new Resource();
expectedResource.setUniqueId(resourceId);
@@ -505,10 +512,12 @@ public class PropertyBusinessLogicTest extends BaseBusinessLogicMock {
final PropertyDefinition property1 = createPropertyObject("property1", resourceId);
propertiesToCopyList.add(property1);
Mockito.when(toscaOperationFacade
- .addPropertyToComponent(eq(property1.getName()), Mockito.any(PropertyDefinition.class), eq(expectedResource)))
+ .addPropertyToComponent(Mockito.any(PropertyDefinition.class), eq(expectedResource)))
.thenReturn(Either.right(StorageOperationStatus.GENERAL_ERROR));
Mockito.when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(expectedResource));
//when
- propertyBusinessLogic.copyPropertyToComponent(expectedResource, propertiesToCopyList, true);
+ assertThrows(ToscaOperationException.class, () -> {
+ propertyBusinessLogic.copyPropertyToComponent(expectedResource, propertiesToCopyList, true);
+ });
}
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java
index 80b5cf09bc..df679f1402 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -30,6 +30,7 @@ import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.anyBoolean;
@@ -41,6 +42,7 @@ import static org.mockito.Mockito.when;
import fj.data.Either;
import java.io.IOException;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
@@ -65,9 +67,13 @@ import org.openecomp.sdc.be.config.Configuration;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphDao;
+import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.CapabilityDefinition;
import org.openecomp.sdc.be.model.Component;
@@ -85,7 +91,6 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation;
import org.openecomp.sdc.be.model.tosca.constraints.GreaterOrEqualConstraint;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.be.tosca.utils.InterfaceTypesNameUtil;
import org.openecomp.sdc.be.user.UserBusinessLogic;
import org.openecomp.sdc.be.utils.TypeUtils;
import org.openecomp.sdc.common.api.ConfigurationSource;
@@ -94,7 +99,7 @@ import org.openecomp.sdc.common.impl.FSConfigurationSource;
import org.openecomp.sdc.exception.PolicyException;
import org.openecomp.sdc.exception.ResponseFormat;
-public class ResourceImportManagerTest {
+class ResourceImportManagerTest {
private ResourceImportManager importManager;
@@ -105,9 +110,11 @@ public class ResourceImportManagerTest {
private final InterfaceDefinitionHandler interfaceDefinitionHandler = new InterfaceDefinitionHandler(interfaceOperationBusinessLogic);
private final JanusGraphDao janusGraphDao = mock(JanusGraphDao.class);
private final UserBusinessLogic userAdmin = mock(UserBusinessLogic.class);
- private final ToscaOperationFacade toscaOperationFacade = mock(ToscaOperationFacade.class);
+ private final ToscaOperationFacade toscaOperationFacade = mock(ToscaOperationFacade.class);
private final ComponentsUtils componentsUtils = mock(ComponentsUtils.class);
private final CapabilityTypeOperation capabilityTypeOperation = mock(CapabilityTypeOperation.class);
+ private UploadResourceInfo resourceMD;
+ private User user;
@BeforeAll
public static void beforeClass() {
@@ -132,13 +139,14 @@ public class ResourceImportManagerTest {
Either<Component, StorageOperationStatus> notFound = Either.right(StorageOperationStatus.NOT_FOUND);
when(toscaOperationFacade.getComponentByNameAndVendorRelease(any(ComponentTypeEnum.class), anyString(), anyString(),
any(JsonParseFlagEnum.class), any())).thenReturn(notFound);
+ when(janusGraphDao.getByCriteria(eq(VertexTypeEnum.NODE_TYPE), anyMap(), anyMap(), eq(JsonParseFlagEnum.ParseAll), any(), anyBoolean()))
+ .thenReturn(Either.right(JanusGraphOperationStatus.NOT_FOUND));
+ resourceMD = createDummyResourceMD();
+ user = new User();
}
@Test
void testBasicResourceCreation() throws IOException {
- UploadResourceInfo resourceMD = createDummyResourceMD();
-
- User user = new User();
user.setUserId(resourceMD.getContactId());
user.setRole("ADMIN");
user.setFirstName("Jhon");
@@ -155,11 +163,58 @@ public class ResourceImportManagerTest {
testSetConstantMetaData(resource);
testSetMetaDataFromJson(resource, resourceMD);
-
+
testSetDerivedFrom(resource);
testSetProperties(resource);
- verify(resourceBusinessLogic).propagateStateToCertified(eq(user), eq(resource), any(LifecycleChangeInfoWithAction.class), eq(false), eq(true), eq(false));
+ verify(resourceBusinessLogic).propagateStateToCertified(eq(user), eq(resource), any(LifecycleChangeInfoWithAction.class), eq(false), eq(true),
+ eq(false));
+ }
+
+ @Test
+ void testReimportVfcToExistedResource() throws IOException {
+ user.setUserId(resourceMD.getContactId());
+ user.setRole("ADMIN");
+ user.setFirstName("John");
+ user.setLastName("Doe");
+ when(userAdmin.getUser(anyString(), anyBoolean())).thenReturn(user);
+
+ setResourceBusinessLogicMock();
+
+ final String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-blockStorage.yml");
+
+ ImmutablePair<Resource, ActionStatus> createResource =
+ importManager.importNormativeResource(jsonContent, resourceMD, user, true, true, false);
+ assertNotNull(createResource);
+ Resource resource = createResource.left;
+ assertNotNull(resource);
+
+ final GraphVertex graphVertex_1 = new GraphVertex();
+ graphVertex_1.setUniqueId("1-2-3-4-5-6-7");
+ graphVertex_1.addMetadataProperty(GraphPropertyEnum.VERSION, "1.1");
+ when(janusGraphDao.getByCriteria(eq(VertexTypeEnum.NODE_TYPE), anyMap(), anyMap(), eq(JsonParseFlagEnum.ParseAll), any(), anyBoolean()))
+ .thenReturn(Either.left(Arrays.asList(graphVertex_1)));
+ when(toscaOperationFacade.getToscaElement(anyString())).thenReturn(Either.left(resource));
+ createResource = reimportVfc(resource, jsonContent);
+ assertNotNull(createResource);
+ resource = createResource.left;
+ assertNotNull(resource);
+ testPropertiesAfterReimport(resource);
+
+ final GraphVertex graphVertex_2 = new GraphVertex();
+ graphVertex_2.setUniqueId("11-22-33-44-55-66-77");
+ graphVertex_2.addMetadataProperty(GraphPropertyEnum.VERSION, "2.2");
+ when(janusGraphDao.getByCriteria(eq(VertexTypeEnum.NODE_TYPE), anyMap(), anyMap(), eq(JsonParseFlagEnum.ParseAll), any(), anyBoolean()))
+ .thenReturn(Either.left(Arrays.asList(graphVertex_1, graphVertex_2)));
+ when(toscaOperationFacade.getToscaElement(anyString())).thenReturn(Either.left(resource));
+ createResource = reimportVfc(resource, jsonContent);
+ assertNotNull(createResource);
+ resource = createResource.left;
+ assertNotNull(resource);
+ testPropertiesAfterReimport(resource);
+
+ verify(resourceBusinessLogic, times(3))
+ .propagateStateToCertified(eq(user), eq(resource), any(LifecycleChangeInfoWithAction.class), eq(false), eq(true), eq(false));
}
@Test
@@ -167,13 +222,13 @@ public class ResourceImportManagerTest {
final List<NodeTypeMetadata> nodeMetadataList = new ArrayList<>();
var nodeTypeMetadata1 = new NodeTypeMetadata();
nodeTypeMetadata1.setToscaName("my.tosca.Type");
+ nodeTypeMetadata1.setName("Type");
nodeMetadataList.add(nodeTypeMetadata1);
var nodeTypeMetadata2 = new NodeTypeMetadata();
nodeTypeMetadata2.setToscaName("my.tosca.not.in.the.Yaml");
nodeMetadataList.add(nodeTypeMetadata2);
var nodeTypesMetadataList = new NodeTypesMetadataList();
nodeTypesMetadataList.setNodeMetadataList(nodeMetadataList);
- var user = new User();
var yaml = "node_types:\n"
+ " my.tosca.Type:\n"
+ " description: a description";
@@ -197,7 +252,7 @@ public class ResourceImportManagerTest {
}
@Test
- void importAllNormativeResourceTest_exceptionDuringImportShouldTriggerRolback() {
+ void importAllNormativeResourceTest_exceptionDuringImportShouldTriggerRollback() {
when(responseFormatManager.getResponseFormat(ActionStatus.GENERAL_ERROR)).thenReturn(mock(ResponseFormat.class));
when(toscaOperationFacade.getLatestByName(any(), any())).thenThrow(new RuntimeException());
@@ -210,7 +265,6 @@ public class ResourceImportManagerTest {
nodeMetadataList.add(nodeTypeMetadata2);
var nodeTypesMetadataList = new NodeTypesMetadataList();
nodeTypesMetadataList.setNodeMetadataList(nodeMetadataList);
- var user = new User();
var yaml = "node_types:\n"
+ " my.tosca.Type:\n"
+ " description: a description";
@@ -220,11 +274,8 @@ public class ResourceImportManagerTest {
verify(janusGraphDao).rollback();
}
-
- @Test()
+ @Test
void testResourceCreationFailed() {
- UploadResourceInfo resourceMD = createDummyResourceMD();
- User user = new User();
user.setUserId(resourceMD.getContactId());
when(userAdmin.getUser(anyString(), anyBoolean())).thenReturn(user);
ResponseFormat dummyResponseFormat = createGeneralErrorInfo();
@@ -236,7 +287,7 @@ public class ResourceImportManagerTest {
ComponentException errorInfoFromTest = null;
try {
importManager.importNormativeResource(jsonContent, resourceMD, user, true, true, false);
- }catch (ComponentException e){
+ } catch (ComponentException e) {
errorInfoFromTest = e;
}
assertNotNull(errorInfoFromTest);
@@ -250,8 +301,6 @@ public class ResourceImportManagerTest {
@Test
void testResourceCreationWithCapabilities() throws IOException {
- UploadResourceInfo resourceMD = createDummyResourceMD();
- User user = new User();
user.setUserId(resourceMD.getContactId());
when(userAdmin.getUser(anyString(), anyBoolean())).thenReturn(user);
@@ -272,8 +321,6 @@ public class ResourceImportManagerTest {
@Test
void testResourceCreationWithRequirements() throws IOException {
- UploadResourceInfo resourceMD = createDummyResourceMD();
- User user = new User();
user.setUserId(resourceMD.getContactId());
when(userAdmin.getUser(anyString(), anyBoolean())).thenReturn(user);
@@ -289,8 +336,6 @@ public class ResourceImportManagerTest {
@Test
void testResourceCreationWithInterfaceImplementation() throws IOException {
- UploadResourceInfo resourceMD = createDummyResourceMD();
- User user = new User();
user.setUserId(resourceMD.getContactId());
when(userAdmin.getUser(anyString(), anyBoolean())).thenReturn(user);
@@ -303,9 +348,9 @@ public class ResourceImportManagerTest {
interfaceDefinition.setType("tosca.interfaces.node.lifecycle.Standard");
Map<String, OperationDataDefinition> operations = new HashMap<>();
operations.put("configure", new OperationDataDefinition());
- interfaceDefinition.setOperations(operations );
+ interfaceDefinition.setOperations(operations);
interfaceTypes.put("tosca.interfaces.node.lifecycle.standard", interfaceDefinition);
- when(interfaceOperationBusinessLogic.getAllInterfaceLifecycleTypes(any())).thenReturn(Either.left(interfaceTypes));
+ when(interfaceOperationBusinessLogic.getAllInterfaceLifecycleTypes(any())).thenReturn(Either.left(interfaceTypes));
final ImmutablePair<Resource, ActionStatus> createResource =
importManager.importNormativeResource(jsonContent, resourceMD, user, true, true, false);
@@ -314,8 +359,6 @@ public class ResourceImportManagerTest {
@Test
void testResourceCreationWithInterfaceImplementation_UnknownInterface() throws IOException {
- UploadResourceInfo resourceMD = createDummyResourceMD();
- User user = new User();
user.setUserId(resourceMD.getContactId());
when(userAdmin.getUser(anyString(), anyBoolean())).thenReturn(user);
@@ -328,9 +371,9 @@ public class ResourceImportManagerTest {
interfaceDefinition.setType("tosca.interfaces.node.lifecycle.Standard");
Map<String, OperationDataDefinition> operations = new HashMap<>();
operations.put("configure", new OperationDataDefinition());
- interfaceDefinition.setOperations(operations );
+ interfaceDefinition.setOperations(operations);
interfaceTypes.put("tosca.interfaces.node.lifecycle.standard", interfaceDefinition);
- when(interfaceOperationBusinessLogic.getAllInterfaceLifecycleTypes(any())).thenReturn(Either.left(interfaceTypes));
+ when(interfaceOperationBusinessLogic.getAllInterfaceLifecycleTypes(any())).thenReturn(Either.left(interfaceTypes));
ImmutablePair<Resource, ActionStatus> createResource =
importManager.importNormativeResource(jsonContent, resourceMD, user, true, true, false);
@@ -339,8 +382,6 @@ public class ResourceImportManagerTest {
@Test
void testResourceCreationWitInterfaceImplementation_UnknownOperation() throws IOException {
- UploadResourceInfo resourceMD = createDummyResourceMD();
- User user = new User();
user.setUserId(resourceMD.getContactId());
when(userAdmin.getUser(anyString(), anyBoolean())).thenReturn(user);
@@ -353,20 +394,17 @@ public class ResourceImportManagerTest {
interfaceDefinition.setType("tosca.interfaces.node.lifecycle.Standard");
Map<String, OperationDataDefinition> operations = new HashMap<>();
operations.put("configure", new OperationDataDefinition());
- interfaceDefinition.setOperations(operations );
+ interfaceDefinition.setOperations(operations);
interfaceTypes.put("tosca.interfaces.node.lifecycle.standard", interfaceDefinition);
- when(interfaceOperationBusinessLogic.getAllInterfaceLifecycleTypes(any())).thenReturn(Either.left(interfaceTypes));
-
+ when(interfaceOperationBusinessLogic.getAllInterfaceLifecycleTypes(any())).thenReturn(Either.left(interfaceTypes));
+
ImmutablePair<Resource, ActionStatus> createResource =
importManager.importNormativeResource(jsonContent, resourceMD, user, true, true, false);
assertNull(createResource.left.getInterfaces());
}
-
+
@Test
void testResourceCreationFailedVendorReleaseAlreadyExists() throws IOException {
- UploadResourceInfo resourceMD = createDummyResourceMD();
-
- User user = new User();
user.setUserId(resourceMD.getContactId());
user.setRole("ADMIN");
user.setFirstName("Jhon");
@@ -388,30 +426,35 @@ public class ResourceImportManagerTest {
private void setResourceBusinessLogicMock() {
when(resourceBusinessLogic.getUserAdmin()).thenReturn(userAdmin);
- when(resourceBusinessLogic.createOrUpdateResourceByImport(any(Resource.class), any(User.class), anyBoolean(), anyBoolean(), anyBoolean(), eq(null), eq(null), eq(false)))
- .thenAnswer((Answer<ImmutablePair<Resource, ActionStatus>>) invocation -> {
- Object[] args = invocation.getArguments();
- return new ImmutablePair<>((Resource) args[0], ActionStatus.CREATED);
-
- });
- when(resourceBusinessLogic.propagateStateToCertified(any(User.class), any(Resource.class), any(LifecycleChangeInfoWithAction.class), eq(false), eq(true), eq(false)))
- .thenAnswer((Answer<Resource>) invocation -> {
- Object[] args = invocation.getArguments();
- return (Resource) args[1];
-
- });
+ when(resourceBusinessLogic.createOrUpdateResourceByImport(any(Resource.class), any(User.class), anyBoolean(), anyBoolean(), anyBoolean(),
+ eq(null), eq(null), eq(false)))
+ .thenAnswer((Answer<ImmutablePair<Resource, ActionStatus>>) invocation -> {
+ Object[] args = invocation.getArguments();
+ return new ImmutablePair<>((Resource) args[0], ActionStatus.CREATED);
+
+ });
+ when(
+ resourceBusinessLogic.propagateStateToCertified(any(User.class), any(Resource.class), any(LifecycleChangeInfoWithAction.class), eq(false),
+ eq(true), eq(false)))
+ .thenAnswer((Answer<Resource>) invocation -> {
+ Object[] args = invocation.getArguments();
+ return (Resource) args[1];
+
+ });
when(resourceBusinessLogic.createResourceByDao(
- any(Resource.class), any(User.class), any(AuditingActionEnum.class), anyBoolean(), anyBoolean())).thenAnswer((Answer<Either<Resource, ResponseFormat>>) invocation -> {
- Object[] args = invocation.getArguments();
- return Either.left((Resource) args[0]);
+ any(Resource.class), any(User.class), any(AuditingActionEnum.class), anyBoolean(), anyBoolean())).thenAnswer(
+ (Answer<Either<Resource, ResponseFormat>>) invocation -> {
+ Object[] args = invocation.getArguments();
+ return Either.left((Resource) args[0]);
- });
+ });
when(resourceBusinessLogic.validateResourceBeforeCreate(
- any(Resource.class), any(User.class), any(AuditingActionEnum.class), eq(false), eq(null))).thenAnswer((Answer<Either<Resource, ResponseFormat>>) invocation -> {
- Object[] args = invocation.getArguments();
- return Either.left((Resource) args[0]);
+ any(Resource.class), any(User.class), any(AuditingActionEnum.class), eq(false), eq(null))).thenAnswer(
+ (Answer<Either<Resource, ResponseFormat>>) invocation -> {
+ Object[] args = invocation.getArguments();
+ return Either.left((Resource) args[0]);
- });
+ });
when(resourceBusinessLogic.validatePropertiesDefaultValues(any(Resource.class))).thenReturn(true);
}
@@ -430,7 +473,8 @@ public class ResourceImportManagerTest {
resourceMD.setContactId("ya107f");
resourceMD.setResourceIconPath("defaulticon");
resourceMD.setTags(Collections.singletonList("BlockStorage"));
- resourceMD.setDescription("Represents a server-local block storage device (i.e., not shared) offering evenly sized blocks of data from which raw storage volumes can be created.");
+ resourceMD.setDescription(
+ "Represents a server-local block storage device (i.e., not shared) offering evenly sized blocks of data from which raw storage volumes can be created.");
resourceMD.setResourceVendorModelNumber("vendorReleaseNumber");
resourceMD.setNormative(true);
return resourceMD;
@@ -464,6 +508,54 @@ public class ResourceImportManagerTest {
}
+ private ImmutablePair<Resource, ActionStatus> reimportVfc(Resource resource, String jsonContent) {
+ List<PropertyDefinition> propertiesList = resource.getProperties();
+ PropertyDefinition propertyDefinition = new PropertyDefinition();
+ propertyDefinition.setName("oneMore");
+ propertyDefinition.setUserCreated(true);
+ propertyDefinition.setType("boolean");
+ propertiesList.add(propertyDefinition);
+ resource.setProperties(propertiesList);
+ return importManager.importNormativeResource(jsonContent, resourceMD, user, true, true, false);
+
+ }
+
+ private void testPropertiesAfterReimport(Resource resource) {
+ List<PropertyDefinition> propertiesList = resource.getProperties();
+
+ Map<String, PropertyDefinition> properties = new HashMap<>();
+ for (PropertyDefinition propertyDefinition : propertiesList) {
+ properties.put(propertyDefinition.getName(), propertyDefinition);
+ }
+
+ assertEquals(4, properties.size());
+
+ assertTrue(properties.containsKey("size"));
+ PropertyDefinition propertyDefinition = properties.get("size");
+ assertEquals("scalar-unit.size", propertyDefinition.getType());
+ assertEquals(1, propertyDefinition.getConstraints().size());
+ PropertyConstraint propertyConstraint = propertyDefinition.getConstraints().get(0);
+ assertTrue(propertyConstraint instanceof GreaterOrEqualConstraint);
+
+ assertTrue(properties.containsKey("volume_id"));
+ propertyDefinition = properties.get("volume_id");
+ assertEquals("string", propertyDefinition.getType());
+ assertFalse(propertyDefinition.isRequired());
+ assertFalse(propertyDefinition.isUserCreated());
+
+ assertTrue(properties.containsKey("snapshot_id"));
+ propertyDefinition = properties.get("snapshot_id");
+ assertEquals("string", propertyDefinition.getType());
+ assertFalse(propertyDefinition.isRequired());
+ assertFalse(propertyDefinition.isUserCreated());
+
+ assertTrue(properties.containsKey("oneMore"));
+ propertyDefinition = properties.get("oneMore");
+ assertEquals("boolean", propertyDefinition.getType());
+ assertFalse(propertyDefinition.isRequired());
+ assertTrue(propertyDefinition.isUserCreated());
+ }
+
private void testSetCapabilities(Resource resource) {
Map<String, List<CapabilityDefinition>> capabilities = resource.getCapabilities();
assertEquals(3, capabilities.size());
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java
index d133e081a2..d85ad38120 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java
@@ -20,11 +20,41 @@
package org.openecomp.sdc.be.components.impl;
+import static org.assertj.core.api.Java6Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.when;
+
import fj.data.Either;
+import java.io.File;
+import java.io.IOException;
+import java.lang.reflect.Method;
+import java.net.URISyntaxException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Optional;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import javax.servlet.ServletContext;
import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
@@ -125,1362 +155,1341 @@ import org.openecomp.sdc.common.zip.exception.ZipException;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.web.context.WebApplicationContext;
-import javax.servlet.ServletContext;
-import java.io.File;
-import java.io.IOException;
-import java.lang.reflect.Method;
-import java.net.URISyntaxException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Optional;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
-import static org.assertj.core.api.Java6Assertions.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThrows;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyList;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.doAnswer;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.when;
-
-public class ResourceBusinessLogicTest {
-
- private final ConfigurationManager configurationManager = new ConfigurationManager(new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be"));
- private static final String RESOURCE_CATEGORY1 = "Network Layer 2-3";
- private static final String RESOURCE_SUBCATEGORY = "Router";
-
- private static final String UPDATED_SUBCATEGORY = "Gateway";
-
- private static final String RESOURCE_NAME = "My-Resource_Name with space";
- private static final String RESOURCE_TOSCA_NAME = "My-Resource_Tosca_Name";
- private static final String GENERIC_ROOT_NAME = "tosca.nodes.Root";
- private static final String GENERIC_VF_NAME = "org.openecomp.resource.abstract.nodes.VF";
- private static final String GENERIC_CR_NAME = "org.openecomp.resource.abstract.nodes.CR";
- private static final String GENERIC_PNF_NAME = "org.openecomp.resource.abstract.nodes.PNF";
-
- private final ServletContext servletContext = Mockito.mock(ServletContext.class);
- IElementOperation mockElementDao;
- private final JanusGraphDao mockJanusGraphDao = Mockito.mock(JanusGraphDao.class);
- private final UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class);
- private final ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
- private final NodeTypeOperation nodeTypeOperation = Mockito.mock(NodeTypeOperation.class);
- private final NodeTemplateOperation nodeTemplateOperation = Mockito.mock(NodeTemplateOperation.class);
- private final TopologyTemplateOperation topologyTemplateOperation = Mockito.mock(TopologyTemplateOperation.class);
- private final LifecycleBusinessLogic lifecycleBl = Mockito.mock(LifecycleBusinessLogic.class);
- private final CatalogOperation catalogOperation = Mockito.mock(CatalogOperation.class);
- private final ICapabilityTypeOperation capabilityTypeOperation = Mockito.mock(ICapabilityTypeOperation.class);
- private final PropertyOperation propertyOperation = Mockito.mock(PropertyOperation.class);
- private final ApplicationDataTypeCache applicationDataTypeCache = Mockito.mock(ApplicationDataTypeCache.class);
- private final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
- private final UserValidations userValidations = Mockito.mock(UserValidations.class);
- private final WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class);
- private final IInterfaceLifecycleOperation interfaceTypeOperation = Mockito.mock(IInterfaceLifecycleOperation.class);
- private final ArtifactCassandraDao artifactCassandraDao = Mockito.mock(ArtifactCassandraDao.class);
- private final IElementOperation elementDao = new ElementOperationMock();
-
- private final CsarUtils csarUtils = Mockito.mock(CsarUtils.class);
- private final UserBusinessLogic userBusinessLogic = Mockito.mock(UserBusinessLogic.class);
- private final IGroupOperation groupOperation = Mockito.mock(IGroupOperation.class);
- private final IGroupInstanceOperation groupInstanceOperation = Mockito.mock(IGroupInstanceOperation.class);
- private final IGroupTypeOperation groupTypeOperation = Mockito.mock(IGroupTypeOperation.class);
+class ResourceBusinessLogicTest {
+
+ private final ConfigurationManager configurationManager = new ConfigurationManager(
+ new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be"));
+ private static final String RESOURCE_CATEGORY1 = "Network Layer 2-3";
+ private static final String RESOURCE_SUBCATEGORY = "Router";
+
+ private static final String UPDATED_SUBCATEGORY = "Gateway";
+
+ private static final String RESOURCE_NAME = "My-Resource_Name with space";
+ private static final String RESOURCE_TOSCA_NAME = "My-Resource_Tosca_Name";
+ private static final String GENERIC_ROOT_NAME = "tosca.nodes.Root";
+ private static final String GENERIC_VF_NAME = "org.openecomp.resource.abstract.nodes.VF";
+ private static final String GENERIC_CR_NAME = "org.openecomp.resource.abstract.nodes.CR";
+ private static final String GENERIC_PNF_NAME = "org.openecomp.resource.abstract.nodes.PNF";
+
+ private final ServletContext servletContext = Mockito.mock(ServletContext.class);
+ private IElementOperation mockElementDao;
+ private final JanusGraphDao mockJanusGraphDao = Mockito.mock(JanusGraphDao.class);
+ private final UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class);
+ private final ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
+ private final NodeTypeOperation nodeTypeOperation = Mockito.mock(NodeTypeOperation.class);
+ private final NodeTemplateOperation nodeTemplateOperation = Mockito.mock(NodeTemplateOperation.class);
+ private final TopologyTemplateOperation topologyTemplateOperation = Mockito.mock(TopologyTemplateOperation.class);
+ private final LifecycleBusinessLogic lifecycleBl = Mockito.mock(LifecycleBusinessLogic.class);
+ private final CatalogOperation catalogOperation = Mockito.mock(CatalogOperation.class);
+ private final ICapabilityTypeOperation capabilityTypeOperation = Mockito.mock(ICapabilityTypeOperation.class);
+ private final PropertyOperation propertyOperation = Mockito.mock(PropertyOperation.class);
+ private final ApplicationDataTypeCache applicationDataTypeCache = Mockito.mock(ApplicationDataTypeCache.class);
+ private final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
+ private final UserValidations userValidations = Mockito.mock(UserValidations.class);
+ private final WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class);
+ private final IInterfaceLifecycleOperation interfaceTypeOperation = Mockito.mock(IInterfaceLifecycleOperation.class);
+ private final ArtifactCassandraDao artifactCassandraDao = Mockito.mock(ArtifactCassandraDao.class);
+ private final IElementOperation elementDao = new ElementOperationMock();
+
+ private final CsarUtils csarUtils = Mockito.mock(CsarUtils.class);
+ private final UserBusinessLogic userBusinessLogic = Mockito.mock(UserBusinessLogic.class);
+ private final IGroupOperation groupOperation = Mockito.mock(IGroupOperation.class);
+ private final IGroupInstanceOperation groupInstanceOperation = Mockito.mock(IGroupInstanceOperation.class);
+ private final IGroupTypeOperation groupTypeOperation = Mockito.mock(IGroupTypeOperation.class);
private final GroupBusinessLogic groupBusinessLogic = Mockito.mock(GroupBusinessLogic.class);
private final ModelBusinessLogic modelBusinessLogic = Mockito.mock(ModelBusinessLogic.class);
- private final InterfaceOperation interfaceOperation = Mockito.mock(InterfaceOperation.class);
- private final ArtifactsOperations artifactToscaOperation = Mockito.mock(ArtifactsOperations.class);
- private final PropertyBusinessLogic propertyBusinessLogic = Mockito.mock(PropertyBusinessLogic.class);
- private final ArtifactsResolver artifactsResolver = Mockito.mock(ArtifactsResolver.class);
- private final InterfaceLifecycleOperation interfaceLifecycleTypeOperation = Mockito.mock(InterfaceLifecycleOperation.class);
- private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic = Mockito.mock(ComponentInstanceBusinessLogic.class);
- private final ResourceImportManager resourceImportManager = Mockito.mock(ResourceImportManager.class);
- private final InputsBusinessLogic inputsBusinessLogic = Mockito.mock(InputsBusinessLogic.class);
- private final OutputsBusinessLogic outputsBusinessLogic = Mockito.mock(OutputsBusinessLogic.class);
- private final CompositionBusinessLogic compositionBusinessLogic = Mockito.mock(CompositionBusinessLogic.class);
- private final ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic = Mockito.mock(ResourceDataMergeBusinessLogic.class);
- private final CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic = Mockito.mock(CsarArtifactsAndGroupsBusinessLogic.class);
- private final MergeInstanceUtils mergeInstanceUtils = Mockito.mock(MergeInstanceUtils.class);
- private final UiComponentDataConverter uiComponentDataConverter = Mockito.mock(UiComponentDataConverter.class);
- private final ToscaExportHandler toscaExportHandler = Mockito.mock(ToscaExportHandler.class);
- private final PolicyTypeOperation policyTypeOperation = Mockito.mock(PolicyTypeOperation.class);
- private final PolicyBusinessLogic policyBusinessLogic = Mockito.mock(PolicyBusinessLogic.class);
- private final ArtifactTypeOperation artifactTypeOperation = Mockito.mock(ArtifactTypeOperation.class);
- private final DataTypeBusinessLogic dataTypeBusinessLogic = Mockito.mock(DataTypeBusinessLogic.class);
- private final PolicyTypeBusinessLogic policyTypeBusinessLogic = Mockito.mock(PolicyTypeBusinessLogic.class);
- private final ModelOperation modelOperation = Mockito.mock(ModelOperation.class);
-
- private YamlTemplateParsingHandler yamlTemplateParsingHandler = Mockito.mock(YamlTemplateParsingHandler.class);
- @InjectMocks
- ResponseFormatManager responseManager = null;
- private final GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class);
- User user = null;
- Resource resourceResponse = null;
- Resource genericVF = null;
- Resource genericCR = null;
- Resource genericVFC = null;
- Resource genericPNF = null;
- Resource rootType = null;
- ComponentsUtils componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class));
- ArtifactsBusinessLogic artifactManager = new ArtifactsBusinessLogic(artifactCassandraDao, toscaExportHandler, csarUtils, lifecycleBl,
- userBusinessLogic, artifactsResolver, elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
- interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation, artifactTypeOperation);
- CsarOperation csarOperation = Mockito.mock(CsarOperation.class);
- @InjectMocks
- CsarBusinessLogic csarBusinessLogic ;
- Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<>();
- List<Resource> reslist;
- private GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class);
- protected ComponentDescriptionValidator componentDescriptionValidator = new ComponentDescriptionValidator(componentsUtils);
- protected ComponentProjectCodeValidator componentProjectCodeValidator = new ComponentProjectCodeValidator(componentsUtils);
- protected ComponentIconValidator componentIconValidator = new ComponentIconValidator(componentsUtils);
- protected ComponentContactIdValidator componentContactIdValidator = new ComponentContactIdValidator(componentsUtils);
- protected ComponentTagsValidator componentTagsValidator = new ComponentTagsValidator(componentsUtils);
- protected ComponentNameValidator componentNameValidator = new ComponentNameValidator(componentsUtils, toscaOperationFacade);
- private ComponentValidator componentValidator = createComponentValidator();
- private SoftwareInformationBusinessLogic softwareInformationBusinessLogic = Mockito.mock(SoftwareInformationBusinessLogic.class);
-
- private ComponentValidator createComponentValidator() {
- List<ComponentFieldValidator> componentFieldValidators = Arrays.asList(componentNameValidator,
- componentDescriptionValidator, componentProjectCodeValidator,
- componentIconValidator, componentContactIdValidator,
- componentTagsValidator);
- return new ComponentValidator(componentsUtils,componentFieldValidators);
- }
-
- ResourceBusinessLogic bl;
-
- @Before
- public void setup() {
- MockitoAnnotations.openMocks(this);
- Mockito.reset(propertyOperation);
-
- // Elements
- mockElementDao = new ElementOperationMock();
-
-
- // User data and management
- user = new User();
- user.setUserId("jh0003");
- user.setFirstName("Jimmi");
- user.setLastName("Hendrix");
- user.setRole(Role.ADMIN.name());
-
- when(mockUserAdmin.getUser("jh0003", false)).thenReturn(user);
- when(userValidations.validateUserExists(user.getUserId())).thenReturn(user);
- when(userValidations.validateUserNotEmpty(eq(user), anyString())).thenReturn(user);
- // Servlet Context attributes
- when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
- when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR))
- .thenReturn(webAppContextWrapper);
- when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext);
- when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao);
-
- Either<Boolean, StorageOperationStatus> eitherFalse = Either.left(true);
- when(toscaOperationFacade.validateComponentNameExists("tosca.nodes.Root", ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
- .thenReturn(eitherFalse);
-
-
- Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(true);
- when(toscaOperationFacade.validateComponentNameExists("alreadyExists", ResourceTypeEnum.VFC,
- ComponentTypeEnum.RESOURCE)).thenReturn(eitherCountExist);
-
- Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false);
- when(toscaOperationFacade.validateComponentNameExists(eq(RESOURCE_NAME), any(ResourceTypeEnum.class),
- eq(ComponentTypeEnum.RESOURCE))).thenReturn(eitherCount);
- Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true);
- when(toscaOperationFacade.validateToscaResourceNameExists("tosca.nodes.Root")).thenReturn(validateDerivedExists);
-
- Either<Boolean, StorageOperationStatus> validateDerivedNotExists = Either.left(false);
- when(toscaOperationFacade.validateToscaResourceNameExists("kuku")).thenReturn(validateDerivedNotExists);
- when(graphLockOperation.lockComponent(anyString(), eq(NodeTypeEnum.Resource)))
- .thenReturn(StorageOperationStatus.OK);
- when(graphLockOperation.lockComponentByName(anyString(), eq(NodeTypeEnum.Resource)))
- .thenReturn(StorageOperationStatus.OK);
-
- // createResource
- resourceResponse = createResourceObject(true);
- Either<Resource, StorageOperationStatus> eitherCreate = Either.left(resourceResponse);
- when(toscaOperationFacade.createToscaComponent(any(Resource.class))).thenReturn(eitherCreate);
- when(catalogOperation.updateCatalog(Mockito.any(), Mockito.any())).thenReturn(ActionStatus.OK);
- Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<>();
- when(applicationDataTypeCache.getAll(null)).thenReturn(Either.left(emptyDataTypes));
- when(mockJanusGraphDao.commit()).thenReturn(JanusGraphOperationStatus.OK);
- when(policyTypeOperation.getLatestPolicyTypeByType(any(String.class), any(String.class)))
- .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
- // BL object
- artifactManager.setNodeTemplateOperation(nodeTemplateOperation);
- bl = new ResourceBusinessLogic(mockElementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic,
- interfaceOperation, interfaceLifecycleTypeOperation, artifactManager, componentInstanceBusinessLogic,
- resourceImportManager, inputsBusinessLogic, outputsBusinessLogic, compositionBusinessLogic, resourceDataMergeBusinessLogic,
- csarArtifactsAndGroupsBusinessLogic, mergeInstanceUtils, uiComponentDataConverter, csarBusinessLogic,
- artifactToscaOperation, propertyBusinessLogic, componentContactIdValidator, componentNameValidator,
- componentTagsValidator, componentValidator, componentIconValidator, componentProjectCodeValidator,
- componentDescriptionValidator, policyBusinessLogic, modelBusinessLogic, dataTypeBusinessLogic, policyTypeBusinessLogic, modelOperation);
- bl.setElementDao(mockElementDao);
- bl.setUserAdmin(mockUserAdmin);
- bl.setCapabilityTypeOperation(capabilityTypeOperation);
- bl.setComponentsUtils(componentsUtils);
- bl.setLifecycleManager(lifecycleBl);
- bl.setArtifactsManager(artifactManager);
- bl.setGraphLockOperation(graphLockOperation);
- bl.setPropertyOperation(propertyOperation);
- bl.setJanusGraphDao(mockJanusGraphDao);
- bl.setApplicationDataTypeCache(applicationDataTypeCache);
- bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic);
- bl.setCatalogOperations(catalogOperation);
- toscaOperationFacade.setNodeTypeOperation(nodeTypeOperation);
- csarBusinessLogic.setComponentsUtils(componentsUtils);
- toscaOperationFacade.setTopologyTemplateOperation(topologyTemplateOperation);
- bl.setToscaOperationFacade(toscaOperationFacade);
- bl.setUserValidations(userValidations);
- bl.setInterfaceTypeOperation(interfaceTypeOperation);
- bl.setPolicyTypeOperation(policyTypeOperation);
-
- csarBusinessLogic.setCsarOperation(csarOperation);
- Resource resourceCsar = createResourceObjectCsar(true);
- setCanWorkOnResource(resourceCsar);
- Either<Component, StorageOperationStatus> oldResourceRes = Either.left(resourceCsar);
- when(toscaOperationFacade.getToscaFullElement(resourceCsar.getUniqueId())).thenReturn(oldResourceRes);
- responseManager = ResponseFormatManager.getInstance();
- bl.setComponentIconValidator(componentIconValidator);
- bl.setComponentNameValidator(componentNameValidator);
- bl.setComponentDescriptionValidator(componentDescriptionValidator);
- bl.setComponentTagsValidator(componentTagsValidator);
- bl.setComponentContactIdValidator(componentContactIdValidator);
- bl.setComponentProjectCodeValidator(componentProjectCodeValidator);
- bl.setComponentValidator(componentValidator);
- reslist = new ArrayList<>();
- reslist.add(resourceResponse);
- reslist.add(genericVF);
- reslist.add(genericCR);
- reslist.add(genericVFC);
- reslist.add(genericPNF);
- Either<List<Resource>, StorageOperationStatus> returneval= Either.left(reslist);
- when(toscaOperationFacade.getAllCertifiedResources(true, true)).thenReturn(returneval);
- when(toscaOperationFacade.validateComponentNameUniqueness("Resource", ResourceTypeEnum.CR, ComponentTypeEnum.RESOURCE)).thenReturn(Either.left(true));
- Either<List<Resource>, StorageOperationStatus> returnevalexception= Either.right(StorageOperationStatus.BAD_REQUEST);
- when(toscaOperationFacade.getAllCertifiedResources(false, false)).thenReturn(returnevalexception);
- }
-
- @Test(expected = ComponentException.class)
- public void createResourcesFromYamlNodeTypesList() throws IOException {
- Map<String, Object> mappedToscaTemplate = new HashMap<>();
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
- List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
- Map<String, NodeTypeInfo> nodeTypesInfo = new HashMap<>();
- bl.createResourcesFromYamlNodeTypesList(
- "",
- resourceResponse,
- mappedToscaTemplate,
- false,
- nodeTypesArtifactsToHandle,
- nodeTypesNewCreatedArtifacts,
- nodeTypesInfo,
- new CsarInfo(user, "abcd1234", new HashMap<>(), RESOURCE_NAME, "template name", ImportUtilsTest.loadFileNameToJsonString("normative-types-new-webServer.yml"),true), "");
- }
-
- @Test
- public void handleNodeTypeArtifactsTest() {
- Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = new HashMap<>();
- List<ArtifactDefinition> defs = new ArrayList<>();
- defs.add(new ArtifactDefinition());
- nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, defs);
- nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, defs);
- assertTrue(bl.handleNodeTypeArtifacts(resourceResponse, nodeTypeArtifactsToHandle, new ArrayList<>(), user, true, true).isRight());
- }
-
- @Test
- public void getUiComponentDataTransferByComponentIdTest() {
- when(toscaOperationFacade.getToscaElement(eq(""), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(genericCR));
- assertTrue(bl.getUiComponentDataTransferByComponentId("", new ArrayList<>()).isLeft());
- when(toscaOperationFacade.getToscaElement(eq(""), Mockito.any(ComponentParametersView.class))).thenReturn(Either.right(StorageOperationStatus.OK));
- assertTrue(bl.getUiComponentDataTransferByComponentId("", new ArrayList<>()).isRight());
- }
-
- @Test
- public void shouldUpgradeToLatestDerivedTest() {
- createCR();
- createVF();
- when(toscaOperationFacade.shouldUpgradeToLatestDerived(genericCR)).thenReturn(Either.left(genericCR));
- when(toscaOperationFacade.shouldUpgradeToLatestDerived(genericVFC)).thenReturn(Either.right(StorageOperationStatus.OK));
- assertTrue(bl.shouldUpgradeToLatestDerived(genericVF).isLeft());
- assertTrue(bl.shouldUpgradeToLatestDerived(genericCR).isLeft());
- }
-
- private Resource createResourceObject(boolean afterCreate) {
- Resource resource = new Resource();
- resource.setName(RESOURCE_NAME);
- resource.setToscaResourceName(RESOURCE_TOSCA_NAME);
- resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY);
- resource.setDescription("My short description");
- List<String> tgs = new ArrayList<>();
- tgs.add("test");
- tgs.add(resource.getName());
- resource.setTags(tgs);
- List<String> template = new ArrayList<>();
- template.add("tosca.nodes.Root");
- resource.setDerivedFrom(template);
- resource.setVendorName("Motorola");
- resource.setVendorRelease("1.0.0");
- resource.setContactId("ya5467");
- resource.setIcon("defaulticon");
-
- if (afterCreate) {
- resource.setName(resource.getName());
- resource.setVersion("0.1");
- resource.setUniqueId(resource.getName()
- .toLowerCase() + ":" + resource.getVersion());
- resource.setCreatorUserId(user.getUserId());
- resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
- resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- }
- return resource;
- }
-
- private Resource createResourceObjectWithModel(boolean afterCreate) {
- Resource resource = new Resource();
- resource.setName(RESOURCE_NAME);
- resource.setToscaResourceName(RESOURCE_TOSCA_NAME);
- resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY);
- resource.setDescription("My short description");
- List<String> tgs = new ArrayList<>();
- tgs.add("test");
- tgs.add(resource.getName());
- resource.setTags(tgs);
- List<String> template = new ArrayList<>();
- template.add("tosca.nodes.Root");
- resource.setDerivedFrom(template);
- resource.setVendorName("Motorola");
- resource.setVendorRelease("1.0.0");
- resource.setContactId("ya5467");
- resource.setIcon("defaulticon");
- resource.setModel("Test Model");
-
- if (afterCreate) {
- resource.setName(resource.getName());
- resource.setVersion("0.1");
- resource.setUniqueId(resource.getName()
- .toLowerCase() + ":" + resource.getVersion());
- resource.setCreatorUserId(user.getUserId());
- resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
- resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- }
- return resource;
- }
-
- private Resource createResourceObjectCsar(boolean afterCreate) {
- Resource resource = new Resource();
- resource.setName(RESOURCE_NAME);
- resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY);
- resource.setDescription("My short description");
- List<String> tgs = new ArrayList<>();
- tgs.add("test");
- tgs.add(resource.getName());
- resource.setTags(tgs);
- List<String> template = new ArrayList<>();
- template.add("tosca.nodes.Root");
- resource.setDerivedFrom(template);
- resource.setVendorName("Motorola");
- resource.setVendorRelease("1.0.0");
- resource.setResourceVendorModelNumber("");
- resource.setContactId("ya5467");
- resource.setIcon("MyIcon");
- resource.setCsarUUID("valid_vf.csar");
- resource.setCsarVersion("1");
-
- if (afterCreate) {
- resource.setName(resource.getName());
- resource.setVersion("0.1");
-
- resource.setUniqueId(resource.getName()
- .toLowerCase() + ":" + resource.getVersion());
- resource.setCreatorUserId(user.getUserId());
- resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
- resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- }
- return resource;
- }
-
- private Resource setCanWorkOnResource(Resource resource) {
- resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- resource.setLastUpdaterUserId(user.getUserId());
- return resource;
- }
-
- @Test
- public void testHappyScenario() {
- validateUserRoles(Role.ADMIN, Role.DESIGNER);
- Resource resource = createResourceObject(false);
- Resource createdResource = null;
- try {
- when(toscaOperationFacade
- .validateComponentNameAndModelExists(resource.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
- .thenReturn(Either.left(false));
- createdResource = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertThat(createResourceObject(true)).isEqualTo(createdResource);
- } catch (ComponentException e) {
- assertThat(new Integer(200)).isEqualTo(e.getResponseFormat()
- .getStatus());
- }
- }
-
- @Test
- public void testUpdateHappyScenario() {
- Resource resource = createResourceObjectCsar(true);
- setCanWorkOnResource(resource);
- validateUserRoles(Role.ADMIN, Role.DESIGNER);
- Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = Either.left(resource);
- when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, resource.getCsarUUID(), resource.getSystemName())).thenReturn(resourceLinkedToCsarRes);
- Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true);
- when(toscaOperationFacade.validateToscaResourceNameExists("tosca.nodes.Root")).thenReturn(validateDerivedExists);
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
- try {
- assertThat(resource.getUniqueId()).isEqualTo(bl.validateAndUpdateResourceFromCsar(resource, user, null, null, resource.getUniqueId()).getUniqueId());
- } catch (ComponentException e) {
- assertThat(e.getResponseFormat().getStatus()).isEqualTo(200);
- }
- }
-
- @Test
- public void testUpdateUnhappyScenario() {
- Resource resource = createResourceObjectCsar(true);
- final var csarVersionId = "csarVersionId";
- resource.setCsarVersionId(csarVersionId);
-
- final var vendorSoftwareProduct = new VendorSoftwareProduct();
- vendorSoftwareProduct.setFileMap(new HashMap<>());
- vendorSoftwareProduct.setModelList(Collections.emptyList());
- setCanWorkOnResource(resource);
- validateUserRoles(Role.ADMIN, Role.DESIGNER);
-
- when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, resource.getCsarUUID(), resource.getSystemName())).thenReturn(Either.left(resource));
- when(toscaOperationFacade.validateToscaResourceNameExists("tosca.nodes.Root")).thenReturn(Either.left(true));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(Either.left(setCanWorkOnResource(resource)));
- when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(Either.left(resource));
- when(csarOperation.findVsp("valid_vf.csar", csarVersionId, user)).thenReturn(Optional.of(vendorSoftwareProduct));
-
- try {
- Resource createdResource = bl.validateAndUpdateResourceFromCsar(resource, user, null, "", resource.getUniqueId());
- assertThat(resource.getUniqueId()).isEqualTo(createdResource.getUniqueId());
- } catch (ComponentException e) {
- assertThat(e.getResponseFormat().getStatus()).isEqualTo(400);
- }
- try {
- resource.setCsarVersion("2");
- when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, resource.getCsarUUID(), resource.getSystemName())).thenReturn(Either.left(resource));
- bl.validateAndUpdateResourceFromCsar(resource, user, null, null, resource.getUniqueId());
- } catch (ComponentException e) {
- assertThat(e.getResponseFormat().getStatus()).isEqualTo(400);
- }
- }
- /* CREATE validations - start ***********************/
- // Resource name - start
-
- @Test
- public void testFailedResourceValidations() {
- testResourceNameExist();
- testResourceNameEmpty();
- // testResourceNameExceedsLimit();
- testResourceNameWrongFormat();
- testResourceDescExceedsLimitCreate();
- testResourceDescNotEnglish();
- testResourceDescriptionEmpty();
- testResourceDescriptionMissing();
- testResourceIconMissing();
- testResourceIconInvalid();
- testResourceIconExceedsLimit();
- testResourceTagNotExist();
- testResourceTagEmpty();
- testTagsExceedsLimitCreate();
- testTagsNoServiceName();
- testInvalidTag();
-
- testContactIdTooLong();
- testContactIdWrongFormatCreate();
- testResourceContactIdEmpty();
- testResourceContactIdMissing();
- testVendorNameExceedsLimit();
- testVendorNameWrongFormatCreate();
- testVendorReleaseWrongFormat();
- testVendorReleaseExceedsLimitCreate();
- testResourceVendorModelNumberExceedsLimit();
- testResourceVendorNameMissing();
- testResourceVendorReleaseMissing();
- testResourceCategoryExist();
- testResourceBadCategoryCreate();
- testHappyScenarioCostLicenseType();
- testCostWrongFormatCreate();
- testLicenseTypeWrongFormatCreate();
- testResourceTemplateNotExist();
- testResourceTemplateEmpty();
- testResourceTemplateInvalid();
- }
-
- private void testResourceNameExist() {
- String resourceName = "alreadyExists";
- Resource resourceExist = createResourceObject(false);
- resourceExist.setName(resourceName);
- resourceExist.getTags()
- .add(resourceName);
- validateUserRoles(Role.ADMIN, Role.DESIGNER);
- when(toscaOperationFacade
- .validateComponentNameAndModelExists(resourceName, null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
- .thenReturn(Either.left(true));
- try {
- bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
- ComponentTypeEnum.RESOURCE.getValue(), resourceName);
- }
- }
-
- private void testResourceNameEmpty() {
- Resource resourceExist = createResourceObject(false);
- resourceExist.setName(null);
-
- try {
- bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
- }
- }
-
- private void testResourceNameExceedsLimit() {
- Resource resourceExccedsNameLimit = createResourceObject(false);
- // 51 chars, the limit is 50
- String tooLongResourceName = "zCRCAWjqte0DtgcAAMmcJcXeNubeX1p1vOZNTShAHOYNAHvV3iK";
- resourceExccedsNameLimit.setName(tooLongResourceName);
-
- try {
- bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT,
- ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
- }
- }
-
- private void testResourceNameWrongFormat() {
- Resource resource = createResourceObject(false);
- // contains :
- String nameWrongFormat = "ljg?fd";
- resource.setName(nameWrongFormat);
-
- try {
- bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
- }
- }
-
- // Resource name - end
- // Resource description - start
- private void testResourceDescExceedsLimitCreate() {
- Resource resourceExccedsDescLimit = createResourceObject(false);
- // 1025 chars, the limit is 1024
- String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
- + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
- + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
- + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
- + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
- + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
- + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
- + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
-
- resourceExccedsDescLimit.setDescription(tooLongResourceDesc);
- try {
- bl.createResource(resourceExccedsDescLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT,
- ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
- }
- }
-
- private void testResourceDescNotEnglish() {
- Resource notEnglish = createResourceObject(false);
- // Not english
- String notEnglishDesc = "\uC2B5";
- notEnglish.setDescription(notEnglishDesc);
-
- try {
- bl.createResource(notEnglish, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.COMPONENT_INVALID_DESCRIPTION,
- ComponentTypeEnum.RESOURCE.getValue());
- }
- }
-
- private void testResourceDescriptionEmpty() {
- Resource resourceExist = createResourceObject(false);
- resourceExist.setDescription("");
-
- try {
- bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION,
- ComponentTypeEnum.RESOURCE.getValue());
- }
- }
-
- private void testResourceDescriptionMissing() {
- Resource resourceExist = createResourceObject(false);
- resourceExist.setDescription(null);
-
- try {
- bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION,
- ComponentTypeEnum.RESOURCE.getValue());
- }
- }
- // Resource description - end
- // Resource icon start
-
- private void testResourceIconMissing() {
- Resource resourceExist = createResourceObject(false);
- resourceExist.setIcon(null);
- when(toscaOperationFacade
- .validateComponentNameAndModelExists(resourceExist.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
- .thenReturn(Either.left(false));
- try {
- bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.RESOURCE.getValue());
- }
- }
-
- private void testResourceIconInvalid() {
- Resource resourceExist = createResourceObject(false);
- resourceExist.setIcon("kjk3453^&");
-
- try {
- bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue());
- }
- }
-
- private void testResourceIconExceedsLimit() {
- Resource resourceExist = createResourceObject(false);
- resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf");
- try {
- bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT,
- ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH);
- }
- }
-
- // Resource icon end
- // Resource tags - start
- private void testResourceTagNotExist() {
- Resource resourceExist = createResourceObject(false);
- resourceExist.setTags(null);
- try {
- bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.COMPONENT_MISSING_TAGS);
- }
- }
-
- private void testResourceTagEmpty() {
- Resource resourceExist = createResourceObject(false);
- resourceExist.setTags(new ArrayList<>());
- try {
- bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.COMPONENT_MISSING_TAGS);
- }
- }
-
- private void testTagsExceedsLimitCreate() {
- Resource resourceExccedsNameLimit = createResourceObject(false);
- String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ";
- String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW";
- String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE";
- String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb";
- String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr";
- String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
- String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
- String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd";
- String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
- String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
- String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh";
- String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj";
- String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk";
- String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs";
- String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz";
- String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx";
- String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2";
- String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3";
- String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4";
- String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5";
- String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0";
-
- List<String> tagsList = new ArrayList<>();
- tagsList.add(tag1);
- tagsList.add(tag2);
- tagsList.add(tag3);
- tagsList.add(tag4);
- tagsList.add(tag5);
- tagsList.add(tag6);
- tagsList.add(tag7);
- tagsList.add(tag8);
- tagsList.add(tag9);
- tagsList.add(tag10);
- tagsList.add(tag11);
- tagsList.add(tag12);
- tagsList.add(tag13);
- tagsList.add(tag14);
- tagsList.add(tag15);
- tagsList.add(tag16);
- tagsList.add(tag17);
- tagsList.add(tag18);
- tagsList.add(tag19);
- tagsList.add(tag20);
- tagsList.add(tag21);
- tagsList.add(resourceExccedsNameLimit.getName());
-
- resourceExccedsNameLimit.setTags(tagsList);
- try {
- bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT,
- "" + ValidationUtils.TAG_LIST_MAX_LENGTH);
- }
- }
-
- private void testTagsSingleExceedsLimit() {
- Resource resourceExccedsNameLimit = createResourceObject(false);
- String tag1 = "afzs2qLBb5X6tZhiunkcEwiFX1qRQY8YZl3y3Du5M5xeQY5Nq9afcFHDZ9HaURw43gH27nAUWM36bMbMylwTFSzzNV8NO4v4ripe6Q15Vc2nPOFI";
- String tag2 = resourceExccedsNameLimit.getName();
- List<String> tagsList = new ArrayList<>();
- tagsList.add(tag1);
- tagsList.add(tag2);
-
- resourceExccedsNameLimit.setTags(tagsList);
- try {
- bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT,
- "" + ValidationUtils.TAG_MAX_LENGTH);
- }
- }
-
- private void testTagsNoServiceName() {
- Resource serviceExccedsNameLimit = createResourceObject(false);
- String tag1 = "afzs2qLBb";
- List<String> tagsList = new ArrayList<>();
- tagsList.add(tag1);
- serviceExccedsNameLimit.setTags(tagsList);
- try {
- bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME);
- }
- }
-
- private void testInvalidTag() {
- Resource serviceExccedsNameLimit = createResourceObject(false);
- String tag1 = "afzs2qLBb%#%";
- List<String> tagsList = new ArrayList<>();
- tagsList.add(tag1);
- serviceExccedsNameLimit.setTags(tagsList);
- try {
- bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.INVALID_FIELD_FORMAT, new String[] { "Resource", "tag" });
- }
- }
-
- // Resource tags - stop
- // Resource contact start
-
- private void testContactIdTooLong() {
- Resource resourceContactId = createResourceObject(false);
- // 59 chars instead of 50
- String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId";
- resourceContactId.setContactId(contactIdTooLong);
-
- try {
- bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
- }
- }
-
- private void testContactIdWrongFormatCreate() {
- Resource resourceContactId = createResourceObject(false);
- // 3 letters and 3 digits and special characters
- String contactIdFormatWrong = "yrt134!!!";
- resourceContactId.setContactId(contactIdFormatWrong);
- try {
- bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
- }
- }
-
- private void testResourceContactIdEmpty() {
- Resource resourceExist = createResourceObject(false);
- resourceExist.setContactId("");
- try {
- bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
- }
- }
-
- private void testResourceContactIdMissing() {
- Resource resourceExist = createResourceObject(false);
- resourceExist.setContactId(null);
- try {
- bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
- }
- }
-
- private void testVendorNameExceedsLimit() {
- Resource resourceExccedsVendorNameLimit = createResourceObject(false);
- String tooLongVendorName = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
- resourceExccedsVendorNameLimit.setVendorName(tooLongVendorName);
- try {
- bl.createResource(resourceExccedsVendorNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
- "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
- }
- }
-
- private void testResourceVendorModelNumberExceedsLimit() {
- Resource resourceExccedsVendorModelNumberLimit = createResourceObject(false);
- String tooLongVendorModelNumber = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
- resourceExccedsVendorModelNumberLimit.setResourceVendorModelNumber(tooLongVendorModelNumber);
- try {
- bl.createResource(resourceExccedsVendorModelNumberLimit, AuditingActionEnum.CREATE_RESOURCE, user, null,
- null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
- "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
- }
- }
-
- private void testVendorNameWrongFormatCreate() {
- Resource resource = createResourceObject(false);
- // contains *
- String nameWrongFormat = "ljg*fd";
- resource.setVendorName(nameWrongFormat);
- try {
- bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.INVALID_VENDOR_NAME, nameWrongFormat);
- }
- }
-
- private void testVendorReleaseWrongFormat() {
- Resource resource = createResourceObject(false);
- // contains >
- String vendorReleaseWrongFormat = "1>2";
- resource.setVendorRelease(vendorReleaseWrongFormat);
- try {
- bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.INVALID_VENDOR_RELEASE, vendorReleaseWrongFormat);
- }
- }
-
- private void testVendorReleaseExceedsLimitCreate() {
- Resource resourceExccedsNameLimit = createResourceObject(false);
- String tooLongVendorRelease = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
- resourceExccedsNameLimit.setVendorRelease(tooLongVendorRelease);
- try {
- bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT,
- "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
- }
- }
-
- private void testResourceVendorNameMissing() {
- Resource resourceExist = createResourceObject(false);
- resourceExist.setVendorName(null);
- try {
- bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.MISSING_VENDOR_NAME);
- }
- }
-
- private void testResourceVendorReleaseMissing() {
- Resource resourceExist = createResourceObject(false);
- resourceExist.setVendorRelease(null);
- try {
- bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.MISSING_VENDOR_RELEASE);
- }
- }
-
- // Resource vendor name/release stop
- // Category start
- private void testResourceCategoryExist() {
- Resource resourceExist = createResourceObject(false);
- resourceExist.setCategories(null);
- try {
- bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
- }
- }
-
- private void testResourceBadCategoryCreate() {
-
- Resource resourceExist = createResourceObject(false);
- resourceExist.setCategories(null);
- resourceExist.addCategory("koko", "koko");
- try {
- bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
- }
- }
-
- // Category stop
- // Cost start
- private void testHappyScenarioCostLicenseType() {
- Resource createResourceObject = createResourceObject(false);
- Resource createResourceObjectAfterCreate = createResourceObject(true);
- // Adding cost and licenseType to basic mock
- Either<Resource, StorageOperationStatus> eitherCreate = Either.left(createResourceObjectAfterCreate);
- when(toscaOperationFacade.createToscaComponent(any(Resource.class))).thenReturn(eitherCreate);
-
- String cost = "123.456";
- String licenseType = "User";
- createResourceObject.setCost(cost);
- createResourceObject.setLicenseType(licenseType);
- Resource createdResource;
- try {
- createdResource = bl.createResource(createResourceObject, AuditingActionEnum.CREATE_RESOURCE, user, null,
- null);
- createResourceObjectAfterCreate.setCost(cost);
- createResourceObjectAfterCreate.setLicenseType(licenseType);
- assertThat(createResourceObjectAfterCreate).isEqualTo(createdResource);
- } catch (ComponentException e) {
- assertThat(new Integer(200)).isEqualTo(e.getResponseFormat()
- .getStatus());
- }
- }
-
- private void testCostWrongFormatCreate() {
- Resource resourceCost = createResourceObject(false);
- // Comma instead of fullstop
- String cost = "12356,464";
- resourceCost.setCost(cost);
- try {
- bl.createResource(resourceCost, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.INVALID_CONTENT);
- }
- }
-
- // Cost stop
- // License type start
- private void testLicenseTypeWrongFormatCreate() {
- Resource resourceLicenseType = createResourceObject(false);
- // lowcase
- String licenseType = "cpu";
- resourceLicenseType.setLicenseType(licenseType);
- try {
- bl.createResource(resourceLicenseType, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.INVALID_CONTENT);
- }
- }
-
- // License type stop
- // Derived from start
- private void testResourceTemplateNotExist() {
- Resource resourceExist = createResourceObject(false);
- List<String> list = null;
- resourceExist.setDerivedFrom(list);
- try {
- bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
- }
- }
-
- private void testResourceTemplateEmpty() {
- Resource resourceExist = createResourceObject(false);
- resourceExist.setDerivedFrom(new ArrayList<>());
- try {
- bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
- }
- }
-
- private void testResourceTemplateInvalid() {
- Resource resourceExist = createResourceObject(false);
- ArrayList<String> derivedFrom = new ArrayList<>();
- derivedFrom.add("kuku");
- resourceExist.setDerivedFrom(derivedFrom);
- try {
- bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.PARENT_RESOURCE_NOT_FOUND);
- }
- }
-
- // Derived from stop
- private void assertComponentException(ComponentException e, ActionStatus expectedStatus, String... variables) {
- ResponseFormat actualResponse = e.getResponseFormat() != null ? e.getResponseFormat()
- : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
- assertResponse(actualResponse, expectedStatus, variables);
- }
-
- private void assertResponse(ResponseFormat actualResponse, ActionStatus expectedStatus, String... variables) {
- ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables);
- assertThat(expectedResponse.getStatus()).isEqualTo(actualResponse.getStatus());
- assertThat(expectedResponse.getFormattedMessage()).isEqualTo(actualResponse.getFormattedMessage());
- }
-
- private void assertResponse(Either<Resource, ResponseFormat> createResponse, ActionStatus expectedStatus,
- String... variables) {
- assertResponse(createResponse.right()
- .value(), expectedStatus, variables);
- }
-
- // UPDATE tests - start
- // Resource name
- @Test
- public void testResourceNameWrongFormat_UPDATE() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
- // contains *
- String nameWrongFormat = "ljg*fd";
- updatedResource.setName(nameWrongFormat);
-
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
- try {
- bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
- }
- }
-
- @Test
- public void testResourceNameAfterCertify_UPDATE() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate);
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
-
- String name = "ljg";
- updatedResource.setName(name);
- resource.setVersion("1.0");
-
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
- try {
- bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
- }
- }
-
- @Test
- public void testResourceNameAlreadyExist_UPDATE() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
-
- String resourceName = "alreadyExists";
- updatedResource.setName(resourceName);
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(updatedResource);
- when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
- try {
- bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
- ComponentTypeEnum.RESOURCE.getValue(), resourceName);
- }
- }
-
- //
-
- @Test
- public void testResourceDescExceedsLimit_UPDATE() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
-
- // 1025 chars, the limit is 1024
- String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
- + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
- + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
- + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
- + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
- + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
- + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
- + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
- updatedResource.setDescription(tooLongResourceDesc);
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
- try {
- bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT,
- ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
- }
- }
-
- @Test
- public void testIconWrongFormat_UPDATE() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
-
- // contains .
- String icon = "icon.jpg";
- updatedResource.setIcon(icon);
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
- try {
- bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue());
- }
- }
-
- @Test
- public void testIconAfterCertify_UPDATE() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
-
- // contains
- String icon = "icon";
- updatedResource.setIcon(icon);
-
- resource.setVersion("1.0");
- ;
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
- try {
- bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
- }
- }
-
- @Test
- public void testTagsExceedsLimit_UPDATE() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
-
- String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ";
- String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW";
- String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE";
- String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb";
- String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr";
- String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
- String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
- String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd";
- String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
- String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
- String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh";
- String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj";
- String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk";
- String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs";
- String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz";
- String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx";
- String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2";
- String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3";
- String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4";
- String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5";
- String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0";
-
- List<String> tagsList = new ArrayList<>();
- tagsList.add(tag1);
- tagsList.add(tag2);
- tagsList.add(tag3);
- tagsList.add(tag4);
- tagsList.add(tag5);
- tagsList.add(tag6);
- tagsList.add(tag7);
- tagsList.add(tag8);
- tagsList.add(tag9);
- tagsList.add(tag10);
- tagsList.add(tag11);
- tagsList.add(tag12);
- tagsList.add(tag13);
- tagsList.add(tag14);
- tagsList.add(tag15);
- tagsList.add(tag16);
- tagsList.add(tag17);
- tagsList.add(tag18);
- tagsList.add(tag19);
- tagsList.add(tag20);
- tagsList.add(tag21);
- tagsList.add(resource.getName());
-
- updatedResource.setTags(tagsList);
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
- try {
- bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT,
- "" + ValidationUtils.TAG_LIST_MAX_LENGTH);
- }
- }
-
- @Test
- public void testVendorNameWrongFormat_UPDATE() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
-
- // contains *
- String nameWrongFormat = "ljg*fd";
- updatedResource.setVendorName(nameWrongFormat);
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
- try {
- bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.INVALID_VENDOR_NAME, nameWrongFormat);
- }
- }
-
- @Test
- public void testVendorNameWrongFormat() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
-
- // contains *
- String nameWrongFormat = "ljg*fd";
- updatedResource.setVendorName(nameWrongFormat);
- resource.setVersion("1.0");
- ;
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
- try {
- bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.INVALID_VENDOR_NAME, nameWrongFormat);
- }
- }
-
- @Test
- public void testVendorReleaseExceedsLimit_UPDATE() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
- // 129 chars, the limit is 128
- String tooLongVendorRelease = "h1KSyJh9EspI8SPwAGu4VETfqWejeanuB1PCJBxJmJncYnrW0lnsEFFVRIukRJkwlOVnZCy8p38tjhANeZq3BGMHIawWR6ICl8Wi9mikRYALWgvJug00JrlQ0iPVKPLxy";
- updatedResource.setVendorRelease(tooLongVendorRelease);
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
- try {
- bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT,
- "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
- }
- }
-
- @Test
- public void testResourceBadCategory_UPDATE() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
-
- String resourceId = resource.getUniqueId();
- String badCategory = "ddfds";
- updatedResource.setCategories(null);
- updatedResource.addCategory(badCategory, "fikt");
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
- try {
- bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
- }
- }
-
- @Test(expected = ComponentException.class)
- public void createResourceFromCsarTest() {
- bl.createResourceFromCsar(resourceResponse, user, new HashMap<>(), "");
- }
-
- @Test()
- public void testCreateResourceFromCsarWithModel() throws URISyntaxException, ZipException {
+ private final InterfaceOperation interfaceOperation = Mockito.mock(InterfaceOperation.class);
+ private final ArtifactsOperations artifactToscaOperation = Mockito.mock(ArtifactsOperations.class);
+ private final PropertyBusinessLogic propertyBusinessLogic = Mockito.mock(PropertyBusinessLogic.class);
+ private final ArtifactsResolver artifactsResolver = Mockito.mock(ArtifactsResolver.class);
+ private final InterfaceLifecycleOperation interfaceLifecycleTypeOperation = Mockito.mock(InterfaceLifecycleOperation.class);
+ private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic = Mockito.mock(ComponentInstanceBusinessLogic.class);
+ private final ResourceImportManager resourceImportManager = Mockito.mock(ResourceImportManager.class);
+ private final InputsBusinessLogic inputsBusinessLogic = Mockito.mock(InputsBusinessLogic.class);
+ private final OutputsBusinessLogic outputsBusinessLogic = Mockito.mock(OutputsBusinessLogic.class);
+ private final CompositionBusinessLogic compositionBusinessLogic = Mockito.mock(CompositionBusinessLogic.class);
+ private final ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic = Mockito.mock(ResourceDataMergeBusinessLogic.class);
+ private final CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic = Mockito.mock(CsarArtifactsAndGroupsBusinessLogic.class);
+ private final MergeInstanceUtils mergeInstanceUtils = Mockito.mock(MergeInstanceUtils.class);
+ private final UiComponentDataConverter uiComponentDataConverter = Mockito.mock(UiComponentDataConverter.class);
+ private final ToscaExportHandler toscaExportHandler = Mockito.mock(ToscaExportHandler.class);
+ private final PolicyTypeOperation policyTypeOperation = Mockito.mock(PolicyTypeOperation.class);
+ private final PolicyBusinessLogic policyBusinessLogic = Mockito.mock(PolicyBusinessLogic.class);
+ private final ArtifactTypeOperation artifactTypeOperation = Mockito.mock(ArtifactTypeOperation.class);
+ private final DataTypeBusinessLogic dataTypeBusinessLogic = Mockito.mock(DataTypeBusinessLogic.class);
+ private final PolicyTypeBusinessLogic policyTypeBusinessLogic = Mockito.mock(PolicyTypeBusinessLogic.class);
+ private final ModelOperation modelOperation = Mockito.mock(ModelOperation.class);
+
+ private YamlTemplateParsingHandler yamlTemplateParsingHandler = Mockito.mock(YamlTemplateParsingHandler.class);
+ @InjectMocks
+ private ResponseFormatManager responseManager = null;
+ private final GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class);
+ private User user = null;
+ private Resource resourceResponse = null;
+ private Resource genericVF = null;
+ private Resource genericCR = null;
+ private Resource genericVFC = null;
+ private Resource genericPNF = null;
+ private Resource rootType = null;
+ private ComponentsUtils componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class));
+ private ArtifactsBusinessLogic artifactManager = new ArtifactsBusinessLogic(artifactCassandraDao, toscaExportHandler, csarUtils, lifecycleBl,
+ userBusinessLogic, artifactsResolver, elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
+ interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation, artifactTypeOperation);
+ private CsarOperation csarOperation = Mockito.mock(CsarOperation.class);
+ @InjectMocks
+ private CsarBusinessLogic csarBusinessLogic;
+ private Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<>();
+ private List<Resource> reslist;
+ private GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class);
+ protected ComponentDescriptionValidator componentDescriptionValidator = new ComponentDescriptionValidator(componentsUtils);
+ protected ComponentProjectCodeValidator componentProjectCodeValidator = new ComponentProjectCodeValidator(componentsUtils);
+ protected ComponentIconValidator componentIconValidator = new ComponentIconValidator(componentsUtils);
+ protected ComponentContactIdValidator componentContactIdValidator = new ComponentContactIdValidator(componentsUtils);
+ protected ComponentTagsValidator componentTagsValidator = new ComponentTagsValidator(componentsUtils);
+ protected ComponentNameValidator componentNameValidator = new ComponentNameValidator(componentsUtils, toscaOperationFacade);
+ private ComponentValidator componentValidator = createComponentValidator();
+ private SoftwareInformationBusinessLogic softwareInformationBusinessLogic = Mockito.mock(SoftwareInformationBusinessLogic.class);
+
+ private ComponentValidator createComponentValidator() {
+ List<ComponentFieldValidator> componentFieldValidators = Arrays.asList(componentNameValidator,
+ componentDescriptionValidator, componentProjectCodeValidator,
+ componentIconValidator, componentContactIdValidator,
+ componentTagsValidator);
+ return new ComponentValidator(componentsUtils, componentFieldValidators);
+ }
+
+ private ResourceBusinessLogic bl;
+
+ @BeforeEach
+ public void setup() {
+ MockitoAnnotations.openMocks(this);
+ Mockito.reset(propertyOperation);
+
+ // Elements
+ mockElementDao = new ElementOperationMock();
+
+ // User data and management
+ user = new User();
+ user.setUserId("jh0003");
+ user.setFirstName("Jimmi");
+ user.setLastName("Hendrix");
+ user.setRole(Role.ADMIN.name());
+
+ when(mockUserAdmin.getUser("jh0003", false)).thenReturn(user);
+ when(userValidations.validateUserExists(user.getUserId())).thenReturn(user);
+ when(userValidations.validateUserNotEmpty(eq(user), anyString())).thenReturn(user);
+ // Servlet Context attributes
+ when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
+ when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR))
+ .thenReturn(webAppContextWrapper);
+ when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext);
+ when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao);
+
+ Either<Boolean, StorageOperationStatus> eitherFalse = Either.left(true);
+ when(toscaOperationFacade.validateComponentNameExists("tosca.nodes.Root", ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
+ .thenReturn(eitherFalse);
+
+ Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(true);
+ when(toscaOperationFacade.validateComponentNameExists("alreadyExists", ResourceTypeEnum.VFC,
+ ComponentTypeEnum.RESOURCE)).thenReturn(eitherCountExist);
+
+ Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false);
+ when(toscaOperationFacade.validateComponentNameExists(eq(RESOURCE_NAME), any(ResourceTypeEnum.class),
+ eq(ComponentTypeEnum.RESOURCE))).thenReturn(eitherCount);
+ Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true);
+ when(toscaOperationFacade.validateToscaResourceNameExists("tosca.nodes.Root")).thenReturn(validateDerivedExists);
+
+ Either<Boolean, StorageOperationStatus> validateDerivedNotExists = Either.left(false);
+ when(toscaOperationFacade.validateToscaResourceNameExists("kuku")).thenReturn(validateDerivedNotExists);
+ when(graphLockOperation.lockComponent(anyString(), eq(NodeTypeEnum.Resource)))
+ .thenReturn(StorageOperationStatus.OK);
+ when(graphLockOperation.lockComponentByName(anyString(), eq(NodeTypeEnum.Resource)))
+ .thenReturn(StorageOperationStatus.OK);
+
+ // createResource
+ resourceResponse = createResourceObject(true);
+ Either<Resource, StorageOperationStatus> eitherCreate = Either.left(resourceResponse);
+ when(toscaOperationFacade.createToscaComponent(any(Resource.class))).thenReturn(eitherCreate);
+ when(catalogOperation.updateCatalog(Mockito.any(), Mockito.any())).thenReturn(ActionStatus.OK);
+ Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<>();
+ when(applicationDataTypeCache.getAll(null)).thenReturn(Either.left(emptyDataTypes));
+ when(mockJanusGraphDao.commit()).thenReturn(JanusGraphOperationStatus.OK);
+ when(policyTypeOperation.getLatestPolicyTypeByType(any(String.class), any(String.class)))
+ .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
+ // BL object
+ artifactManager.setNodeTemplateOperation(nodeTemplateOperation);
+ bl = new ResourceBusinessLogic(mockElementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic,
+ interfaceOperation, interfaceLifecycleTypeOperation, artifactManager, componentInstanceBusinessLogic,
+ resourceImportManager, inputsBusinessLogic, outputsBusinessLogic, compositionBusinessLogic, resourceDataMergeBusinessLogic,
+ csarArtifactsAndGroupsBusinessLogic, mergeInstanceUtils, uiComponentDataConverter, csarBusinessLogic,
+ artifactToscaOperation, propertyBusinessLogic, componentContactIdValidator, componentNameValidator,
+ componentTagsValidator, componentValidator, componentIconValidator, componentProjectCodeValidator,
+ componentDescriptionValidator, policyBusinessLogic, modelBusinessLogic, dataTypeBusinessLogic, policyTypeBusinessLogic, modelOperation);
+ bl.setElementDao(mockElementDao);
+ bl.setUserAdmin(mockUserAdmin);
+ bl.setCapabilityTypeOperation(capabilityTypeOperation);
+ bl.setComponentsUtils(componentsUtils);
+ bl.setLifecycleManager(lifecycleBl);
+ bl.setArtifactsManager(artifactManager);
+ bl.setGraphLockOperation(graphLockOperation);
+ bl.setPropertyOperation(propertyOperation);
+ bl.setJanusGraphDao(mockJanusGraphDao);
+ bl.setApplicationDataTypeCache(applicationDataTypeCache);
+ bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic);
+ bl.setCatalogOperations(catalogOperation);
+ toscaOperationFacade.setNodeTypeOperation(nodeTypeOperation);
+ csarBusinessLogic.setComponentsUtils(componentsUtils);
+ toscaOperationFacade.setTopologyTemplateOperation(topologyTemplateOperation);
+ bl.setToscaOperationFacade(toscaOperationFacade);
+ bl.setUserValidations(userValidations);
+ bl.setInterfaceTypeOperation(interfaceTypeOperation);
+ bl.setPolicyTypeOperation(policyTypeOperation);
+
+ csarBusinessLogic.setCsarOperation(csarOperation);
+ Resource resourceCsar = createResourceObjectCsar(true);
+ setCanWorkOnResource(resourceCsar);
+ Either<Component, StorageOperationStatus> oldResourceRes = Either.left(resourceCsar);
+ when(toscaOperationFacade.getToscaFullElement(resourceCsar.getUniqueId())).thenReturn(oldResourceRes);
+ responseManager = ResponseFormatManager.getInstance();
+ bl.setComponentIconValidator(componentIconValidator);
+ bl.setComponentNameValidator(componentNameValidator);
+ bl.setComponentDescriptionValidator(componentDescriptionValidator);
+ bl.setComponentTagsValidator(componentTagsValidator);
+ bl.setComponentContactIdValidator(componentContactIdValidator);
+ bl.setComponentProjectCodeValidator(componentProjectCodeValidator);
+ bl.setComponentValidator(componentValidator);
+ reslist = new ArrayList<>();
+ reslist.add(resourceResponse);
+ reslist.add(genericVF);
+ reslist.add(genericCR);
+ reslist.add(genericVFC);
+ reslist.add(genericPNF);
+ Either<List<Resource>, StorageOperationStatus> returneval = Either.left(reslist);
+ when(toscaOperationFacade.getAllCertifiedResources(true, true)).thenReturn(returneval);
+ when(toscaOperationFacade.validateComponentNameUniqueness("Resource", ResourceTypeEnum.CR, ComponentTypeEnum.RESOURCE)).thenReturn(
+ Either.left(true));
+ Either<List<Resource>, StorageOperationStatus> returnevalexception = Either.right(StorageOperationStatus.BAD_REQUEST);
+ when(toscaOperationFacade.getAllCertifiedResources(false, false)).thenReturn(returnevalexception);
+ }
+
+ @Test
+ void createResourcesFromYamlNodeTypesList() throws IOException {
+ Map<String, Object> mappedToscaTemplate = new HashMap<>();
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
+ List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
+ Map<String, NodeTypeInfo> nodeTypesInfo = new HashMap<>();
+ assertThrows(ComponentException.class, () -> {
+ bl.createResourcesFromYamlNodeTypesList(
+ "",
+ resourceResponse,
+ mappedToscaTemplate,
+ false,
+ nodeTypesArtifactsToHandle,
+ nodeTypesNewCreatedArtifacts,
+ nodeTypesInfo,
+ new CsarInfo(user, "abcd1234", new HashMap<>(), RESOURCE_NAME, "template name",
+ ImportUtilsTest.loadFileNameToJsonString("normative-types-new-webServer.yml"), true), "");
+ });
+ }
+
+ @Test
+ void handleNodeTypeArtifactsTest() {
+ Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = new HashMap<>();
+ List<ArtifactDefinition> defs = new ArrayList<>();
+ defs.add(new ArtifactDefinition());
+ nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, defs);
+ nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, defs);
+ assertTrue(bl.handleNodeTypeArtifacts(resourceResponse, nodeTypeArtifactsToHandle, new ArrayList<>(), user, true, true).isRight());
+ }
+
+ @Test
+ void getUiComponentDataTransferByComponentIdTest() {
+ when(toscaOperationFacade.getToscaElement(eq(""), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(genericCR));
+ assertTrue(bl.getUiComponentDataTransferByComponentId("", new ArrayList<>()).isLeft());
+ when(toscaOperationFacade.getToscaElement(eq(""), Mockito.any(ComponentParametersView.class))).thenReturn(
+ Either.right(StorageOperationStatus.OK));
+ assertTrue(bl.getUiComponentDataTransferByComponentId("", new ArrayList<>()).isRight());
+ }
+
+ @Test
+ void shouldUpgradeToLatestDerivedTest() {
+ createCR();
+ createVF();
+ when(toscaOperationFacade.shouldUpgradeToLatestDerived(genericCR)).thenReturn(Either.left(genericCR));
+ when(toscaOperationFacade.shouldUpgradeToLatestDerived(genericVFC)).thenReturn(Either.right(StorageOperationStatus.OK));
+ assertTrue(bl.shouldUpgradeToLatestDerived(genericVF).isLeft());
+ assertTrue(bl.shouldUpgradeToLatestDerived(genericCR).isLeft());
+ }
+
+ private Resource createResourceObject(boolean afterCreate) {
+ Resource resource = new Resource();
+ resource.setName(RESOURCE_NAME);
+ resource.setToscaResourceName(RESOURCE_TOSCA_NAME);
+ resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY);
+ resource.setDescription("My short description");
+ List<String> tgs = new ArrayList<>();
+ tgs.add("test");
+ tgs.add(resource.getName());
+ resource.setTags(tgs);
+ List<String> template = new ArrayList<>();
+ template.add("tosca.nodes.Root");
+ resource.setDerivedFrom(template);
+ resource.setVendorName("Motorola");
+ resource.setVendorRelease("1.0.0");
+ resource.setContactId("ya5467");
+ resource.setIcon("defaulticon");
+
+ if (afterCreate) {
+ resource.setName(resource.getName());
+ resource.setVersion("0.1");
+ resource.setUniqueId(resource.getName()
+ .toLowerCase() + ":" + resource.getVersion());
+ resource.setCreatorUserId(user.getUserId());
+ resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
+ resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+ return resource;
+ }
+
+ private Resource createResourceObjectWithModel(boolean afterCreate) {
+ Resource resource = new Resource();
+ resource.setName(RESOURCE_NAME);
+ resource.setToscaResourceName(RESOURCE_TOSCA_NAME);
+ resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY);
+ resource.setDescription("My short description");
+ List<String> tgs = new ArrayList<>();
+ tgs.add("test");
+ tgs.add(resource.getName());
+ resource.setTags(tgs);
+ List<String> template = new ArrayList<>();
+ template.add("tosca.nodes.Root");
+ resource.setDerivedFrom(template);
+ resource.setVendorName("Motorola");
+ resource.setVendorRelease("1.0.0");
+ resource.setContactId("ya5467");
+ resource.setIcon("defaulticon");
+ resource.setModel("Test Model");
+
+ if (afterCreate) {
+ resource.setName(resource.getName());
+ resource.setVersion("0.1");
+ resource.setUniqueId(resource.getName()
+ .toLowerCase() + ":" + resource.getVersion());
+ resource.setCreatorUserId(user.getUserId());
+ resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
+ resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+ return resource;
+ }
+
+ private Resource createResourceObjectCsar(boolean afterCreate) {
+ Resource resource = new Resource();
+ resource.setName(RESOURCE_NAME);
+ resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY);
+ resource.setDescription("My short description");
+ List<String> tgs = new ArrayList<>();
+ tgs.add("test");
+ tgs.add(resource.getName());
+ resource.setTags(tgs);
+ List<String> template = new ArrayList<>();
+ template.add("tosca.nodes.Root");
+ resource.setDerivedFrom(template);
+ resource.setVendorName("Motorola");
+ resource.setVendorRelease("1.0.0");
+ resource.setResourceVendorModelNumber("");
+ resource.setContactId("ya5467");
+ resource.setIcon("MyIcon");
+ resource.setCsarUUID("valid_vf.csar");
+ resource.setCsarVersion("1");
+
+ if (afterCreate) {
+ resource.setName(resource.getName());
+ resource.setVersion("0.1");
+
+ resource.setUniqueId(resource.getName()
+ .toLowerCase() + ":" + resource.getVersion());
+ resource.setCreatorUserId(user.getUserId());
+ resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
+ resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+ return resource;
+ }
+
+ private Resource setCanWorkOnResource(Resource resource) {
+ resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ resource.setLastUpdaterUserId(user.getUserId());
+ return resource;
+ }
+
+ @Test
+ void testHappyScenario() {
+ validateUserRoles(Role.ADMIN, Role.DESIGNER);
+ Resource resource = createResourceObject(false);
+ Resource createdResource = null;
+ try {
+ when(toscaOperationFacade
+ .validateComponentNameAndModelExists(resource.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
+ .thenReturn(Either.left(false));
+ createdResource = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertThat(createResourceObject(true)).isEqualTo(createdResource);
+ } catch (ComponentException e) {
+ assertThat(new Integer(200)).isEqualTo(e.getResponseFormat()
+ .getStatus());
+ }
+ }
+
+ @Test
+ void testUpdateHappyScenario() {
+ Resource resource = createResourceObjectCsar(true);
+ setCanWorkOnResource(resource);
+ validateUserRoles(Role.ADMIN, Role.DESIGNER);
+ Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = Either.left(resource);
+ when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, resource.getCsarUUID(),
+ resource.getSystemName())).thenReturn(resourceLinkedToCsarRes);
+ Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true);
+ when(toscaOperationFacade.validateToscaResourceNameExists("tosca.nodes.Root")).thenReturn(validateDerivedExists);
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+ try {
+ assertThat(resource.getUniqueId()).isEqualTo(
+ bl.validateAndUpdateResourceFromCsar(resource, user, null, null, resource.getUniqueId()).getUniqueId());
+ } catch (ComponentException e) {
+ assertThat(e.getResponseFormat().getStatus()).isEqualTo(200);
+ }
+ }
+
+ @Test
+ void testUpdateUnhappyScenario() {
+ Resource resource = createResourceObjectCsar(true);
+ final var csarVersionId = "csarVersionId";
+ resource.setCsarVersionId(csarVersionId);
+
+ final var vendorSoftwareProduct = new VendorSoftwareProduct();
+ vendorSoftwareProduct.setFileMap(new HashMap<>());
+ vendorSoftwareProduct.setModelList(Collections.emptyList());
+ setCanWorkOnResource(resource);
+ validateUserRoles(Role.ADMIN, Role.DESIGNER);
+
+ when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, resource.getCsarUUID(),
+ resource.getSystemName())).thenReturn(Either.left(resource));
+ when(toscaOperationFacade.validateToscaResourceNameExists("tosca.nodes.Root")).thenReturn(Either.left(true));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(Either.left(setCanWorkOnResource(resource)));
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(Either.left(resource));
+ when(csarOperation.findVsp("valid_vf.csar", csarVersionId, user)).thenReturn(Optional.of(vendorSoftwareProduct));
+
+ try {
+ Resource createdResource = bl.validateAndUpdateResourceFromCsar(resource, user, null, "", resource.getUniqueId());
+ assertThat(resource.getUniqueId()).isEqualTo(createdResource.getUniqueId());
+ } catch (ComponentException e) {
+ assertThat(e.getResponseFormat().getStatus()).isEqualTo(400);
+ }
+ try {
+ resource.setCsarVersion("2");
+ when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, resource.getCsarUUID(),
+ resource.getSystemName())).thenReturn(Either.left(resource));
+ bl.validateAndUpdateResourceFromCsar(resource, user, null, null, resource.getUniqueId());
+ } catch (ComponentException e) {
+ assertThat(e.getResponseFormat().getStatus()).isEqualTo(400);
+ }
+ }
+ /* CREATE validations - start ***********************/
+ // Resource name - start
+
+ @Test
+ void testFailedResourceValidations() {
+ testResourceNameExist();
+ testResourceNameEmpty();
+ // testResourceNameExceedsLimit();
+ testResourceNameWrongFormat();
+ testResourceDescExceedsLimitCreate();
+ testResourceDescNotEnglish();
+ testResourceDescriptionEmpty();
+ testResourceDescriptionMissing();
+ testResourceIconMissing();
+ testResourceIconInvalid();
+ testResourceIconExceedsLimit();
+ testResourceTagNotExist();
+ testResourceTagEmpty();
+ testTagsExceedsLimitCreate();
+ testTagsNoServiceName();
+ testInvalidTag();
+
+ testContactIdTooLong();
+ testContactIdWrongFormatCreate();
+ testResourceContactIdEmpty();
+ testResourceContactIdMissing();
+ testVendorNameExceedsLimit();
+ testVendorNameWrongFormatCreate();
+ testVendorReleaseWrongFormat();
+ testVendorReleaseExceedsLimitCreate();
+ testResourceVendorModelNumberExceedsLimit();
+ testResourceVendorNameMissing();
+ testResourceVendorReleaseMissing();
+ testResourceCategoryExist();
+ testResourceBadCategoryCreate();
+ testHappyScenarioCostLicenseType();
+ testCostWrongFormatCreate();
+ testLicenseTypeWrongFormatCreate();
+ testResourceTemplateNotExist();
+ testResourceTemplateEmpty();
+ testResourceTemplateInvalid();
+ }
+
+ private void testResourceNameExist() {
+ String resourceName = "alreadyExists";
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setName(resourceName);
+ resourceExist.getTags()
+ .add(resourceName);
+ validateUserRoles(Role.ADMIN, Role.DESIGNER);
+ when(toscaOperationFacade
+ .validateComponentNameAndModelExists(resourceName, null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
+ .thenReturn(Either.left(true));
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
+ ComponentTypeEnum.RESOURCE.getValue(), resourceName);
+ }
+ }
+
+ private void testResourceNameEmpty() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setName(null);
+
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
+ }
+ }
+
+ private void testResourceNameExceedsLimit() {
+ Resource resourceExccedsNameLimit = createResourceObject(false);
+ // 51 chars, the limit is 50
+ String tooLongResourceName = "zCRCAWjqte0DtgcAAMmcJcXeNubeX1p1vOZNTShAHOYNAHvV3iK";
+ resourceExccedsNameLimit.setName(tooLongResourceName);
+
+ try {
+ bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT,
+ ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
+ }
+ }
+
+ private void testResourceNameWrongFormat() {
+ Resource resource = createResourceObject(false);
+ // contains :
+ String nameWrongFormat = "ljg?fd";
+ resource.setName(nameWrongFormat);
+
+ try {
+ bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
+ }
+ }
+
+ // Resource name - end
+ // Resource description - start
+ private void testResourceDescExceedsLimitCreate() {
+ Resource resourceExccedsDescLimit = createResourceObject(false);
+ // 1025 chars, the limit is 1024
+ String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
+ + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
+ + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
+ + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
+ + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
+ + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
+ + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
+ + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
+
+ resourceExccedsDescLimit.setDescription(tooLongResourceDesc);
+ try {
+ bl.createResource(resourceExccedsDescLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT,
+ ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
+ }
+ }
+
+ private void testResourceDescNotEnglish() {
+ Resource notEnglish = createResourceObject(false);
+ // Not english
+ String notEnglishDesc = "\uC2B5";
+ notEnglish.setDescription(notEnglishDesc);
+
+ try {
+ bl.createResource(notEnglish, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_INVALID_DESCRIPTION,
+ ComponentTypeEnum.RESOURCE.getValue());
+ }
+ }
+
+ private void testResourceDescriptionEmpty() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setDescription("");
+
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION,
+ ComponentTypeEnum.RESOURCE.getValue());
+ }
+ }
+
+ private void testResourceDescriptionMissing() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setDescription(null);
+
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION,
+ ComponentTypeEnum.RESOURCE.getValue());
+ }
+ }
+ // Resource description - end
+ // Resource icon start
+
+ private void testResourceIconMissing() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setIcon(null);
+ when(toscaOperationFacade
+ .validateComponentNameAndModelExists(resourceExist.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
+ .thenReturn(Either.left(false));
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.RESOURCE.getValue());
+ }
+ }
+
+ private void testResourceIconInvalid() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setIcon("kjk3453^&");
+
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue());
+ }
+ }
+
+ private void testResourceIconExceedsLimit() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf");
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT,
+ ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH);
+ }
+ }
+
+ // Resource icon end
+ // Resource tags - start
+ private void testResourceTagNotExist() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setTags(null);
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_MISSING_TAGS);
+ }
+ }
+
+ private void testResourceTagEmpty() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setTags(new ArrayList<>());
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_MISSING_TAGS);
+ }
+ }
+
+ private void testTagsExceedsLimitCreate() {
+ Resource resourceExccedsNameLimit = createResourceObject(false);
+ String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ";
+ String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW";
+ String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE";
+ String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb";
+ String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr";
+ String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
+ String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
+ String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd";
+ String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
+ String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
+ String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh";
+ String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj";
+ String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk";
+ String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs";
+ String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz";
+ String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx";
+ String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2";
+ String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3";
+ String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4";
+ String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5";
+ String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0";
+
+ List<String> tagsList = new ArrayList<>();
+ tagsList.add(tag1);
+ tagsList.add(tag2);
+ tagsList.add(tag3);
+ tagsList.add(tag4);
+ tagsList.add(tag5);
+ tagsList.add(tag6);
+ tagsList.add(tag7);
+ tagsList.add(tag8);
+ tagsList.add(tag9);
+ tagsList.add(tag10);
+ tagsList.add(tag11);
+ tagsList.add(tag12);
+ tagsList.add(tag13);
+ tagsList.add(tag14);
+ tagsList.add(tag15);
+ tagsList.add(tag16);
+ tagsList.add(tag17);
+ tagsList.add(tag18);
+ tagsList.add(tag19);
+ tagsList.add(tag20);
+ tagsList.add(tag21);
+ tagsList.add(resourceExccedsNameLimit.getName());
+
+ resourceExccedsNameLimit.setTags(tagsList);
+ try {
+ bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT,
+ "" + ValidationUtils.TAG_LIST_MAX_LENGTH);
+ }
+ }
+
+ private void testTagsSingleExceedsLimit() {
+ Resource resourceExccedsNameLimit = createResourceObject(false);
+ String tag1 = "afzs2qLBb5X6tZhiunkcEwiFX1qRQY8YZl3y3Du5M5xeQY5Nq9afcFHDZ9HaURw43gH27nAUWM36bMbMylwTFSzzNV8NO4v4ripe6Q15Vc2nPOFI";
+ String tag2 = resourceExccedsNameLimit.getName();
+ List<String> tagsList = new ArrayList<>();
+ tagsList.add(tag1);
+ tagsList.add(tag2);
+
+ resourceExccedsNameLimit.setTags(tagsList);
+ try {
+ bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT,
+ "" + ValidationUtils.TAG_MAX_LENGTH);
+ }
+ }
+
+ private void testTagsNoServiceName() {
+ Resource serviceExccedsNameLimit = createResourceObject(false);
+ String tag1 = "afzs2qLBb";
+ List<String> tagsList = new ArrayList<>();
+ tagsList.add(tag1);
+ serviceExccedsNameLimit.setTags(tagsList);
+ try {
+ bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME);
+ }
+ }
+
+ private void testInvalidTag() {
+ Resource serviceExccedsNameLimit = createResourceObject(false);
+ String tag1 = "afzs2qLBb%#%";
+ List<String> tagsList = new ArrayList<>();
+ tagsList.add(tag1);
+ serviceExccedsNameLimit.setTags(tagsList);
+ try {
+ bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.INVALID_FIELD_FORMAT, new String[]{"Resource", "tag"});
+ }
+ }
+
+ // Resource tags - stop
+ // Resource contact start
+
+ private void testContactIdTooLong() {
+ Resource resourceContactId = createResourceObject(false);
+ // 59 chars instead of 50
+ String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId";
+ resourceContactId.setContactId(contactIdTooLong);
+
+ try {
+ bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
+ }
+ }
+
+ private void testContactIdWrongFormatCreate() {
+ Resource resourceContactId = createResourceObject(false);
+ // 3 letters and 3 digits and special characters
+ String contactIdFormatWrong = "yrt134!!!";
+ resourceContactId.setContactId(contactIdFormatWrong);
+ try {
+ bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
+ }
+ }
+
+ private void testResourceContactIdEmpty() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setContactId("");
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
+ }
+ }
+
+ private void testResourceContactIdMissing() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setContactId(null);
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
+ }
+ }
+
+ private void testVendorNameExceedsLimit() {
+ Resource resourceExccedsVendorNameLimit = createResourceObject(false);
+ String tooLongVendorName = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
+ resourceExccedsVendorNameLimit.setVendorName(tooLongVendorName);
+ try {
+ bl.createResource(resourceExccedsVendorNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
+ "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
+ }
+ }
+
+ private void testResourceVendorModelNumberExceedsLimit() {
+ Resource resourceExccedsVendorModelNumberLimit = createResourceObject(false);
+ String tooLongVendorModelNumber = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
+ resourceExccedsVendorModelNumberLimit.setResourceVendorModelNumber(tooLongVendorModelNumber);
+ try {
+ bl.createResource(resourceExccedsVendorModelNumberLimit, AuditingActionEnum.CREATE_RESOURCE, user, null,
+ null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
+ "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
+ }
+ }
+
+ private void testVendorNameWrongFormatCreate() {
+ Resource resource = createResourceObject(false);
+ // contains *
+ String nameWrongFormat = "ljg*fd";
+ resource.setVendorName(nameWrongFormat);
+ try {
+ bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.INVALID_VENDOR_NAME, nameWrongFormat);
+ }
+ }
+
+ private void testVendorReleaseWrongFormat() {
+ Resource resource = createResourceObject(false);
+ // contains >
+ String vendorReleaseWrongFormat = "1>2";
+ resource.setVendorRelease(vendorReleaseWrongFormat);
+ try {
+ bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.INVALID_VENDOR_RELEASE, vendorReleaseWrongFormat);
+ }
+ }
+
+ private void testVendorReleaseExceedsLimitCreate() {
+ Resource resourceExccedsNameLimit = createResourceObject(false);
+ String tooLongVendorRelease = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
+ resourceExccedsNameLimit.setVendorRelease(tooLongVendorRelease);
+ try {
+ bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT,
+ "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
+ }
+ }
+
+ private void testResourceVendorNameMissing() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setVendorName(null);
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.MISSING_VENDOR_NAME);
+ }
+ }
+
+ private void testResourceVendorReleaseMissing() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setVendorRelease(null);
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.MISSING_VENDOR_RELEASE);
+ }
+ }
+
+ // Resource vendor name/release stop
+ // Category start
+ private void testResourceCategoryExist() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setCategories(null);
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
+ }
+ }
+
+ private void testResourceBadCategoryCreate() {
+
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setCategories(null);
+ resourceExist.addCategory("koko", "koko");
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
+ }
+ }
+
+ // Category stop
+ // Cost start
+ private void testHappyScenarioCostLicenseType() {
+ Resource createResourceObject = createResourceObject(false);
+ Resource createResourceObjectAfterCreate = createResourceObject(true);
+ // Adding cost and licenseType to basic mock
+ Either<Resource, StorageOperationStatus> eitherCreate = Either.left(createResourceObjectAfterCreate);
+ when(toscaOperationFacade.createToscaComponent(any(Resource.class))).thenReturn(eitherCreate);
+
+ String cost = "123.456";
+ String licenseType = "User";
+ createResourceObject.setCost(cost);
+ createResourceObject.setLicenseType(licenseType);
+ Resource createdResource;
+ try {
+ createdResource = bl.createResource(createResourceObject, AuditingActionEnum.CREATE_RESOURCE, user, null,
+ null);
+ createResourceObjectAfterCreate.setCost(cost);
+ createResourceObjectAfterCreate.setLicenseType(licenseType);
+ assertThat(createResourceObjectAfterCreate).isEqualTo(createdResource);
+ } catch (ComponentException e) {
+ assertThat(new Integer(200)).isEqualTo(e.getResponseFormat()
+ .getStatus());
+ }
+ }
+
+ private void testCostWrongFormatCreate() {
+ Resource resourceCost = createResourceObject(false);
+ // Comma instead of fullstop
+ String cost = "12356,464";
+ resourceCost.setCost(cost);
+ try {
+ bl.createResource(resourceCost, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.INVALID_CONTENT);
+ }
+ }
+
+ // Cost stop
+ // License type start
+ private void testLicenseTypeWrongFormatCreate() {
+ Resource resourceLicenseType = createResourceObject(false);
+ // lowcase
+ String licenseType = "cpu";
+ resourceLicenseType.setLicenseType(licenseType);
+ try {
+ bl.createResource(resourceLicenseType, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.INVALID_CONTENT);
+ }
+ }
+
+ // License type stop
+ // Derived from start
+ private void testResourceTemplateNotExist() {
+ Resource resourceExist = createResourceObject(false);
+ List<String> list = null;
+ resourceExist.setDerivedFrom(list);
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
+ }
+ }
+
+ private void testResourceTemplateEmpty() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setDerivedFrom(new ArrayList<>());
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
+ }
+ }
+
+ private void testResourceTemplateInvalid() {
+ Resource resourceExist = createResourceObject(false);
+ ArrayList<String> derivedFrom = new ArrayList<>();
+ derivedFrom.add("kuku");
+ resourceExist.setDerivedFrom(derivedFrom);
+ try {
+ bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.PARENT_RESOURCE_NOT_FOUND);
+ }
+ }
+
+ // Derived from stop
+ private void assertComponentException(ComponentException e, ActionStatus expectedStatus, String... variables) {
+ ResponseFormat actualResponse = e.getResponseFormat() != null ? e.getResponseFormat()
+ : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
+ assertResponse(actualResponse, expectedStatus, variables);
+ }
+
+ private void assertResponse(ResponseFormat actualResponse, ActionStatus expectedStatus, String... variables) {
+ ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables);
+ assertThat(expectedResponse.getStatus()).isEqualTo(actualResponse.getStatus());
+ assertThat(expectedResponse.getFormattedMessage()).isEqualTo(actualResponse.getFormattedMessage());
+ }
+
+ private void assertResponse(Either<Resource, ResponseFormat> createResponse, ActionStatus expectedStatus,
+ String... variables) {
+ assertResponse(createResponse.right()
+ .value(), expectedStatus, variables);
+ }
+
+ // UPDATE tests - start
+ // Resource name
+ @Test
+ void testResourceNameWrongFormat_UPDATE() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+ // contains *
+ String nameWrongFormat = "ljg*fd";
+ updatedResource.setName(nameWrongFormat);
+
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+ try {
+ bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
+ }
+ }
+
+ @Test
+ void testResourceNameAfterCertify_UPDATE() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate);
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+
+ String name = "ljg";
+ updatedResource.setName(name);
+ resource.setVersion("1.0");
+
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+ try {
+ bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
+ }
+ }
+
+ @Test
+ void testResourceNameAlreadyExist_UPDATE() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+
+ String resourceName = "alreadyExists";
+ updatedResource.setName(resourceName);
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(updatedResource);
+ when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
+ try {
+ bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
+ ComponentTypeEnum.RESOURCE.getValue(), resourceName);
+ }
+ }
+
+ @Test
+ void testResourceDescExceedsLimit_UPDATE() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+
+ // 1025 chars, the limit is 1024
+ String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
+ + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
+ + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
+ + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
+ + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
+ + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
+ + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
+ + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
+ updatedResource.setDescription(tooLongResourceDesc);
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+ try {
+ bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT,
+ ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
+ }
+ }
+
+ @Test
+ void testIconWrongFormat_UPDATE() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+
+ // contains .
+ String icon = "icon.jpg";
+ updatedResource.setIcon(icon);
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+ try {
+ bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue());
+ }
+ }
+
+ @Test
+ void testIconAfterCertify_UPDATE() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+
+ // contains
+ String icon = "icon";
+ updatedResource.setIcon(icon);
+
+ resource.setVersion("1.0");
+ ;
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+ try {
+ bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
+ }
+ }
+
+ @Test
+ void testTagsExceedsLimit_UPDATE() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+
+ String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ";
+ String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW";
+ String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE";
+ String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb";
+ String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr";
+ String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
+ String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
+ String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd";
+ String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
+ String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
+ String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh";
+ String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj";
+ String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk";
+ String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs";
+ String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz";
+ String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx";
+ String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2";
+ String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3";
+ String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4";
+ String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5";
+ String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0";
+
+ List<String> tagsList = new ArrayList<>();
+ tagsList.add(tag1);
+ tagsList.add(tag2);
+ tagsList.add(tag3);
+ tagsList.add(tag4);
+ tagsList.add(tag5);
+ tagsList.add(tag6);
+ tagsList.add(tag7);
+ tagsList.add(tag8);
+ tagsList.add(tag9);
+ tagsList.add(tag10);
+ tagsList.add(tag11);
+ tagsList.add(tag12);
+ tagsList.add(tag13);
+ tagsList.add(tag14);
+ tagsList.add(tag15);
+ tagsList.add(tag16);
+ tagsList.add(tag17);
+ tagsList.add(tag18);
+ tagsList.add(tag19);
+ tagsList.add(tag20);
+ tagsList.add(tag21);
+ tagsList.add(resource.getName());
+
+ updatedResource.setTags(tagsList);
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+ try {
+ bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT,
+ "" + ValidationUtils.TAG_LIST_MAX_LENGTH);
+ }
+ }
+
+ @Test
+ void testVendorNameWrongFormat_UPDATE() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+
+ // contains *
+ String nameWrongFormat = "ljg*fd";
+ updatedResource.setVendorName(nameWrongFormat);
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+ try {
+ bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.INVALID_VENDOR_NAME, nameWrongFormat);
+ }
+ }
+
+ @Test
+ void testVendorNameWrongFormat() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+
+ // contains *
+ String nameWrongFormat = "ljg*fd";
+ updatedResource.setVendorName(nameWrongFormat);
+ resource.setVersion("1.0");
+ ;
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+ try {
+ bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.INVALID_VENDOR_NAME, nameWrongFormat);
+ }
+ }
+
+ @Test
+ void testVendorReleaseExceedsLimit_UPDATE() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+ // 129 chars, the limit is 128
+ String tooLongVendorRelease = "h1KSyJh9EspI8SPwAGu4VETfqWejeanuB1PCJBxJmJncYnrW0lnsEFFVRIukRJkwlOVnZCy8p38tjhANeZq3BGMHIawWR6ICl8Wi9mikRYALWgvJug00JrlQ0iPVKPLxy";
+ updatedResource.setVendorRelease(tooLongVendorRelease);
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+ try {
+ bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT,
+ "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
+ }
+ }
+
+ @Test
+ void testResourceBadCategory_UPDATE() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+
+ String resourceId = resource.getUniqueId();
+ String badCategory = "ddfds";
+ updatedResource.setCategories(null);
+ updatedResource.addCategory(badCategory, "fikt");
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+ try {
+ bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
+ }
+ }
+
+ @Test
+ void createResourceFromCsarTest() {
+ assertThrows(ComponentException.class, () -> {
+ bl.createResourceFromCsar(resourceResponse, user, new HashMap<>(), "");
+ });
+ }
+
+ @Test
+ void testCreateResourceFromCsarWithModel() throws URISyntaxException, ZipException {
final File csarFile = new File(
- ResourceBusinessLogicTest.class.getClassLoader().getResource("csars/nonOnapCsar.csar").toURI());
+ ResourceBusinessLogicTest.class.getClassLoader().getResource("csars/nonOnapCsar.csar").toURI());
final Map<String, byte[]> csar = ZipUtils.readZip(csarFile, false);
- String resourceYml = new String(csar.get("Definitions/my_vnf.yaml"));
+ String resourceYml = new String(csar.get("Definitions/my_vnf.yaml"));
- YamlTemplateParsingHandler yamlTemplateParser = new YamlTemplateParsingHandler(mockJanusGraphDao, null, Mockito.mock(AnnotationBusinessLogic.class), null);
- final ParsedToscaYamlInfo parsedToscaYamlInfo = yamlTemplateParser.parseResourceInfoFromYAML("Definitions/my_vnf.yml", resourceYml, Collections.EMPTY_MAP, Collections.EMPTY_MAP, "myVnf", resourceResponse, "");
+ YamlTemplateParsingHandler yamlTemplateParser = new YamlTemplateParsingHandler(mockJanusGraphDao, null,
+ Mockito.mock(AnnotationBusinessLogic.class), null);
+ final ParsedToscaYamlInfo parsedToscaYamlInfo = yamlTemplateParser.parseResourceInfoFromYAML("Definitions/my_vnf.yml", resourceYml,
+ Collections.EMPTY_MAP, Collections.EMPTY_MAP, "myVnf", resourceResponse, "");
+
+ when(propertyOperation.getDataTypeByName("tosca.datatypes.testDataType.FromMainTemplate", "testModel")).thenReturn(
+ Either.right(StorageOperationStatus.NOT_FOUND));
- when(propertyOperation.getDataTypeByName("tosca.datatypes.testDataType.FromMainTemplate", "testModel")).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
-
when(toscaOperationFacade.getLatestByToscaResourceName(anyString(), any())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
Resource vduCp = new Resource();
vduCp.setToscaResourceName("tosca.nodes.nfv.VduCp");
@@ -1530,28 +1539,30 @@ public class ResourceBusinessLogicTest {
baseTypeProp.setName("propInBase");
baseTypeProp.setType("string");
properties.add(baseTypeProp);
- derivedFrom.setProperties(properties );
+ derivedFrom.setProperties(properties);
when(genericTypeBusinessLogic.fetchDerivedFromGenericType(any(), eq("tosca.nodes.nfv.VNF"))).thenReturn(Either.left(derivedFrom));
when(toscaOperationFacade
- .validateComponentNameAndModelExists("myVnf", "testModel_myVnf1.0", ResourceTypeEnum.VF, ComponentTypeEnum.RESOURCE)).thenReturn(Either.left(false));
+ .validateComponentNameAndModelExists("myVnf", "testModel_myVnf1.0", ResourceTypeEnum.VF, ComponentTypeEnum.RESOURCE)).thenReturn(
+ Either.left(false));
- when(toscaOperationFacade.addPropertyToComponent(any(), any(), any())).thenReturn(Either.left(new PropertyDefinition()));
+ when(toscaOperationFacade.addPropertyToComponent(any(), any())).thenReturn(Either.left(new PropertyDefinition()));
when(toscaOperationFacade.associateComponentInstancePropertiesToComponent(any(), any())).thenReturn(Either.left(Collections.emptyMap()));
when(toscaOperationFacade.associateArtifactsToInstances(any(), any())).thenReturn(StorageOperationStatus.OK);
when(toscaOperationFacade.associateDeploymentArtifactsToInstances(any(), any(), any())).thenReturn(StorageOperationStatus.OK);
when(toscaOperationFacade.associateInstAttributeToComponentToInstances(any(), any())).thenReturn(StorageOperationStatus.OK);
- when(toscaOperationFacade.associateResourceInstances(any(Component.class), anyString(), anyList())).thenReturn(Either.left(Collections.EMPTY_LIST));
- when(applicationDataTypeCache.getAll("testModel_myVnf1.0")).thenReturn(Either.left(emptyDataTypes));
+ when(toscaOperationFacade.associateResourceInstances(any(Component.class), anyString(), anyList())).thenReturn(
+ Either.left(Collections.EMPTY_LIST));
+ when(applicationDataTypeCache.getAll("testModel_myVnf1.0")).thenReturn(Either.left(emptyDataTypes));
doAnswer(invocation -> {
Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReqs = invocation.getArgument(1);
- for (final Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> m: instReqs.entrySet()) {
+ for (final Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> m : instReqs.entrySet()) {
m.getKey().setRequirements(m.getValue());
}
return StorageOperationStatus.OK;
}).
- when(toscaOperationFacade).associateOrAddCalculatedCapReq(any(), any(), any());
+ when(toscaOperationFacade).associateOrAddCalculatedCapReq(any(), any(), any());
when(toscaOperationFacade.updateCalculatedCapabilitiesRequirements(any(), any(), any())).thenReturn(StorageOperationStatus.OK);
when(groupBusinessLogic.validateUpdateVfGroupNames(any(), any())).thenReturn(Either.left(Collections.EMPTY_MAP));
@@ -1560,8 +1571,9 @@ public class ResourceBusinessLogicTest {
List<ComponentInstance> cis = new ArrayList<>();
cis.add(ci);
doAnswer(invocation -> {
- List<ComponentInstance> componentInstances = new ArrayList<ComponentInstance>(((Map<ComponentInstance, Resource>)invocation.getArgument(1)).keySet());
- ((Resource)invocation.getArgument(0)).setComponentInstances(componentInstances);
+ List<ComponentInstance> componentInstances = new ArrayList<ComponentInstance>(
+ ((Map<ComponentInstance, Resource>) invocation.getArgument(1)).keySet());
+ ((Resource) invocation.getArgument(0)).setComponentInstances(componentInstances);
return null;
}).when(toscaOperationFacade).associateComponentInstancesToComponent(any(), any(), eq(false), eq(false));
@@ -1589,951 +1601,958 @@ public class ResourceBusinessLogicTest {
final List<String> reqsName = new ArrayList<>();
- final List<ComponentInstance> cisWithExtReq = result.getComponentInstances().stream().filter(instance -> instance.getRequirements().get("tosca.nodes.nfv.VduCp").get(0).isExternal()).collect(Collectors.toList());
+ final List<ComponentInstance> cisWithExtReq = result.getComponentInstances().stream()
+ .filter(instance -> instance.getRequirements().get("tosca.nodes.nfv.VduCp").get(0).isExternal()).collect(Collectors.toList());
cisWithExtReq.forEach(instance -> reqsName.add(instance.getRequirements().get("tosca.nodes.nfv.VduCp").get(0).getExternalName()));
assertEquals(3, cisWithExtReq.size());
}
- @Test
- public void testResourceCategoryAfterCertify_UPDATE() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
-
- String resourceId = resource.getUniqueId();
- updatedResource.setCategories(null);
- updatedResource.addCategory(RESOURCE_CATEGORY1, UPDATED_SUBCATEGORY);
- resource.setVersion("1.0");
- ;
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
- try {
- bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
- }
- }
-
- // Derived from start
- @Test
- public void testResourceTemplateNotExist_UPDATE() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
- String resourceId = resource.getUniqueId();
-
- List<String> list = null;
- updatedResource.setDerivedFrom(list);
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
- try {
- bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
- }
- }
-
- @Test
- public void testResourceTemplateEmpty_UPDATE() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
- String resourceId = resource.getUniqueId();
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
-
- updatedResource.setDerivedFrom(new ArrayList<>());
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
- try {
- bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
- }
- }
-
- @Test
- public void testResourceTemplateInvalid_UPDATE() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
- String resourceId = resource.getUniqueId();
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
-
- ArrayList<String> derivedFrom = new ArrayList<>();
- derivedFrom.add("kuku");
- updatedResource.setDerivedFrom(derivedFrom);
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
- try {
- bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.PARENT_RESOURCE_NOT_FOUND);
- }
- }
-
- @Test
- public void testResourceTemplateCertify_UPDATE_HAPPY() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
- String resourceId = resource.getUniqueId();
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
-
- Either<Boolean, StorageOperationStatus> isToscaNameExtending = Either.left(true);
- when(toscaOperationFacade.validateToscaResourceNameExtends(anyString(), anyString(), anyString()))
- .thenReturn(isToscaNameExtending);
-
- Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = Either
- .left(new HashMap<>());
- when(propertyOperation.deleteAllPropertiesAssociatedToNode(any(NodeTypeEnum.class), anyString()))
- .thenReturn(findPropertiesOfNode);
-
- resource.setVersion("1.0");
-
- ArrayList<String> derivedFrom = new ArrayList<>();
- derivedFrom.add("tosca.nodes.Root");
- updatedResource.setDerivedFrom(derivedFrom);
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(updatedResource);
- when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
- Resource createdResource = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
- assertThat(createdResource).isNotNull();
- }
-
- @Test
- public void testResourceTemplateCertify_UPDATE_SAD() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
- String resourceId = resource.getUniqueId();
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
-
- Either<Boolean, StorageOperationStatus> isToscaNameExtending = Either.left(false);
- when(toscaOperationFacade.validateToscaResourceNameExtends(anyString(), anyString(), anyString()))
- .thenReturn(isToscaNameExtending);
-
- resource.setVersion("1.0");
-
- ArrayList<String> derivedFrom = new ArrayList<>();
- derivedFrom.add("tosca.nodes.Root");
- updatedResource.setDerivedFrom(derivedFrom);
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
- Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = Either
- .left(new HashMap<>());
- when(propertyOperation.deleteAllPropertiesAssociatedToNode(any(NodeTypeEnum.class), anyString()))
- .thenReturn(findPropertiesOfNode);
-
- try {
- bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
- } catch (ComponentException e) {
- assertComponentException(e, ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
- }
- }
- // Derived from stop
-
- @Test
- public void createOrUpdateResourceAlreadyCheckout() {
- createRoot();
- Resource resourceExist = createResourceObject(false);
- validateUserRoles(Role.ADMIN, Role.DESIGNER);
- when(toscaOperationFacade
- .validateComponentNameAndModelExists(resourceExist.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
- .thenReturn(Either.left(false));
- Resource createdResource = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null,
- null);
- createdResource.setLastUpdaterUserId(user.getUserId());
- assertThat(createdResource).isNotNull();
- Either<Resource, StorageOperationStatus> getLatestResult = Either.left(createdResource);
- Either<Component, StorageOperationStatus> getCompLatestResult = Either.left(createdResource);
- when(toscaOperationFacade.getLatestByToscaResourceName(resourceExist.getToscaResourceName(), null))
- .thenReturn(getCompLatestResult);
- when(toscaOperationFacade.getLatestByToscaResourceNameAndModel(resourceExist.getToscaResourceName(), null))
- .thenReturn(getCompLatestResult);
- when(toscaOperationFacade.overrideComponent(any(Resource.class), any(Resource.class)))
- .thenReturn(getLatestResult);
-
- Resource resourceToUpdtae = createResourceObject(false);
-
- ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl
- .createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false);
- assertNotNull(createOrUpdateResource);
-
- Mockito.verify(toscaOperationFacade, Mockito.times(1))
- .overrideComponent(any(Resource.class), any(Resource.class));
- Mockito.verify(lifecycleBl, Mockito.times(0))
- .changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
- any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
-
- }
-
- @Test
- public void createOrUpdateResourceCertified() {
- createRoot();
- Resource resourceExist = createResourceObject(false);
- when(toscaOperationFacade
- .validateComponentNameAndModelExists(resourceExist.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
- .thenReturn(Either.left(false));
- validateUserRoles(Role.ADMIN, Role.DESIGNER);
- Resource createdResource = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null,
- null);
-
- assertThat(createdResource).isNotNull();
- createdResource.setLifecycleState(LifecycleStateEnum.CERTIFIED);
- createdResource.setVersion("1.0");
-
- Either<Resource, StorageOperationStatus> getLatestResult = Either.left(createdResource);
- Either<Component, StorageOperationStatus> getCompLatestResult = Either.left(createdResource);
- when(toscaOperationFacade.getLatestByToscaResourceNameAndModel(resourceExist.getToscaResourceName(), null))
- .thenReturn(getCompLatestResult);
- when(toscaOperationFacade.overrideComponent(any(Resource.class), any(Resource.class)))
- .thenReturn(getLatestResult);
-
- when(lifecycleBl.changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
- any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean()))
- .thenReturn(Either.left(createdResource));
-
- Resource resourceToUpdtae = createResourceObject(false);
-
- ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl
- .createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false);
- assertNotNull(createOrUpdateResource);
-
- Mockito.verify(toscaOperationFacade, Mockito.times(1))
- .overrideComponent(any(Resource.class), any(Resource.class));
- Mockito.verify(lifecycleBl, Mockito.times(1))
- .changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
- any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
-
- }
-
- @Test
- public void createOrUpdateResourceNotExist() {
- Resource resourceToUpdtae = createResourceObject(false);
-
- Either<Component, StorageOperationStatus> getLatestResult = Either.right(StorageOperationStatus.NOT_FOUND);
- when(toscaOperationFacade.getLatestByName(resourceToUpdtae.getName(), null)).thenReturn(getLatestResult);
- when(toscaOperationFacade.getLatestByToscaResourceNameAndModel(resourceToUpdtae.getToscaResourceName(), null))
- .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
- when(toscaOperationFacade
- .validateComponentNameAndModelExists(resourceToUpdtae.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
- .thenReturn(Either.left(false));
-
- ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl
- .createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false);
- assertThat(createOrUpdateResource).isNotNull();
-
- Mockito.verify(toscaOperationFacade, times(1))
- .createToscaComponent(resourceToUpdtae);
- Mockito.verify(toscaOperationFacade, Mockito.times(0))
- .overrideComponent(any(Resource.class), any(Resource.class));
- Mockito.verify(lifecycleBl, Mockito.times(0))
- .changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
- any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
-
- }
-
- @Test
- public void testIfNodeTypeNameHasValidPrefix() {
- final List<String> definedNodeTypeNamespaceList = ConfigurationManager.getConfigurationManager()
- .getConfiguration().getDefinedResourceNamespace();
-
- definedNodeTypeNamespaceList.parallelStream().forEach(validNodeTypePrefix -> {
- final String nodeName = validNodeTypePrefix + "." + "abc";
- final Optional<String> result = bl.validateNodeTypeNamePrefix(nodeName, definedNodeTypeNamespaceList);
- assertTrue(result.isPresent());
- });
- }
-
- @Test
- public void updateNestedResource_typeIsNew() throws IOException {
- Resource resourceToUpdate = createResourceObject(false);
- String nodeName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + "." + "abc";
- String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-webServer.yml");
- CsarInfo csarInfo = new CsarInfo(user, "abcd1234", new HashMap<>(), RESOURCE_NAME, "template name", jsonContent,
- true);
- String nestedResourceName = bl.buildNestedToscaResourceName(resourceToUpdate.getResourceType()
- .name(), csarInfo.getVfResourceName(), nodeName)
- .getRight();
- when(toscaOperationFacade.getLatestByName(resourceToUpdate.getName(), null))
- .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
- when(toscaOperationFacade.getLatestByToscaResourceName(resourceToUpdate.getToscaResourceName(), null))
- .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
- when(toscaOperationFacade.getLatestByToscaResourceName(nestedResourceName, null))
- .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
-
- when(toscaOperationFacade.getLatestByToscaResourceNameAndModel(resourceToUpdate.getToscaResourceName(), null))
- .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
- when(toscaOperationFacade
- .validateComponentNameAndModelExists(resourceToUpdate.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
- .thenReturn(Either.left(false));
-
- ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl
- .createOrUpdateResourceByImport(resourceToUpdate, user, false, false, false, csarInfo, nodeName, false);
- assertThat(createOrUpdateResource).isNotNull();
-
- Mockito.verify(toscaOperationFacade, times(1))
- .createToscaComponent(resourceToUpdate);
- Mockito.verify(toscaOperationFacade, times(0))
- .overrideComponent(any(Resource.class), any(Resource.class));
- Mockito.verify(lifecycleBl, times(0))
- .changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
- any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
- }
-
- @Test
- public void updateNestedResource_typeExists() throws IOException {
- createRoot();
- Resource resourceToUpdate = createResourceObject(false);
- setCanWorkOnResource(resourceResponse);
- String nodeName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + "." + "abc";
- String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-webServer.yml");
- CsarInfo csarInfo = new CsarInfo(user, "abcd1234", new HashMap<>(), RESOURCE_NAME, "template name", jsonContent,
- true);
- String nestedResourceName = bl.buildNestedToscaResourceName(resourceToUpdate.getResourceType()
- .name(), csarInfo.getVfResourceName(), nodeName)
- .getRight();
- when(toscaOperationFacade.getLatestByName(resourceToUpdate.getName(), null))
- .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
- when(toscaOperationFacade.getLatestByToscaResourceName(resourceToUpdate.getToscaResourceName(), null))
- .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
- when(toscaOperationFacade.getLatestByToscaResourceNameAndModel(resourceToUpdate.getToscaResourceName(), null))
- .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
- when(toscaOperationFacade.getLatestByToscaResourceName(nestedResourceName, null))
- .thenReturn(Either.left(resourceResponse));
- when(toscaOperationFacade.overrideComponent(any(Resource.class), any(Resource.class)))
- .thenReturn(Either.left(resourceResponse));
-
- ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl
- .createOrUpdateResourceByImport(resourceToUpdate, user, false, false, false, csarInfo, nodeName, false);
- assertThat(createOrUpdateResource).isNotNull();
- Mockito.verify(toscaOperationFacade, times(1))
- .overrideComponent(any(Resource.class), any(Resource.class));
- Mockito.verify(lifecycleBl, times(0))
- .changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
- any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
- }
-
- @Test
- public void testValidatePropertiesDefaultValues_SuccessfullWithoutProperties() {
- Resource basic = createResourceObject(true);
-
- Boolean validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic);
- assertTrue(validatePropertiesDefaultValues);
- }
-
- @Test
- public void testValidatePropertiesDefaultValues_SuccessfullWithProperties() {
- Resource basic = createResourceObject(true);
- PropertyDefinition property = new PropertyDefinition();
- property.setName("myProperty");
- property.setType(ToscaPropertyType.INTEGER.getType());
- property.setDefaultValue("1");
- List<PropertyDefinition> properties = new ArrayList<>();
- properties.add(property);
- basic.setProperties(properties);
- when(propertyOperation.isPropertyTypeValid(property, (String)null)).thenReturn(true);
- when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(true);
- Boolean validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic);
- assertTrue(validatePropertiesDefaultValues);
- }
-
- @Test(expected = ComponentException.class)
- public void testValidatePropertiesDefaultValues_FailedWithProperties() {
- Resource basic = createResourceObject(true);
- PropertyDefinition property = new PropertyDefinition();
- property.setName("myProperty");
- property.setType(ToscaPropertyType.INTEGER.getType());
- property.setDefaultValue("1.5");
- List<PropertyDefinition> properties = new ArrayList<>();
- properties.add(property);
- basic.setProperties(properties);
-
- when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(false);
- bl.validatePropertiesDefaultValues(basic);
- }
-
- @Test
- public void testDeleteMarkedResourcesNoResources() {
- Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(new ArrayList<>());
-
- when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources);
-
- Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
- assertTrue(deleteMarkedResources.isLeft());
- assertTrue(deleteMarkedResources.left().value().isEmpty());
- }
-
- @Test
- public void testDeleteMarkedResources() {
- List<String> ids = new ArrayList<>();
- String resourceInUse = "123";
- String resourceFree = "456";
- ids.add(resourceInUse);
- ids.add(resourceFree);
- Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids);
- when(toscaOperationFacade.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources);
-
- Either<Boolean, StorageOperationStatus> resourceInUseResponse = Either.left(true);
- Either<Boolean, StorageOperationStatus> resourceFreeResponse = Either.left(false);
-
- List<ArtifactDefinition> artifacts = new ArrayList<>();
-
- when(toscaOperationFacade.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse);
- when(toscaOperationFacade.isComponentInUse(resourceInUse)).thenReturn(resourceInUseResponse);
-
- Either<Component, StorageOperationStatus> eitherDelete = Either.left(new
- Resource());
- when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete);
-
- List<String> deletedComponents = new ArrayList<>();
- deletedComponents.add(resourceFree);
- when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.RESOURCE)).thenReturn(Either.left(deletedComponents));
-
- Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
- assertTrue(deleteMarkedResources.isLeft());
- List<String> resourceIdList = deleteMarkedResources.left().value();
- assertFalse(resourceIdList.isEmpty());
- assertTrue(resourceIdList.contains(resourceFree));
- assertFalse(resourceIdList.contains(resourceInUse));
- }
-
- @SuppressWarnings("unchecked")
- @Test
- public void testFindVfCsarArtifactsToHandle() {
-
- Class<ResourceBusinessLogic> targetClass = ResourceBusinessLogic.class;
- String methodName = "findVfCsarArtifactsToHandle";
- Resource resource = new Resource();
- String deploymentArtifactToUpdateFileName = "deploymentArtifactToUpdate.yaml";
- String deploymentArtifactToDeleteFileName = "deploymentArtifactToDelete.yaml";
- String deploymentArtifactToCreateFileName = "deploymentArtifactToCreate.yaml";
-
- String artifactInfoToUpdateFileName = "infoArtifactToUpdate.yaml";
- String artifactInfoToDeleteFileName = "infoArtifactToDelete.yaml";
- String artifactInfoToNotDeleteFileName = "infoArtifactNotToDelete.yaml";
- String artifactInfoToCreateFileName = "infoArtifactToCreate.yaml";
-
- byte[] oldPayloadData = "oldPayloadData".getBytes();
- byte[] newPayloadData = "newPayloadData".getBytes();
- Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>();
-
- ArtifactDefinition deploymentArtifactToUpdate = new ArtifactDefinition();
- deploymentArtifactToUpdate.setMandatory(false);
- deploymentArtifactToUpdate.setArtifactName(deploymentArtifactToUpdateFileName);
- deploymentArtifactToUpdate.setArtifactType("SNMP_POLL");
- deploymentArtifactToUpdate.setPayload(oldPayloadData);
- deploymentArtifactToUpdate
- .setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
-
- ArtifactDefinition deploymentArtifactToDelete = new ArtifactDefinition();
- deploymentArtifactToDelete.setMandatory(false);
- deploymentArtifactToDelete.setArtifactName(deploymentArtifactToDeleteFileName);
- deploymentArtifactToDelete.setArtifactType("SNMP_TRAP");
- deploymentArtifactToDelete.setPayload(oldPayloadData);
- deploymentArtifactToDelete
- .setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
-
- ArtifactDefinition deploymentArtifactToIgnore = new ArtifactDefinition();
-
- deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToUpdate.getArtifactName()),
- deploymentArtifactToUpdate);
- deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToDelete.getArtifactName()),
- deploymentArtifactToDelete);
- deploymentArtifacts.put("ignore", deploymentArtifactToIgnore);
-
- Map<String, ArtifactDefinition> artifacts = new HashMap<>();
-
- ArtifactDefinition artifactToUpdate = new ArtifactDefinition();
- artifactToUpdate.setMandatory(false);
- artifactToUpdate.setArtifactName(artifactInfoToUpdateFileName);
- artifactToUpdate.setArtifactType("SNMP_POLL");
- artifactToUpdate.setPayload(oldPayloadData);
- artifactToUpdate.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
-
- ArtifactDefinition artifactToDelete = new ArtifactDefinition();
- artifactToDelete.setMandatory(false);
- artifactToDelete.setArtifactName(artifactInfoToDeleteFileName);
- artifactToDelete.setArtifactType("SNMP_TRAP");
- artifactToDelete.setPayload(oldPayloadData);
- artifactToDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
- artifactToDelete.setIsFromCsar(true);
-
- ArtifactDefinition artifactToNotDelete = new ArtifactDefinition();
- artifactToNotDelete.setMandatory(false);
- artifactToNotDelete.setArtifactName(artifactInfoToNotDeleteFileName);
- artifactToNotDelete.setArtifactType("SNMP_TRAP");
- artifactToNotDelete.setPayload(oldPayloadData);
- artifactToNotDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
- artifactToNotDelete.setIsFromCsar(false);
-
- ArtifactDefinition artifactToIgnore = new ArtifactDefinition();
-
- artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToUpdate.getArtifactName()), artifactToUpdate);
- artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToDelete.getArtifactName()), artifactToDelete);
- artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToNotDelete.getArtifactName()),
- artifactToNotDelete);
- artifacts.put("ignore", artifactToIgnore);
-
- resource.setDeploymentArtifacts(deploymentArtifacts);
- resource.setArtifacts(artifacts);
-
- List<NonMetaArtifactInfo> artifactPathAndNameList = new ArrayList<>();
- NonMetaArtifactInfo deploymentArtifactInfoToUpdate = new NonMetaArtifactInfo(
- deploymentArtifactToUpdate.getArtifactName(), null,
- deploymentArtifactToUpdate.getArtifactType(),
- ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData, deploymentArtifactToUpdate.getArtifactName(), false);
-
- NonMetaArtifactInfo informationalArtifactInfoToUpdate = new NonMetaArtifactInfo(
- artifactToUpdate.getArtifactName(), null, artifactToUpdate.getArtifactType(),
- ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData, artifactToUpdate.getArtifactName(), false);
-
- NonMetaArtifactInfo informationalArtifactInfoToUpdateFromCsar = new NonMetaArtifactInfo(
- artifactToUpdate.getArtifactName(), null, artifactToUpdate.getArtifactType(),
- ArtifactGroupTypeEnum.INFORMATIONAL, newPayloadData, artifactToUpdate.getArtifactName(), true);
-
- NonMetaArtifactInfo deploymentArtifactInfoToUpdateFromCsar = new NonMetaArtifactInfo(
- artifactToUpdate.getArtifactName(), null, artifactToUpdate.getArtifactType(),
- ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData, artifactToUpdate.getArtifactName(), true);
-
- NonMetaArtifactInfo deploymentArtifactInfoToCreate = new NonMetaArtifactInfo(deploymentArtifactToCreateFileName,
- null, ArtifactTypeEnum.OTHER.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData,
- deploymentArtifactToCreateFileName, false);
-
- NonMetaArtifactInfo informationalArtifactInfoToCreate = new NonMetaArtifactInfo(artifactInfoToCreateFileName,
- null, ArtifactTypeEnum.OTHER.getType(), ArtifactGroupTypeEnum.INFORMATIONAL, newPayloadData,
- artifactInfoToCreateFileName, false);
-
- artifactPathAndNameList.add(deploymentArtifactInfoToUpdate);
- artifactPathAndNameList.add(informationalArtifactInfoToUpdate);
- artifactPathAndNameList.add(deploymentArtifactInfoToCreate);
- artifactPathAndNameList.add(informationalArtifactInfoToCreate);
- artifactPathAndNameList.add(informationalArtifactInfoToUpdateFromCsar);
- artifactPathAndNameList.add(deploymentArtifactInfoToUpdateFromCsar);
-
- Object[] argObjects = { resource, artifactPathAndNameList, user };
- Class[] argClasses = { Resource.class, List.class, User.class };
- try {
- Method method = targetClass.getDeclaredMethod(methodName, argClasses);
- method.setAccessible(true);
- Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = (Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat>) method
- .invoke(bl, argObjects);
- assertTrue(findVfCsarArtifactsToHandleRes.isLeft());
- EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> foundVfArtifacts = findVfCsarArtifactsToHandleRes
- .left()
- .value();
- assertEquals(4, foundVfArtifacts.get(ArtifactOperationEnum.CREATE)
- .size());
- assertEquals(4, foundVfArtifacts.get(ArtifactOperationEnum.UPDATE)
- .size());
- assertEquals(1, foundVfArtifacts.get(ArtifactOperationEnum.DELETE)
- .size());
-
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- @Test
- public void testVFGeneratedInputs() {
- validateUserRoles(Role.ADMIN, Role.DESIGNER);
- Resource resource = createVF();
- List<InputDefinition> inputs = resource.getInputs();
- assertEquals(6, inputs.size());
- for (InputDefinition input : inputs) {
- assertThat(input.getOwnerId()).isNotNull();
- }
- assertEquals(resource.getDerivedFromGenericType(), genericVF.getToscaResourceName());
- assertEquals(resource.getDerivedFromGenericVersion(), genericVF.getVersion());
- }
-
- @Test
- public void testCRGeneratedInputs() {
- validateUserRoles(Role.ADMIN, Role.DESIGNER);
- Resource resource = createCR();
- List<InputDefinition> inputs = resource.getInputs();
- assertEquals(3, inputs.size());
- for (InputDefinition input : inputs) {
- assertThat(input.getOwnerId()).isNotNull();
- }
- assertEquals(resource.getDerivedFromGenericType(), genericCR.getToscaResourceName());
- assertEquals(resource.getDerivedFromGenericVersion(), genericCR.getVersion());
- }
-
- @Test
- public void testVFUpdateGenericInputsToLatestOnCheckout() {
- validateUserRoles(Role.ADMIN, Role.DESIGNER);
- // create a VF that is derived from generic version 1.0
- Resource resource = createVF();
- // create a new generic version without properties
- genericVF.setVersion("2.0");
- genericVF.setProperties(null);
- String currentDerivedFromVersion = resource.getDerivedFromGenericVersion();
- List<InputDefinition> currentInputs = resource.getInputs();
- // verify previous inputs ownerId fields exist - user may not delete
- // generated inputs
- assertEquals(6, currentInputs.stream()
- .filter(p -> null != p.getOwnerId())
- .collect(Collectors.toList())
- .size());
- Either<Boolean, ResponseFormat> upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource);
- // verify success
- assertTrue(upgradeToLatestGeneric.isLeft());
- // verify update required and valid
- assertTrue(upgradeToLatestGeneric.left()
- .value());
- // verify version was upgraded
- assertNotEquals(resource.getDerivedFromGenericVersion(), currentDerivedFromVersion);
- // verify inputs were not deleted
- assertEquals(6, resource.getInputs()
- .size());
- // verify inputs ownerId fields were removed - user may delete/edit
- // inputs
- assertEquals(6, resource.getInputs()
- .stream()
- .filter(p -> null == p.getOwnerId())
- .collect(Collectors.toList())
- .size());
- }
-
- @Test
- public void testVFUpdateGenericInputsToLatestOnCheckoutNotPerformed() {
-
- // create a VF that is derived from generic version 1.0
- validateUserRoles(Role.ADMIN, Role.DESIGNER);
- Resource resource = createVF();
-
- // add an input to the VF
- PropertyDefinition newProp = new PropertyDefinition();
- newProp.setType("integer");
- newProp.setName("newProp");
- resource.getInputs()
- .add(new InputDefinition(newProp));
-
- // create a new generic version with a new property which has the same
- // name as a user defined input on the VF with a different type
- genericVF.setVersion("2.0");
- newProp.setType("string");
- genericVF.setProperties(new ArrayList<>());
- genericVF.getProperties()
- .add(newProp);
- when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericVF));
- when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(),
- genericVF.getUniqueId())).thenCallRealMethod();
- String currentDerivedFromVersion = resource.getDerivedFromGenericVersion();
- assertEquals(6, resource.getInputs()
- .stream()
- .filter(p -> null != p.getOwnerId())
- .collect(Collectors.toList())
- .size());
- Either<Boolean, ResponseFormat> upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource);
- // verify success
- assertTrue(upgradeToLatestGeneric.isLeft());
- // verify update is invalid an void
- assertFalse(upgradeToLatestGeneric.left()
- .value());
- // verify version was not upgraded
- assertEquals(resource.getDerivedFromGenericVersion(), currentDerivedFromVersion);
- // verify inputs were not removed
- assertEquals(7, resource.getInputs()
- .size());
- // verify user defined input exists
- assertEquals(1, resource.getInputs()
- .stream()
- .filter(p -> null == p.getOwnerId())
- .collect(Collectors.toList())
- .size());
- assertEquals("integer", resource.getInputs()
- .stream()
- .filter(p -> null == p.getOwnerId())
- .findAny()
- .get()
- .getType());
- }
-
- @Test
- public void testPNFGeneratedInputsNoGeneratedInformationalArtifacts() {
- validateUserRoles(Role.ADMIN, Role.DESIGNER);
- Resource resource = createPNF();
- List<InputDefinition> inputs = resource.getInputs();
- assertEquals(3, inputs.size());
- for (InputDefinition input : inputs) {
- assertThat(input.getOwnerId()).isNotNull();
- }
- assertEquals(resource.getDerivedFromGenericType(), genericPNF.getToscaResourceName());
- assertEquals(resource.getDerivedFromGenericVersion(), genericPNF.getVersion());
- assertEquals(0, resource.getArtifacts()
- .size());
- }
-
- private Resource createVF() {
-
- genericVF = setupGenericTypeMock(GENERIC_VF_NAME);
- when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_VF_NAME))
- .thenReturn(Either.left(genericVF));
- Resource resource = createResourceObject(true);
- resource.setDerivedFrom(null);
- resource.setResourceType(ResourceTypeEnum.VF);
- when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource));
- when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource, null)).thenReturn(Either.left(genericVF));
- when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericVF)).thenCallRealMethod();
- when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(),
- resource.getUniqueId())).thenCallRealMethod();
- when(toscaOperationFacade
- .validateComponentNameAndModelExists(resource.getName(), null, ResourceTypeEnum.VF, ComponentTypeEnum.RESOURCE))
- .thenReturn(Either.left(false));
- Resource createdResource = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertThat(createdResource).isNotNull();
- return createdResource;
- }
-
- private Resource createRoot() {
- rootType = setupGenericTypeMock(GENERIC_ROOT_NAME);
- when(toscaOperationFacade.getLatestByToscaResourceName(GENERIC_ROOT_NAME, null))
- .thenReturn(Either.left(rootType));
- return rootType;
- }
-
- private Resource createCR() {
-
- genericCR = setupGenericTypeMock(GENERIC_CR_NAME);
- when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_CR_NAME))
- .thenReturn(Either.left(genericCR));
- Resource resource = createResourceObject(true);
- resource.setDerivedFrom(null);
- resource.setResourceType(ResourceTypeEnum.CR);
- when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource));
- when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource, null)).thenReturn(Either.left(genericCR));
- when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericCR)).thenCallRealMethod();
- when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericCR.getProperties(),
- resource.getUniqueId())).thenCallRealMethod();
- when(toscaOperationFacade
- .validateComponentNameAndModelExists(resource.getName(), null, ResourceTypeEnum.CR, ComponentTypeEnum.RESOURCE))
- .thenReturn(Either.left(false));
- Resource createdResource = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertThat(createdResource).isNotNull();
- return createdResource;
- }
-
- private Resource createPNF() {
-
- genericPNF = setupGenericTypeMock(GENERIC_PNF_NAME);
- when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_PNF_NAME))
- .thenReturn(Either.left(genericPNF));
- Resource resource = createResourceObject(true);
- resource.setDerivedFrom(null);
- resource.setResourceType(ResourceTypeEnum.PNF);
- when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource));
- when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource, null)).thenReturn(Either.left(genericPNF));
- when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericPNF)).thenCallRealMethod();
- when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericPNF.getProperties(),
- resource.getUniqueId())).thenCallRealMethod();
- when(toscaOperationFacade
- .validateComponentNameAndModelExists(resource.getName(), null, ResourceTypeEnum.PNF, ComponentTypeEnum.RESOURCE))
- .thenReturn(Either.left(false));
- Resource createdResource = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertThat(createdResource).isNotNull();
- return createdResource;
- }
-
- private Map<String, String> getGenericPropertiesByToscaName(String toscaName) {
- HashMap<String, String> PNFProps = new HashMap<String, String>() {
- {
- put("nf_function", "string");
- put("nf_role", "string");
- put("nf_type", "string");
- }
- };
-
- HashMap<String, String> CRProps = new HashMap<String, String>() {
- {
- put("cr_function", "string");
- put("cr_role", "string");
- put("cr_type", "string");
- }
- };
-
- HashMap<String, String> VFProps = new HashMap<String, String>() {
- {
- putAll(CRProps);
- put("availability_zone_max_count", "integer");
- put("min_instances", "integer");
- put("max_instances", "integer");
- }
- };
-
- if (toscaName.contains("PNF"))
- return PNFProps;
- if (toscaName.contains("CR"))
- return CRProps;
- if (toscaName.contains("VF"))
- return VFProps;
-
- return new HashMap<>();
- }
-
- private Resource setupGenericTypeMock(String toscaName) {
-
- Resource genericType = createResourceObject(true);
- genericType.setVersion("1.0");
- genericType.setToscaResourceName(toscaName);
- genericType.setAbstract(true);
- List<PropertyDefinition> genericProps = new ArrayList<>();
- Map<String, String> genericPropsMap = getGenericPropertiesByToscaName(toscaName);
- genericPropsMap.forEach((name, type) -> {
- PropertyDefinition prop = new PropertyDefinition();
- prop.setName(name);
- prop.setType(type);
- genericProps.add(prop);
- });
-
- genericType.setProperties(genericProps);
- return genericType;
- }
-
- private void validateUserRoles(Role... roles) {
- List<Role> listOfRoles = Stream.of(roles)
- .collect(Collectors.toList());
- }
-
- @Test
- public void testUpdateVolumeGroup() {
- Resource resource = getResourceWithType("HEAT_VOL", "org.openecomp.groups.VfModule");
- bl.updateVolumeGroup(resource);
- assertThat(resource.getGroups().get(0).getProperties().get(0).getValue()).isEqualTo(Boolean.toString(true));
- }
-
- @Test
- public void testUpdateVolumeGroupNull() {
- Resource resource = getResourceWithType("HEAT_VOL", "org.openecomp.groups.VfModule");
- resource.setGroups(null);
- bl.updateVolumeGroup(resource);
- assertThat(resource.getGroups()).isNull();
- }
-
- @Test
- public void testUpdateVolumeGroupFail() {
- Resource resource = getResourceWithType("NON_EXIST_HEAT", "org.openecomp.groups.VfModule");
- bl.updateVolumeGroup(resource);
- assertThat(resource.getGroups().get(0).getProperties().get(0).getValue()).isEqualTo(Boolean.toString(false));
- }
-
- private Resource getResourceWithType(String artifactType, String groupDefinitionType) {
- ArtifactDefinition artifactToUpdate = new ArtifactDefinition();
- List<GroupDefinition> groups = new ArrayList<>();
- GroupDefinition gd = new GroupDefinition();
- List<PropertyDataDefinition> properties = new ArrayList<>();
- PropertyDataDefinition pdd = new PropertyDataDefinition();
- Map<String, ArtifactDefinition> artifacts = new HashMap<>();
- List<String> artifactsList = new ArrayList<>();
-
- artifactToUpdate.setArtifactType(artifactType);
- artifactToUpdate.setArtifactName(artifactType);
- artifactToUpdate.setUniqueId(artifactType);
- Resource resource = createResourceObjectCsar(true);
- artifactsList.add(artifactToUpdate.getArtifactName());
-
-
- pdd.setName("volume_group");
- pdd.setValue("true");
- pdd.setType(ToscaPropertyType.BOOLEAN.getType());
-
- artifacts.put(artifactToUpdate.getArtifactName(), artifactToUpdate);
-
- properties.add(pdd);
- gd.setType(groupDefinitionType);
- gd.setProperties(properties);
- gd.setArtifacts(artifactsList);
- groups.add(gd);
-
- resource.setGroups(groups);
- resource.setDeploymentArtifacts(artifacts);
- return resource;
- }
-
-
- @Test
- public void testgetAllCertifiedResources() throws Exception {
- List<Resource> list = bl.getAllCertifiedResources(true, HighestFilterEnum.HIGHEST_ONLY, "USER");
- Assert.assertEquals(reslist,list);
- }
-
- @Test(expected = StorageException.class)
- public void testgetAllCertifiedResources_exception() throws Exception {
- List<Resource> list = bl.getAllCertifiedResources(false, HighestFilterEnum.NON_HIGHEST_ONLY, "USER");
- Assert.assertEquals(reslist,list);
- }
-
- @Test
- public void testvalidateResourceNameExists() throws Exception {
- Either<Map<String, Boolean>, ResponseFormat> res = bl.validateResourceNameExists("Resource", ResourceTypeEnum.CR, "jh0003");
- Assert.assertEquals(true,res.isLeft());
- }
-
- @Test
- public void rollbackWithEitherAlwaysReturnARuntimeException() {
- JanusGraphDao janusGraphDao = mockJanusGraphDao;
- ActionStatus actionStatus = ActionStatus.INPUTS_NOT_FOUND;
- String params = "testName";
-
- Either<Object, RuntimeException> result =
- ResourceBusinessLogic.rollbackWithEither(janusGraphDao, actionStatus, params);
-
- assertTrue(result.isRight());
- assertTrue(result.right().value() instanceof ByActionStatusComponentException);
- }
-
- @Test
- public void rollbackWithEitherWorksWithNullJanusGraphDao() {
- JanusGraphDao janusGraphDao = null;
- ActionStatus actionStatus = ActionStatus.INPUTS_NOT_FOUND;
- String params = "testName";
-
- Either<Object, RuntimeException> result =
- ResourceBusinessLogic.rollbackWithEither(janusGraphDao, actionStatus, params);
-
- assertTrue(result.isRight());
- assertTrue(result.right().value() instanceof ByActionStatusComponentException);
- }
-
- @Test
- public void testDeleteResource_NotFound() {
- Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
- ResponseFormat respFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), "");
- ResponseFormat actualResponseFormat = bl.deleteResource("1", user);
- assertEquals(respFormat.getStatus(), actualResponseFormat.getStatus());
- }
-
- @Test
- public void testDeleteResource_NotArchived() {
- Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(Either.left(resourceResponse));
- ComponentException actualComponentException = assertThrows(ComponentException.class, () -> bl.deleteResourceAllVersions(resourceResponse.getUniqueId(), user));
- assertEquals(ActionStatus.COMPONENT_NOT_ARCHIVED, actualComponentException.getActionStatus());
- assertEquals("my-resource_name with space:0.1", actualComponentException.getParams()[0]);
- }
-
- @Test
- public void testDeleteResource_IsInUse() {
- Resource resourceObject = createResourceObject(true);
- Mockito.when(toscaOperationFacade.getToscaElement(anyString())).thenReturn(Either.left(resourceObject));
- resourceObject.setArchived(true);
- OperationException oe = new OperationException(ActionStatus.COMPONENT_IN_USE_BY_ANOTHER_COMPONENT, "resource_name");
- Mockito.when(toscaOperationFacade.deleteComponent(resourceObject.getInvariantUUID(), NodeTypeEnum.Resource, true)).thenThrow(oe);
- OperationException actualOperationException = assertThrows(OperationException.class, () -> bl.deleteResourceAllVersions(resourceResponse.getUniqueId(), user));
- assertEquals(ActionStatus.COMPONENT_IN_USE_BY_ANOTHER_COMPONENT, actualOperationException.getActionStatus());
- assertEquals("resource_name", actualOperationException.getParams()[0]);
- }
+ @Test
+ void testResourceCategoryAfterCertify_UPDATE() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+
+ String resourceId = resource.getUniqueId();
+ updatedResource.setCategories(null);
+ updatedResource.addCategory(RESOURCE_CATEGORY1, UPDATED_SUBCATEGORY);
+ resource.setVersion("1.0");
+ ;
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
+ try {
+ bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
+ }
+ }
+
+ // Derived from start
+ @Test
+ void testResourceTemplateNotExist_UPDATE() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+ String resourceId = resource.getUniqueId();
+
+ List<String> list = null;
+ updatedResource.setDerivedFrom(list);
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+ try {
+ bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
+ }
+ }
+
+ @Test
+ void testResourceTemplateEmpty_UPDATE() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+ String resourceId = resource.getUniqueId();
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+
+ updatedResource.setDerivedFrom(new ArrayList<>());
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+ try {
+ bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
+ }
+ }
+
+ @Test
+ void testResourceTemplateInvalid_UPDATE() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+ String resourceId = resource.getUniqueId();
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+
+ ArrayList<String> derivedFrom = new ArrayList<>();
+ derivedFrom.add("kuku");
+ updatedResource.setDerivedFrom(derivedFrom);
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+ try {
+ bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.PARENT_RESOURCE_NOT_FOUND);
+ }
+ }
+
+ @Test
+ void testResourceTemplateCertify_UPDATE_HAPPY() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+ String resourceId = resource.getUniqueId();
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+
+ Either<Boolean, StorageOperationStatus> isToscaNameExtending = Either.left(true);
+ when(toscaOperationFacade.validateToscaResourceNameExtends(anyString(), anyString(), anyString()))
+ .thenReturn(isToscaNameExtending);
+
+ Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = Either
+ .left(new HashMap<>());
+ when(propertyOperation.deleteAllPropertiesAssociatedToNode(any(NodeTypeEnum.class), anyString()))
+ .thenReturn(findPropertiesOfNode);
+
+ resource.setVersion("1.0");
+
+ ArrayList<String> derivedFrom = new ArrayList<>();
+ derivedFrom.add("tosca.nodes.Root");
+ updatedResource.setDerivedFrom(derivedFrom);
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(updatedResource);
+ when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
+ Resource createdResource = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
+ assertThat(createdResource).isNotNull();
+ }
+
+ @Test
+ void testResourceTemplateCertify_UPDATE_SAD() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+ String resourceId = resource.getUniqueId();
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+
+ Either<Boolean, StorageOperationStatus> isToscaNameExtending = Either.left(false);
+ when(toscaOperationFacade.validateToscaResourceNameExtends(anyString(), anyString(), anyString()))
+ .thenReturn(isToscaNameExtending);
+
+ resource.setVersion("1.0");
+
+ ArrayList<String> derivedFrom = new ArrayList<>();
+ derivedFrom.add("tosca.nodes.Root");
+ updatedResource.setDerivedFrom(derivedFrom);
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
+ Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = Either
+ .left(new HashMap<>());
+ when(propertyOperation.deleteAllPropertiesAssociatedToNode(any(NodeTypeEnum.class), anyString()))
+ .thenReturn(findPropertiesOfNode);
+
+ try {
+ bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
+ } catch (ComponentException e) {
+ assertComponentException(e, ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
+ }
+ }
+ // Derived from stop
+
+ @Test
+ void createOrUpdateResourceAlreadyCheckout() {
+ createRoot();
+ Resource resourceExist = createResourceObject(false);
+ validateUserRoles(Role.ADMIN, Role.DESIGNER);
+ when(toscaOperationFacade
+ .validateComponentNameAndModelExists(resourceExist.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
+ .thenReturn(Either.left(false));
+ Resource createdResource = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null,
+ null);
+ createdResource.setLastUpdaterUserId(user.getUserId());
+ assertThat(createdResource).isNotNull();
+ Either<Resource, StorageOperationStatus> getLatestResult = Either.left(createdResource);
+ Either<Component, StorageOperationStatus> getCompLatestResult = Either.left(createdResource);
+ when(toscaOperationFacade.getLatestByToscaResourceName(resourceExist.getToscaResourceName(), null))
+ .thenReturn(getCompLatestResult);
+ when(toscaOperationFacade.getLatestByToscaResourceNameAndModel(resourceExist.getToscaResourceName(), null))
+ .thenReturn(getCompLatestResult);
+ when(toscaOperationFacade.overrideComponent(any(Resource.class), any(Resource.class)))
+ .thenReturn(getLatestResult);
+
+ Resource resourceToUpdtae = createResourceObject(false);
+
+ ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl
+ .createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false);
+ assertNotNull(createOrUpdateResource);
+
+ Mockito.verify(toscaOperationFacade, Mockito.times(1))
+ .overrideComponent(any(Resource.class), any(Resource.class));
+ Mockito.verify(lifecycleBl, Mockito.times(0))
+ .changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
+ any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
+
+ }
+
+ @Test
+ void createOrUpdateResourceCertified() {
+ createRoot();
+ Resource resourceExist = createResourceObject(false);
+ when(toscaOperationFacade
+ .validateComponentNameAndModelExists(resourceExist.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
+ .thenReturn(Either.left(false));
+ validateUserRoles(Role.ADMIN, Role.DESIGNER);
+ Resource createdResource = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null,
+ null);
+
+ assertThat(createdResource).isNotNull();
+ createdResource.setLifecycleState(LifecycleStateEnum.CERTIFIED);
+ createdResource.setVersion("1.0");
+
+ Either<Resource, StorageOperationStatus> getLatestResult = Either.left(createdResource);
+ Either<Component, StorageOperationStatus> getCompLatestResult = Either.left(createdResource);
+ when(toscaOperationFacade.getLatestByToscaResourceNameAndModel(resourceExist.getToscaResourceName(), null))
+ .thenReturn(getCompLatestResult);
+ when(toscaOperationFacade.overrideComponent(any(Resource.class), any(Resource.class)))
+ .thenReturn(getLatestResult);
+
+ when(lifecycleBl.changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
+ any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean()))
+ .thenReturn(Either.left(createdResource));
+
+ Resource resourceToUpdtae = createResourceObject(false);
+
+ ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl
+ .createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false);
+ assertNotNull(createOrUpdateResource);
+
+ Mockito.verify(toscaOperationFacade, Mockito.times(1))
+ .overrideComponent(any(Resource.class), any(Resource.class));
+ Mockito.verify(lifecycleBl, Mockito.times(1))
+ .changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
+ any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
+
+ }
+
+ @Test
+ void createOrUpdateResourceNotExist() {
+ Resource resourceToUpdtae = createResourceObject(false);
+
+ Either<Component, StorageOperationStatus> getLatestResult = Either.right(StorageOperationStatus.NOT_FOUND);
+ when(toscaOperationFacade.getLatestByName(resourceToUpdtae.getName(), null)).thenReturn(getLatestResult);
+ when(toscaOperationFacade.getLatestByToscaResourceNameAndModel(resourceToUpdtae.getToscaResourceName(), null))
+ .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
+ when(toscaOperationFacade
+ .validateComponentNameAndModelExists(resourceToUpdtae.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
+ .thenReturn(Either.left(false));
+
+ ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl
+ .createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false);
+ assertThat(createOrUpdateResource).isNotNull();
+
+ Mockito.verify(toscaOperationFacade, times(1))
+ .createToscaComponent(resourceToUpdtae);
+ Mockito.verify(toscaOperationFacade, Mockito.times(0))
+ .overrideComponent(any(Resource.class), any(Resource.class));
+ Mockito.verify(lifecycleBl, Mockito.times(0))
+ .changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
+ any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
+
+ }
+
+ @Test
+ void testIfNodeTypeNameHasValidPrefix() {
+ final List<String> definedNodeTypeNamespaceList = ConfigurationManager.getConfigurationManager()
+ .getConfiguration().getDefinedResourceNamespace();
+
+ definedNodeTypeNamespaceList.parallelStream().forEach(validNodeTypePrefix -> {
+ final String nodeName = validNodeTypePrefix + "." + "abc";
+ final Optional<String> result = bl.validateNodeTypeNamePrefix(nodeName, definedNodeTypeNamespaceList);
+ assertTrue(result.isPresent());
+ });
+ }
+
+ @Test
+ void updateNestedResource_typeIsNew() throws IOException {
+ Resource resourceToUpdate = createResourceObject(false);
+ String nodeName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + "." + "abc";
+ String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-webServer.yml");
+ CsarInfo csarInfo = new CsarInfo(user, "abcd1234", new HashMap<>(), RESOURCE_NAME, "template name", jsonContent,
+ true);
+ String nestedResourceName = bl.buildNestedToscaResourceName(resourceToUpdate.getResourceType()
+ .name(), csarInfo.getVfResourceName(), nodeName)
+ .getRight();
+ when(toscaOperationFacade.getLatestByName(resourceToUpdate.getName(), null))
+ .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
+ when(toscaOperationFacade.getLatestByToscaResourceName(resourceToUpdate.getToscaResourceName(), null))
+ .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
+ when(toscaOperationFacade.getLatestByToscaResourceName(nestedResourceName, null))
+ .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
+
+ when(toscaOperationFacade.getLatestByToscaResourceNameAndModel(resourceToUpdate.getToscaResourceName(), null))
+ .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
+ when(toscaOperationFacade
+ .validateComponentNameAndModelExists(resourceToUpdate.getName(), null, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE))
+ .thenReturn(Either.left(false));
+
+ ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl
+ .createOrUpdateResourceByImport(resourceToUpdate, user, false, false, false, csarInfo, nodeName, false);
+ assertThat(createOrUpdateResource).isNotNull();
+
+ Mockito.verify(toscaOperationFacade, times(1))
+ .createToscaComponent(resourceToUpdate);
+ Mockito.verify(toscaOperationFacade, times(0))
+ .overrideComponent(any(Resource.class), any(Resource.class));
+ Mockito.verify(lifecycleBl, times(0))
+ .changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
+ any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
+ }
+
+ @Test
+ void updateNestedResource_typeExists() throws IOException {
+ createRoot();
+ Resource resourceToUpdate = createResourceObject(false);
+ setCanWorkOnResource(resourceResponse);
+ String nodeName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + "." + "abc";
+ String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-webServer.yml");
+ CsarInfo csarInfo = new CsarInfo(user, "abcd1234", new HashMap<>(), RESOURCE_NAME, "template name", jsonContent,
+ true);
+ String nestedResourceName = bl.buildNestedToscaResourceName(resourceToUpdate.getResourceType()
+ .name(), csarInfo.getVfResourceName(), nodeName)
+ .getRight();
+ when(toscaOperationFacade.getLatestByName(resourceToUpdate.getName(), null))
+ .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
+ when(toscaOperationFacade.getLatestByToscaResourceName(resourceToUpdate.getToscaResourceName(), null))
+ .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
+ when(toscaOperationFacade.getLatestByToscaResourceNameAndModel(resourceToUpdate.getToscaResourceName(), null))
+ .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
+ when(toscaOperationFacade.getLatestByToscaResourceName(nestedResourceName, null))
+ .thenReturn(Either.left(resourceResponse));
+ when(toscaOperationFacade.overrideComponent(any(Resource.class), any(Resource.class)))
+ .thenReturn(Either.left(resourceResponse));
+
+ ImmutablePair<Resource, ActionStatus> createOrUpdateResource = bl
+ .createOrUpdateResourceByImport(resourceToUpdate, user, false, false, false, csarInfo, nodeName, false);
+ assertThat(createOrUpdateResource).isNotNull();
+ Mockito.verify(toscaOperationFacade, times(1))
+ .overrideComponent(any(Resource.class), any(Resource.class));
+ Mockito.verify(lifecycleBl, times(0))
+ .changeState(anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT),
+ any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
+ }
+
+ @Test
+ void testValidatePropertiesDefaultValues_SuccessfullWithoutProperties() {
+ Resource basic = createResourceObject(true);
+
+ Boolean validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic);
+ assertTrue(validatePropertiesDefaultValues);
+ }
+
+ @Test
+ void testValidatePropertiesDefaultValues_SuccessfullWithProperties() {
+ Resource basic = createResourceObject(true);
+ PropertyDefinition property = new PropertyDefinition();
+ property.setName("myProperty");
+ property.setType(ToscaPropertyType.INTEGER.getType());
+ property.setDefaultValue("1");
+ List<PropertyDefinition> properties = new ArrayList<>();
+ properties.add(property);
+ basic.setProperties(properties);
+ when(propertyOperation.isPropertyTypeValid(property, (String) null)).thenReturn(true);
+ when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(true);
+ Boolean validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic);
+ assertTrue(validatePropertiesDefaultValues);
+ }
+
+ @Test
+ void testValidatePropertiesDefaultValues_FailedWithProperties() {
+ Resource basic = createResourceObject(true);
+ PropertyDefinition property = new PropertyDefinition();
+ property.setName("myProperty");
+ property.setType(ToscaPropertyType.INTEGER.getType());
+ property.setDefaultValue("1.5");
+ List<PropertyDefinition> properties = new ArrayList<>();
+ properties.add(property);
+ basic.setProperties(properties);
+
+ when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(false);
+ assertThrows(ComponentException.class, () -> {
+ bl.validatePropertiesDefaultValues(basic);
+ });
+ }
+
+ @Test
+ void testDeleteMarkedResourcesNoResources() {
+ Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(new ArrayList<>());
+
+ when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources);
+
+ Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
+ assertTrue(deleteMarkedResources.isLeft());
+ assertTrue(deleteMarkedResources.left().value().isEmpty());
+ }
+
+ @Test
+ void testDeleteMarkedResources() {
+ List<String> ids = new ArrayList<>();
+ String resourceInUse = "123";
+ String resourceFree = "456";
+ ids.add(resourceInUse);
+ ids.add(resourceFree);
+ Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids);
+ when(toscaOperationFacade.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources);
+
+ Either<Boolean, StorageOperationStatus> resourceInUseResponse = Either.left(true);
+ Either<Boolean, StorageOperationStatus> resourceFreeResponse = Either.left(false);
+
+ List<ArtifactDefinition> artifacts = new ArrayList<>();
+
+ when(toscaOperationFacade.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse);
+ when(toscaOperationFacade.isComponentInUse(resourceInUse)).thenReturn(resourceInUseResponse);
+
+ Either<Component, StorageOperationStatus> eitherDelete = Either.left(new
+ Resource());
+ when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete);
+
+ List<String> deletedComponents = new ArrayList<>();
+ deletedComponents.add(resourceFree);
+ when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.RESOURCE)).thenReturn(Either.left(deletedComponents));
+
+ Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
+ assertTrue(deleteMarkedResources.isLeft());
+ List<String> resourceIdList = deleteMarkedResources.left().value();
+ assertFalse(resourceIdList.isEmpty());
+ assertTrue(resourceIdList.contains(resourceFree));
+ assertFalse(resourceIdList.contains(resourceInUse));
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ void testFindVfCsarArtifactsToHandle() {
+
+ Class<ResourceBusinessLogic> targetClass = ResourceBusinessLogic.class;
+ String methodName = "findVfCsarArtifactsToHandle";
+ Resource resource = new Resource();
+ String deploymentArtifactToUpdateFileName = "deploymentArtifactToUpdate.yaml";
+ String deploymentArtifactToDeleteFileName = "deploymentArtifactToDelete.yaml";
+ String deploymentArtifactToCreateFileName = "deploymentArtifactToCreate.yaml";
+
+ String artifactInfoToUpdateFileName = "infoArtifactToUpdate.yaml";
+ String artifactInfoToDeleteFileName = "infoArtifactToDelete.yaml";
+ String artifactInfoToNotDeleteFileName = "infoArtifactNotToDelete.yaml";
+ String artifactInfoToCreateFileName = "infoArtifactToCreate.yaml";
+
+ byte[] oldPayloadData = "oldPayloadData".getBytes();
+ byte[] newPayloadData = "newPayloadData".getBytes();
+ Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>();
+
+ ArtifactDefinition deploymentArtifactToUpdate = new ArtifactDefinition();
+ deploymentArtifactToUpdate.setMandatory(false);
+ deploymentArtifactToUpdate.setArtifactName(deploymentArtifactToUpdateFileName);
+ deploymentArtifactToUpdate.setArtifactType("SNMP_POLL");
+ deploymentArtifactToUpdate.setPayload(oldPayloadData);
+ deploymentArtifactToUpdate
+ .setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
+
+ ArtifactDefinition deploymentArtifactToDelete = new ArtifactDefinition();
+ deploymentArtifactToDelete.setMandatory(false);
+ deploymentArtifactToDelete.setArtifactName(deploymentArtifactToDeleteFileName);
+ deploymentArtifactToDelete.setArtifactType("SNMP_TRAP");
+ deploymentArtifactToDelete.setPayload(oldPayloadData);
+ deploymentArtifactToDelete
+ .setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
+
+ ArtifactDefinition deploymentArtifactToIgnore = new ArtifactDefinition();
+
+ deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToUpdate.getArtifactName()),
+ deploymentArtifactToUpdate);
+ deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToDelete.getArtifactName()),
+ deploymentArtifactToDelete);
+ deploymentArtifacts.put("ignore", deploymentArtifactToIgnore);
+
+ Map<String, ArtifactDefinition> artifacts = new HashMap<>();
+
+ ArtifactDefinition artifactToUpdate = new ArtifactDefinition();
+ artifactToUpdate.setMandatory(false);
+ artifactToUpdate.setArtifactName(artifactInfoToUpdateFileName);
+ artifactToUpdate.setArtifactType("SNMP_POLL");
+ artifactToUpdate.setPayload(oldPayloadData);
+ artifactToUpdate.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
+
+ ArtifactDefinition artifactToDelete = new ArtifactDefinition();
+ artifactToDelete.setMandatory(false);
+ artifactToDelete.setArtifactName(artifactInfoToDeleteFileName);
+ artifactToDelete.setArtifactType("SNMP_TRAP");
+ artifactToDelete.setPayload(oldPayloadData);
+ artifactToDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
+ artifactToDelete.setIsFromCsar(true);
+
+ ArtifactDefinition artifactToNotDelete = new ArtifactDefinition();
+ artifactToNotDelete.setMandatory(false);
+ artifactToNotDelete.setArtifactName(artifactInfoToNotDeleteFileName);
+ artifactToNotDelete.setArtifactType("SNMP_TRAP");
+ artifactToNotDelete.setPayload(oldPayloadData);
+ artifactToNotDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
+ artifactToNotDelete.setIsFromCsar(false);
+
+ ArtifactDefinition artifactToIgnore = new ArtifactDefinition();
+
+ artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToUpdate.getArtifactName()), artifactToUpdate);
+ artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToDelete.getArtifactName()), artifactToDelete);
+ artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToNotDelete.getArtifactName()),
+ artifactToNotDelete);
+ artifacts.put("ignore", artifactToIgnore);
+
+ resource.setDeploymentArtifacts(deploymentArtifacts);
+ resource.setArtifacts(artifacts);
+
+ List<NonMetaArtifactInfo> artifactPathAndNameList = new ArrayList<>();
+ NonMetaArtifactInfo deploymentArtifactInfoToUpdate = new NonMetaArtifactInfo(
+ deploymentArtifactToUpdate.getArtifactName(), null,
+ deploymentArtifactToUpdate.getArtifactType(),
+ ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData, deploymentArtifactToUpdate.getArtifactName(), false);
+
+ NonMetaArtifactInfo informationalArtifactInfoToUpdate = new NonMetaArtifactInfo(
+ artifactToUpdate.getArtifactName(), null, artifactToUpdate.getArtifactType(),
+ ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData, artifactToUpdate.getArtifactName(), false);
+
+ NonMetaArtifactInfo informationalArtifactInfoToUpdateFromCsar = new NonMetaArtifactInfo(
+ artifactToUpdate.getArtifactName(), null, artifactToUpdate.getArtifactType(),
+ ArtifactGroupTypeEnum.INFORMATIONAL, newPayloadData, artifactToUpdate.getArtifactName(), true);
+
+ NonMetaArtifactInfo deploymentArtifactInfoToUpdateFromCsar = new NonMetaArtifactInfo(
+ artifactToUpdate.getArtifactName(), null, artifactToUpdate.getArtifactType(),
+ ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData, artifactToUpdate.getArtifactName(), true);
+
+ NonMetaArtifactInfo deploymentArtifactInfoToCreate = new NonMetaArtifactInfo(deploymentArtifactToCreateFileName,
+ null, ArtifactTypeEnum.OTHER.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData,
+ deploymentArtifactToCreateFileName, false);
+
+ NonMetaArtifactInfo informationalArtifactInfoToCreate = new NonMetaArtifactInfo(artifactInfoToCreateFileName,
+ null, ArtifactTypeEnum.OTHER.getType(), ArtifactGroupTypeEnum.INFORMATIONAL, newPayloadData,
+ artifactInfoToCreateFileName, false);
+
+ artifactPathAndNameList.add(deploymentArtifactInfoToUpdate);
+ artifactPathAndNameList.add(informationalArtifactInfoToUpdate);
+ artifactPathAndNameList.add(deploymentArtifactInfoToCreate);
+ artifactPathAndNameList.add(informationalArtifactInfoToCreate);
+ artifactPathAndNameList.add(informationalArtifactInfoToUpdateFromCsar);
+ artifactPathAndNameList.add(deploymentArtifactInfoToUpdateFromCsar);
+
+ Object[] argObjects = {resource, artifactPathAndNameList, user};
+ Class[] argClasses = {Resource.class, List.class, User.class};
+ try {
+ Method method = targetClass.getDeclaredMethod(methodName, argClasses);
+ method.setAccessible(true);
+ Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = (Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat>) method
+ .invoke(bl, argObjects);
+ assertTrue(findVfCsarArtifactsToHandleRes.isLeft());
+ EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> foundVfArtifacts = findVfCsarArtifactsToHandleRes
+ .left()
+ .value();
+ assertEquals(4, foundVfArtifacts.get(ArtifactOperationEnum.CREATE)
+ .size());
+ assertEquals(4, foundVfArtifacts.get(ArtifactOperationEnum.UPDATE)
+ .size());
+ assertEquals(1, foundVfArtifacts.get(ArtifactOperationEnum.DELETE)
+ .size());
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Test
+ void testVFGeneratedInputs() {
+ validateUserRoles(Role.ADMIN, Role.DESIGNER);
+ Resource resource = createVF();
+ List<InputDefinition> inputs = resource.getInputs();
+ assertEquals(6, inputs.size());
+ for (InputDefinition input : inputs) {
+ assertThat(input.getOwnerId()).isNotNull();
+ }
+ assertEquals(resource.getDerivedFromGenericType(), genericVF.getToscaResourceName());
+ assertEquals(resource.getDerivedFromGenericVersion(), genericVF.getVersion());
+ }
+
+ @Test
+ void testCRGeneratedInputs() {
+ validateUserRoles(Role.ADMIN, Role.DESIGNER);
+ Resource resource = createCR();
+ List<InputDefinition> inputs = resource.getInputs();
+ assertEquals(3, inputs.size());
+ for (InputDefinition input : inputs) {
+ assertThat(input.getOwnerId()).isNotNull();
+ }
+ assertEquals(resource.getDerivedFromGenericType(), genericCR.getToscaResourceName());
+ assertEquals(resource.getDerivedFromGenericVersion(), genericCR.getVersion());
+ }
+
+ @Test
+ void testVFUpdateGenericInputsToLatestOnCheckout() {
+ validateUserRoles(Role.ADMIN, Role.DESIGNER);
+ // create a VF that is derived from generic version 1.0
+ Resource resource = createVF();
+ // create a new generic version without properties
+ genericVF.setVersion("2.0");
+ genericVF.setProperties(null);
+ String currentDerivedFromVersion = resource.getDerivedFromGenericVersion();
+ List<InputDefinition> currentInputs = resource.getInputs();
+ // verify previous inputs ownerId fields exist - user may not delete
+ // generated inputs
+ assertEquals(6, currentInputs.stream()
+ .filter(p -> null != p.getOwnerId())
+ .collect(Collectors.toList())
+ .size());
+ Either<Boolean, ResponseFormat> upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource);
+ // verify success
+ assertTrue(upgradeToLatestGeneric.isLeft());
+ // verify update required and valid
+ assertTrue(upgradeToLatestGeneric.left()
+ .value());
+ // verify version was upgraded
+ assertNotEquals(resource.getDerivedFromGenericVersion(), currentDerivedFromVersion);
+ // verify inputs were not deleted
+ assertEquals(6, resource.getInputs()
+ .size());
+ // verify inputs ownerId fields were removed - user may delete/edit
+ // inputs
+ assertEquals(6, resource.getInputs()
+ .stream()
+ .filter(p -> null == p.getOwnerId())
+ .collect(Collectors.toList())
+ .size());
+ }
+
+ @Test
+ void testVFUpdateGenericInputsToLatestOnCheckoutNotPerformed() {
+
+ // create a VF that is derived from generic version 1.0
+ validateUserRoles(Role.ADMIN, Role.DESIGNER);
+ Resource resource = createVF();
+
+ // add an input to the VF
+ PropertyDefinition newProp = new PropertyDefinition();
+ newProp.setType("integer");
+ newProp.setName("newProp");
+ resource.getInputs()
+ .add(new InputDefinition(newProp));
+
+ // create a new generic version with a new property which has the same
+ // name as a user defined input on the VF with a different type
+ genericVF.setVersion("2.0");
+ newProp.setType("string");
+ genericVF.setProperties(new ArrayList<>());
+ genericVF.getProperties()
+ .add(newProp);
+ when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericVF));
+ when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(),
+ genericVF.getUniqueId())).thenCallRealMethod();
+ String currentDerivedFromVersion = resource.getDerivedFromGenericVersion();
+ assertEquals(6, resource.getInputs()
+ .stream()
+ .filter(p -> null != p.getOwnerId())
+ .collect(Collectors.toList())
+ .size());
+ Either<Boolean, ResponseFormat> upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource);
+ // verify success
+ assertTrue(upgradeToLatestGeneric.isLeft());
+ // verify update is invalid an void
+ assertFalse(upgradeToLatestGeneric.left().value());
+ // verify version was not upgraded
+ assertEquals(resource.getDerivedFromGenericVersion(), currentDerivedFromVersion);
+ // verify inputs were not removed
+ assertEquals(7, resource.getInputs().size());
+ // verify user defined input exists
+ assertEquals(1, resource.getInputs()
+ .stream()
+ .filter(p -> null == p.getOwnerId())
+ .collect(Collectors.toList())
+ .size());
+ assertEquals("integer", resource.getInputs()
+ .stream()
+ .filter(p -> null == p.getOwnerId())
+ .findAny()
+ .get()
+ .getType());
+ }
+
+ @Test
+ void testPNFGeneratedInputsNoGeneratedInformationalArtifacts() {
+ validateUserRoles(Role.ADMIN, Role.DESIGNER);
+ Resource resource = createPNF();
+ List<InputDefinition> inputs = resource.getInputs();
+ assertEquals(3, inputs.size());
+ for (InputDefinition input : inputs) {
+ assertThat(input.getOwnerId()).isNotNull();
+ }
+ assertEquals(resource.getDerivedFromGenericType(), genericPNF.getToscaResourceName());
+ assertEquals(resource.getDerivedFromGenericVersion(), genericPNF.getVersion());
+ assertEquals(0, resource.getArtifacts()
+ .size());
+ }
+
+ private Resource createVF() {
+
+ genericVF = setupGenericTypeMock(GENERIC_VF_NAME);
+ when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_VF_NAME))
+ .thenReturn(Either.left(genericVF));
+ Resource resource = createResourceObject(true);
+ resource.setDerivedFrom(null);
+ resource.setResourceType(ResourceTypeEnum.VF);
+ when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource));
+ when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource, null)).thenReturn(Either.left(genericVF));
+ when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericVF)).thenCallRealMethod();
+ when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(),
+ resource.getUniqueId())).thenCallRealMethod();
+ when(toscaOperationFacade
+ .validateComponentNameAndModelExists(resource.getName(), null, ResourceTypeEnum.VF, ComponentTypeEnum.RESOURCE))
+ .thenReturn(Either.left(false));
+ Resource createdResource = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertThat(createdResource).isNotNull();
+ return createdResource;
+ }
+
+ private Resource createRoot() {
+ rootType = setupGenericTypeMock(GENERIC_ROOT_NAME);
+ when(toscaOperationFacade.getLatestByToscaResourceName(GENERIC_ROOT_NAME, null))
+ .thenReturn(Either.left(rootType));
+ return rootType;
+ }
+
+ private Resource createCR() {
+
+ genericCR = setupGenericTypeMock(GENERIC_CR_NAME);
+ when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_CR_NAME))
+ .thenReturn(Either.left(genericCR));
+ Resource resource = createResourceObject(true);
+ resource.setDerivedFrom(null);
+ resource.setResourceType(ResourceTypeEnum.CR);
+ when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource));
+ when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource, null)).thenReturn(Either.left(genericCR));
+ when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericCR)).thenCallRealMethod();
+ when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericCR.getProperties(),
+ resource.getUniqueId())).thenCallRealMethod();
+ when(toscaOperationFacade
+ .validateComponentNameAndModelExists(resource.getName(), null, ResourceTypeEnum.CR, ComponentTypeEnum.RESOURCE))
+ .thenReturn(Either.left(false));
+ Resource createdResource = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertThat(createdResource).isNotNull();
+ return createdResource;
+ }
+
+ private Resource createPNF() {
+
+ genericPNF = setupGenericTypeMock(GENERIC_PNF_NAME);
+ when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_PNF_NAME))
+ .thenReturn(Either.left(genericPNF));
+ Resource resource = createResourceObject(true);
+ resource.setDerivedFrom(null);
+ resource.setResourceType(ResourceTypeEnum.PNF);
+ when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource));
+ when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource, null)).thenReturn(Either.left(genericPNF));
+ when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericPNF)).thenCallRealMethod();
+ when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericPNF.getProperties(),
+ resource.getUniqueId())).thenCallRealMethod();
+ when(toscaOperationFacade
+ .validateComponentNameAndModelExists(resource.getName(), null, ResourceTypeEnum.PNF, ComponentTypeEnum.RESOURCE))
+ .thenReturn(Either.left(false));
+ Resource createdResource = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertThat(createdResource).isNotNull();
+ return createdResource;
+ }
+
+ private Map<String, String> getGenericPropertiesByToscaName(String toscaName) {
+ HashMap<String, String> PNFProps = new HashMap<String, String>() {
+ {
+ put("nf_function", "string");
+ put("nf_role", "string");
+ put("nf_type", "string");
+ }
+ };
+
+ HashMap<String, String> CRProps = new HashMap<String, String>() {
+ {
+ put("cr_function", "string");
+ put("cr_role", "string");
+ put("cr_type", "string");
+ }
+ };
+
+ HashMap<String, String> VFProps = new HashMap<String, String>() {
+ {
+ putAll(CRProps);
+ put("availability_zone_max_count", "integer");
+ put("min_instances", "integer");
+ put("max_instances", "integer");
+ }
+ };
+
+ if (toscaName.contains("PNF")) {
+ return PNFProps;
+ }
+ if (toscaName.contains("CR")) {
+ return CRProps;
+ }
+ if (toscaName.contains("VF")) {
+ return VFProps;
+ }
+
+ return new HashMap<>();
+ }
+
+ private Resource setupGenericTypeMock(String toscaName) {
+
+ Resource genericType = createResourceObject(true);
+ genericType.setVersion("1.0");
+ genericType.setToscaResourceName(toscaName);
+ genericType.setAbstract(true);
+ List<PropertyDefinition> genericProps = new ArrayList<>();
+ Map<String, String> genericPropsMap = getGenericPropertiesByToscaName(toscaName);
+ genericPropsMap.forEach((name, type) -> {
+ PropertyDefinition prop = new PropertyDefinition();
+ prop.setName(name);
+ prop.setType(type);
+ genericProps.add(prop);
+ });
+
+ genericType.setProperties(genericProps);
+ return genericType;
+ }
+
+ private void validateUserRoles(Role... roles) {
+ List<Role> listOfRoles = Stream.of(roles)
+ .collect(Collectors.toList());
+ }
+
+ @Test
+ void testUpdateVolumeGroup() {
+ Resource resource = getResourceWithType("HEAT_VOL", "org.openecomp.groups.VfModule");
+ bl.updateVolumeGroup(resource);
+ assertThat(resource.getGroups().get(0).getProperties().get(0).getValue()).isEqualTo(Boolean.toString(true));
+ }
+
+ @Test
+ void testUpdateVolumeGroupNull() {
+ Resource resource = getResourceWithType("HEAT_VOL", "org.openecomp.groups.VfModule");
+ resource.setGroups(null);
+ bl.updateVolumeGroup(resource);
+ assertThat(resource.getGroups()).isNull();
+ }
+
+ @Test
+ void testUpdateVolumeGroupFail() {
+ Resource resource = getResourceWithType("NON_EXIST_HEAT", "org.openecomp.groups.VfModule");
+ bl.updateVolumeGroup(resource);
+ assertThat(resource.getGroups().get(0).getProperties().get(0).getValue()).isEqualTo(Boolean.toString(false));
+ }
+
+ private Resource getResourceWithType(String artifactType, String groupDefinitionType) {
+ ArtifactDefinition artifactToUpdate = new ArtifactDefinition();
+ List<GroupDefinition> groups = new ArrayList<>();
+ GroupDefinition gd = new GroupDefinition();
+ List<PropertyDataDefinition> properties = new ArrayList<>();
+ PropertyDataDefinition pdd = new PropertyDataDefinition();
+ Map<String, ArtifactDefinition> artifacts = new HashMap<>();
+ List<String> artifactsList = new ArrayList<>();
+
+ artifactToUpdate.setArtifactType(artifactType);
+ artifactToUpdate.setArtifactName(artifactType);
+ artifactToUpdate.setUniqueId(artifactType);
+ Resource resource = createResourceObjectCsar(true);
+ artifactsList.add(artifactToUpdate.getArtifactName());
+
+ pdd.setName("volume_group");
+ pdd.setValue("true");
+ pdd.setType(ToscaPropertyType.BOOLEAN.getType());
+
+ artifacts.put(artifactToUpdate.getArtifactName(), artifactToUpdate);
+
+ properties.add(pdd);
+ gd.setType(groupDefinitionType);
+ gd.setProperties(properties);
+ gd.setArtifacts(artifactsList);
+ groups.add(gd);
+
+ resource.setGroups(groups);
+ resource.setDeploymentArtifacts(artifacts);
+ return resource;
+ }
+
+ @Test
+ void testGetAllCertifiedResources() {
+ List<Resource> list = bl.getAllCertifiedResources(true, HighestFilterEnum.HIGHEST_ONLY, "USER");
+ assertEquals(reslist, list);
+ }
+
+ @Test
+ void testGetAllCertifiedResources_exception() {
+ assertThrows(StorageException.class, () -> {
+ List<Resource> list = bl.getAllCertifiedResources(false, HighestFilterEnum.NON_HIGHEST_ONLY, "USER");
+ assertEquals(reslist, list);
+ });
+ }
+
+ @Test
+ void testValidateResourceNameExists() {
+ Either<Map<String, Boolean>, ResponseFormat> res = bl.validateResourceNameExists("Resource", ResourceTypeEnum.CR, "jh0003");
+ assertEquals(true, res.isLeft());
+ }
+
+ @Test
+ void rollbackWithEitherAlwaysReturnARuntimeException() {
+ JanusGraphDao janusGraphDao = mockJanusGraphDao;
+ ActionStatus actionStatus = ActionStatus.INPUTS_NOT_FOUND;
+ String params = "testName";
+
+ Either<Object, RuntimeException> result =
+ ResourceBusinessLogic.rollbackWithEither(janusGraphDao, actionStatus, params);
+
+ assertTrue(result.isRight());
+ assertTrue(result.right().value() instanceof ByActionStatusComponentException);
+ }
+
+ @Test
+ void rollbackWithEitherWorksWithNullJanusGraphDao() {
+ JanusGraphDao janusGraphDao = null;
+ ActionStatus actionStatus = ActionStatus.INPUTS_NOT_FOUND;
+ String params = "testName";
+
+ Either<Object, RuntimeException> result =
+ ResourceBusinessLogic.rollbackWithEither(janusGraphDao, actionStatus, params);
+
+ assertTrue(result.isRight());
+ assertTrue(result.right().value() instanceof ByActionStatusComponentException);
+ }
+
+ @Test
+ void testDeleteResource_NotFound() {
+ Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
+ ResponseFormat respFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND),
+ "");
+ ResponseFormat actualResponseFormat = bl.deleteResource("1", user);
+ assertEquals(respFormat.getStatus(), actualResponseFormat.getStatus());
+ }
+
+ @Test
+ void testDeleteResource_NotArchived() {
+ Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(Either.left(resourceResponse));
+ ComponentException actualComponentException = assertThrows(ComponentException.class,
+ () -> bl.deleteResourceAllVersions(resourceResponse.getUniqueId(), user));
+ assertEquals(ActionStatus.COMPONENT_NOT_ARCHIVED, actualComponentException.getActionStatus());
+ assertEquals("my-resource_name with space:0.1", actualComponentException.getParams()[0]);
+ }
+
+ @Test
+ void testDeleteResource_IsInUse() {
+ Resource resourceObject = createResourceObject(true);
+ Mockito.when(toscaOperationFacade.getToscaElement(anyString())).thenReturn(Either.left(resourceObject));
+ resourceObject.setArchived(true);
+ OperationException oe = new OperationException(ActionStatus.COMPONENT_IN_USE_BY_ANOTHER_COMPONENT, "resource_name");
+ Mockito.when(toscaOperationFacade.deleteComponent(resourceObject.getInvariantUUID(), NodeTypeEnum.Resource, true)).thenThrow(oe);
+ OperationException actualOperationException = assertThrows(OperationException.class,
+ () -> bl.deleteResourceAllVersions(resourceResponse.getUniqueId(), user));
+ assertEquals(ActionStatus.COMPONENT_IN_USE_BY_ANOTHER_COMPONENT, actualOperationException.getActionStatus());
+ assertEquals("resource_name", actualOperationException.getParams()[0]);
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentPropertyServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentPropertyServletTest.java
index e455896c5e..05e5eedb1f 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentPropertyServletTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentPropertyServletTest.java
@@ -91,8 +91,7 @@ class ComponentPropertyServletTest extends JerseySpringBaseTest {
property.setType(STRING_TYPE);
EntryData<String, PropertyDefinition> propertyEntry = new EntryData<>(VALID_PROPERTY_NAME, property);
- when(propertyBl.addPropertyToComponent(eq(SERVICE_ID), any(), any(), any()))
- .thenReturn(Either.left(propertyEntry));
+ when(propertyBl.addPropertyToComponent(eq(SERVICE_ID), any(), any())).thenReturn(Either.left(propertyEntry));
Response propertyInService =
componentPropertyServlet.createPropertyInService(SERVICE_ID, getValidProperty(), request, USER_ID);
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceProperty.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceProperty.java
index 7e0342866f..5a8cd91492 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceProperty.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceProperty.java
@@ -55,7 +55,7 @@ public class ComponentInstanceProperty extends PropertyDefinition implements ICo
public ComponentInstanceProperty(Boolean hidden, PropertyDefinition pd, String valueUniqueUid) {
super(pd);
- this.hidden = hidden;
+ this.setHidden(hidden);
this.valueUniqueUid = valueUniqueUid;
setParentUniqueId(pd.getParentUniqueId());
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaOperationFacade.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaOperationFacade.java
index 9c34b4caaf..09e02337a1 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaOperationFacade.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaOperationFacade.java
@@ -118,7 +118,6 @@ import org.openecomp.sdc.be.model.catalog.CatalogComponent;
import org.openecomp.sdc.be.model.jsonjanusgraph.config.ContainerInstanceTypesData;
import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate;
import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement;
-import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElementTypeEnum;
import org.openecomp.sdc.be.model.jsonjanusgraph.operations.exception.ToscaOperationExceptionSupplier;
import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
import org.openecomp.sdc.be.model.operations.StorageException;
@@ -173,12 +172,12 @@ public class ToscaOperationFacade {
return Optional.empty();
}
List<CapabilityDefinition> capabilityDefinitionList = componentCapabilities.values().stream().flatMap(Collection::stream)
- .collect(Collectors.toList());
+ .collect(Collectors.toList());
if (CollectionUtils.isEmpty(capabilityDefinitionList)) {
return Optional.empty();
}
return capabilityDefinitionList.stream().filter(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(propertyParentUniqueId))
- .findAny();
+ .findAny();
}
public <T extends Component> Either<T, StorageOperationStatus> getToscaFullElement(String componentId) {
@@ -235,7 +234,7 @@ public class ToscaOperationFacade {
props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
Either<List<GraphVertex>, JanusGraphOperationStatus> getVertexEither = janusGraphDao
- .getByCriteria(ModelConverter.getVertexType(component), props);
+ .getByCriteria(ModelConverter.getVertexType(component), props);
if (getVertexEither.isRight()) {
log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
@@ -304,7 +303,7 @@ public class ToscaOperationFacade {
return StorageOperationStatus.OK;
} else {
Either<GraphVertex, JanusGraphOperationStatus> getResponse = janusGraphDao
- .getVertexById(componentToDelete.getUniqueId(), JsonParseFlagEnum.ParseAll);
+ .getVertexById(componentToDelete.getUniqueId(), JsonParseFlagEnum.ParseAll);
if (getResponse.isRight()) {
log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentToDelete.getUniqueId(), getResponse.right().value());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getResponse.right().value());
@@ -376,7 +375,7 @@ public class ToscaOperationFacade {
propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
final Either<List<GraphVertex>, JanusGraphOperationStatus> highestResources = janusGraphDao
- .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, parseFlag, model);
+ .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, parseFlag, model);
if (highestResources.isRight()) {
final JanusGraphOperationStatus status = highestResources.right().value();
log.debug("failed to find resource with name {}. status={} ", nodeName, status);
@@ -416,7 +415,7 @@ public class ToscaOperationFacade {
Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
Either<List<GraphVertex>, JanusGraphOperationStatus> resources = janusGraphDao
- .getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
+ .getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
if (resources.isRight()) {
if (resources.right().value() == JanusGraphOperationStatus.NOT_FOUND) {
return StorageOperationStatus.OK;
@@ -458,7 +457,7 @@ public class ToscaOperationFacade {
public Either<Resource, StorageOperationStatus> getByToscaResourceNameMatchingVendorRelease(final String toscaResourceName,
final String vendorVersion) {
return getByToscaResourceNameMatchingVendorRelease(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata,
- vendorVersion);
+ vendorVersion);
}
public Either<Resource, StorageOperationStatus> getByToscaResourceNameMatchingVendorRelease(String toscaResourceName, VertexTypeEnum vertexType,
@@ -468,13 +467,13 @@ public class ToscaOperationFacade {
props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
Map<String, Entry<JanusGraphPredicate, Object>> predicateCriteria = getVendorVersionPredicate(vendorRelease);
Either<List<GraphVertex>, JanusGraphOperationStatus> getLatestRes = janusGraphDao
- .getByCriteria(vertexType, props, null, predicateCriteria, parseFlag, null);
+ .getByCriteria(vertexType, props, null, predicateCriteria, parseFlag, null);
if (getLatestRes.isRight() || CollectionUtils.isEmpty(getLatestRes.left().value())) {
getLatestRes = janusGraphDao.getByCriteria(vertexType, props, parseFlag);
}
return getLatestRes.right().map(status -> {
CommonUtility
- .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status);
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status);
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
}).left().bind(resources -> {
double version = 0.0;
@@ -507,7 +506,7 @@ public class ToscaOperationFacade {
hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
Either<List<GraphVertex>, JanusGraphOperationStatus> getResourceRes = janusGraphDao
- .getByCriteria(VertexTypeEnum.NODE_TYPE, hasProperties, hasNotProperties, JsonParseFlagEnum.ParseAll, model);
+ .getByCriteria(VertexTypeEnum.NODE_TYPE, hasProperties, hasNotProperties, JsonParseFlagEnum.ParseAll, model);
if (getResourceRes.isRight()) {
JanusGraphOperationStatus status = getResourceRes.right().value();
log.debug("failed to find resource with toscaResourceName {}, version {}. Status is {} ", toscaResourceName, version, status);
@@ -543,12 +542,12 @@ public class ToscaOperationFacade {
public List<GraphVertex> getResourceModelElementVertices(final Resource resource) {
final Either<GraphVertex, JanusGraphOperationStatus> vertex =
- janusGraphDao.getVertexById(resource.getUniqueId(), JsonParseFlagEnum.NoParse);
+ janusGraphDao.getVertexById(resource.getUniqueId(), JsonParseFlagEnum.NoParse);
if (vertex.isRight() || Objects.isNull(vertex.left().value())) {
return Collections.emptyList();
}
final Either<List<GraphVertex>, JanusGraphOperationStatus> nodeModelVertices =
- janusGraphDao.getParentVertices(vertex.left().value(), EdgeLabelEnum.MODEL_ELEMENT, JsonParseFlagEnum.NoParse);
+ janusGraphDao.getParentVertices(vertex.left().value(), EdgeLabelEnum.MODEL_ELEMENT, JsonParseFlagEnum.NoParse);
if (nodeModelVertices.isRight() || nodeModelVertices.left().value() == null) {
return Collections.emptyList();
}
@@ -578,7 +577,7 @@ public class ToscaOperationFacade {
Either<List<GraphVertex>, JanusGraphOperationStatus> getLatestRes = janusGraphDao.getByCriteria(vertexType, props, parseFlag);
return getLatestRes.right().map(status -> {
CommonUtility
- .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status);
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status);
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
}).left().bind(resources -> {
double version = 0.0;
@@ -620,7 +619,7 @@ public class ToscaOperationFacade {
if (getLatestRes.isRight()) {
JanusGraphOperationStatus status = getLatestRes.right().value();
CommonUtility
- .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status);
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status);
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
if (result == null) {
@@ -678,7 +677,7 @@ public class ToscaOperationFacade {
public Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> associateResourceInstances(Component component, String componentId,
List<RequirementCapabilityRelDef> relations) {
Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> reqAndCapListEither = nodeTemplateOperation
- .associateResourceInstances(component, componentId, relations);
+ .associateResourceInstances(component, componentId, relations);
if (component != null) {
updateInstancesCapAndReqOnComponentFromDB(component);
}
@@ -689,7 +688,7 @@ public class ToscaOperationFacade {
Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, name);
Either<List<GraphVertex>, JanusGraphOperationStatus> resources = janusGraphDao
- .getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
+ .getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
if (resources.isRight() && resources.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
log.debug("failed to get resources from graph with property name: {}", name);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(resources.right().value()));
@@ -714,14 +713,14 @@ public class ToscaOperationFacade {
public Either<Resource, StorageOperationStatus> overrideComponent(Resource newComponent, Resource oldComponent) {
copyArtifactsToNewComponent(newComponent, oldComponent);
Either<GraphVertex, JanusGraphOperationStatus> componentVEither = janusGraphDao
- .getVertexById(oldComponent.getUniqueId(), JsonParseFlagEnum.NoParse);
+ .getVertexById(oldComponent.getUniqueId(), JsonParseFlagEnum.NoParse);
if (componentVEither.isRight()) {
log.debug("Failed to fetch component {} error {}", oldComponent.getUniqueId(), componentVEither.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(componentVEither.right().value()));
}
GraphVertex componentv = componentVEither.left().value();
Either<GraphVertex, JanusGraphOperationStatus> parentVertexEither = janusGraphDao
- .getParentVertex(componentv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
+ .getParentVertex(componentv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
if (parentVertexEither.isRight() && parentVertexEither.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
log.debug("Failed to fetch parent version for component {} error {}", oldComponent.getUniqueId(), parentVertexEither.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(parentVertexEither.right().value()));
@@ -738,7 +737,7 @@ public class ToscaOperationFacade {
}
Resource newElement = createToscaComponent.left().value();
Either<GraphVertex, JanusGraphOperationStatus> newVersionEither = janusGraphDao
- .getVertexById(newElement.getUniqueId(), JsonParseFlagEnum.NoParse);
+ .getVertexById(newElement.getUniqueId(), JsonParseFlagEnum.NoParse);
if (newVersionEither.isRight()) {
log.debug("Failed to fetch new tosca element component {} error {}", newComponent.getUniqueId(), newVersionEither.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(newVersionEither.right().value()));
@@ -746,10 +745,10 @@ public class ToscaOperationFacade {
if (parentVertexEither.isLeft()) {
GraphVertex previousVersionV = parentVertexEither.left().value();
JanusGraphOperationStatus createEdge = janusGraphDao
- .createEdge(previousVersionV, newVersionEither.left().value(), EdgeLabelEnum.VERSION, null);
+ .createEdge(previousVersionV, newVersionEither.left().value(), EdgeLabelEnum.VERSION, null);
if (createEdge != JanusGraphOperationStatus.OK) {
log.debug("Failed to associate to previous version {} new version {} error {}", previousVersionV.getUniqueId(),
- newVersionEither.right().value(), createEdge);
+ newVersionEither.right().value(), createEdge);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdge));
}
}
@@ -819,7 +818,7 @@ public class ToscaOperationFacade {
propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
Either<List<GraphVertex>, JanusGraphOperationStatus> highestResources = janusGraphDao
- .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, parseFlag, model);
+ .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, parseFlag, model);
if (highestResources.isRight()) {
JanusGraphOperationStatus status = highestResources.right().value();
log.debug("failed to find resource with name {}. status={} ", nodeName, status);
@@ -858,7 +857,7 @@ public class ToscaOperationFacade {
}
propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
Either<List<GraphVertex>, JanusGraphOperationStatus> getComponentsRes = janusGraphDao
- .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
+ .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
if (getComponentsRes.isRight()) {
JanusGraphOperationStatus status = getComponentsRes.right().value();
log.debug("Failed to fetch the component with system name {}. Status is {} ", systemName, status);
@@ -870,7 +869,7 @@ public class ToscaOperationFacade {
getComponentRes = getToscaElementByOperation(componentVertex);
if (getComponentRes.isRight()) {
log.debug("Failed to get the component {}. Status is {} ", componentVertex.getJsonMetadataField(JsonPresentationFields.NAME),
- getComponentRes.right().value());
+ getComponentRes.right().value());
result = Either.right(getComponentRes.right().value());
break;
}
@@ -902,7 +901,7 @@ public class ToscaOperationFacade {
hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
}
Either<List<GraphVertex>, JanusGraphOperationStatus> getResourceRes = janusGraphDao
- .getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
+ .getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
if (getResourceRes.isRight()) {
JanusGraphOperationStatus status = getResourceRes.right().value();
log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
@@ -925,7 +924,7 @@ public class ToscaOperationFacade {
}
Map<String, Entry<JanusGraphPredicate, Object>> predicateCriteria = getVendorVersionPredicate(vendorRelease);
Either<List<GraphVertex>, JanusGraphOperationStatus> getResourceRes = janusGraphDao.getByCriteria(null, hasProperties, hasNotProperties,
- predicateCriteria, parseFlag, modelName);
+ predicateCriteria, parseFlag, modelName);
if (getResourceRes.isRight()) {
JanusGraphOperationStatus status = getResourceRes.right().value();
log.debug("failed to find resource with name {}, version {}. Status is {} ", name, predicateCriteria, status);
@@ -937,8 +936,8 @@ public class ToscaOperationFacade {
public Either<List<CatalogComponent>, StorageOperationStatus> getCatalogOrArchiveComponents(boolean isCatalog,
List<OriginTypeEnum> excludeTypes) {
List<ResourceTypeEnum> excludedResourceTypes = Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()).stream()
- .filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name()))
- .collect(Collectors.toList());
+ .filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name()))
+ .collect(Collectors.toList());
return topologyTemplateOperation.getElementCatalogData(isCatalog, excludedResourceTypes);
}
@@ -950,8 +949,8 @@ public class ToscaOperationFacade {
Either<List<ToscaElement>, StorageOperationStatus> catalogDataResult;
List<ToscaElement> toscaElements = new ArrayList<>();
List<ResourceTypeEnum> excludedResourceTypes = Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()).stream()
- .filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name()))
- .collect(Collectors.toList());
+ .filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name()))
+ .collect(Collectors.toList());
switch (componentType) {
case RESOURCE:
catalogDataResult = nodeTypeOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, excludedResourceTypes, isHighestVersions);
@@ -1038,12 +1037,12 @@ public class ToscaOperationFacade {
private void checkNotUsed(List<GraphVertex> vertices) {
boolean isInUse = isAnyComponentInUse(vertices);
if (isInUse) {
- Set<GraphVertex> listOfVertices = getComponentsUsingComponents(vertices);
+ Set<GraphVertex> listOfVertices = getComponentsUsingComponents(vertices);
List<String> listOfStringComponents = new ArrayList<>();
for (GraphVertex componentVertex : listOfVertices) {
listOfStringComponents.add(
- componentVertex.getMetadataJson().get(GraphPropertyEnum.COMPONENT_TYPE.getProperty()) + " "
- + componentVertex.getMetadataJson().get(GraphPropertyEnum.NAME.getProperty())
+ componentVertex.getMetadataJson().get(GraphPropertyEnum.COMPONENT_TYPE.getProperty()) + " "
+ + componentVertex.getMetadataJson().get(GraphPropertyEnum.NAME.getProperty())
);
}
String stringOfComponents = String.join(", ", listOfStringComponents);
@@ -1095,10 +1094,10 @@ public class ToscaOperationFacade {
private List<GraphVertex> isInUse(GraphVertex elementV) {
final List<EdgeLabelEnum> forbiddenEdgeLabelEnums = Arrays
- .asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF);
+ .asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF);
for (EdgeLabelEnum edgeLabelEnum : forbiddenEdgeLabelEnums) {
Either<List<GraphVertex>, JanusGraphOperationStatus> inUseBy =
- janusGraphDao.getParentVertices(elementV, edgeLabelEnum, JsonParseFlagEnum.ParseAll);
+ janusGraphDao.getParentVertices(elementV, edgeLabelEnum, JsonParseFlagEnum.ParseAll);
if (inUseBy.isLeft()) {
if (log.isDebugEnabled()) {
log.debug("Element {} in use.", elementV.getUniqueId());
@@ -1117,7 +1116,7 @@ public class ToscaOperationFacade {
Either<ToscaElement, StorageOperationStatus> deleteToscaElement = deleteToscaElement(elementV);
if (deleteToscaElement.isRight()) {
log.debug("Failed to delete marked element UniqueID {}, Name {}, error {}", elementV.getUniqueId(),
- elementV.getMetadataProperties().get(GraphPropertyEnum.NAME), deleteToscaElement.right().value());
+ elementV.getMetadataProperties().get(GraphPropertyEnum.NAME), deleteToscaElement.right().value());
continue;
}
deleted.add(elementV.getUniqueId());
@@ -1184,19 +1183,19 @@ public class ToscaOperationFacade {
}
String nextComponentInstanceCounter = getNextComponentInstanceCounter(containerComponent, nameToFindForCounter);
Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addResult = nodeTemplateOperation
- .addComponentInstanceToTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
- ModelConverter.convertToToscaElement(origComponent), nextComponentInstanceCounter, componentInstance, allowDeleted, user);
+ .addComponentInstanceToTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
+ ModelConverter.convertToToscaElement(origComponent), nextComponentInstanceCounter, componentInstance, allowDeleted, user);
if (addResult.isRight()) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the component instance {} to container component {}. ",
- componentInstance.getName(), containerComponent.getName());
+ componentInstance.getName(), containerComponent.getName());
result = Either.right(addResult.right().value());
}
if (result == null) {
updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponent.getUniqueId());
if (updateContainerComponentRes.isRight()) {
CommonUtility
- .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ",
- containerComponent.getName(), componentInstance.getName());
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ",
+ containerComponent.getName(), componentInstance.getName());
result = Either.right(updateContainerComponentRes.right().value());
}
}
@@ -1204,8 +1203,8 @@ public class ToscaOperationFacade {
Component updatedComponent = ModelConverter.convertFromToscaElement(updateContainerComponentRes.left().value());
String createdInstanceId = addResult.left().value().getRight();
CommonUtility
- .addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been added to container component {}. ", createdInstanceId,
- updatedComponent.getName());
+ .addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been added to container component {}. ", createdInstanceId,
+ updatedComponent.getName());
result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
}
return result;
@@ -1215,7 +1214,7 @@ public class ToscaOperationFacade {
boolean allowDeleted, boolean isUpdateCsar) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to add component instances to component {}", containerComponent.getUniqueId());
Either<GraphVertex, JanusGraphOperationStatus> metadataVertex = janusGraphDao
- .getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.ParseAll);
+ .getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.ParseAll);
if (metadataVertex.isRight()) {
JanusGraphOperationStatus status = metadataVertex.right().value();
if (status == JanusGraphOperationStatus.NOT_FOUND) {
@@ -1224,33 +1223,33 @@ public class ToscaOperationFacade {
throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
Map<String, ComponentInstanceDataDefinition> compnentInstancesMap = nodeTemplateOperation
- .associateComponentInstancesToComponent(containerComponent, resourcesInstancesMap, metadataVertex.left().value(), allowDeleted,
- isUpdateCsar);
+ .associateComponentInstancesToComponent(containerComponent, resourcesInstancesMap, metadataVertex.left().value(), allowDeleted,
+ isUpdateCsar);
containerComponent.setComponentInstances(ModelConverter.getComponentInstancesFromMapObject(compnentInstancesMap, containerComponent));
}
public Either<ImmutablePair<Component, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(
- Component containerComponent, Component origComponent, ComponentInstance componentInstance) {
+ Component containerComponent, Component origComponent, ComponentInstance componentInstance) {
Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE,
- "Going to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(),
- containerComponent.getName());
+ "Going to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(),
+ containerComponent.getName());
componentInstance.setIcon(origComponent.getIcon());
Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation
- .updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
- ModelConverter.convertToToscaElement(origComponent), componentInstance);
+ .updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
+ ModelConverter.convertToToscaElement(origComponent), componentInstance);
if (updateResult.isRight()) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
- "Failed to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(),
- containerComponent.getName());
+ "Failed to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(),
+ containerComponent.getName());
result = Either.right(updateResult.right().value());
}
if (result == null) {
Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
String createdInstanceId = updateResult.left().value().getRight();
CommonUtility
- .addRecordToLog(log, LogLevelEnum.TRACE, "The metadata of the component instance {} has been updated to container component {}. ",
- createdInstanceId, updatedComponent.getName());
+ .addRecordToLog(log, LogLevelEnum.TRACE, "The metadata of the component instance {} has been updated to container component {}. ",
+ createdInstanceId, updatedComponent.getName());
result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
}
return result;
@@ -1264,18 +1263,18 @@ public class ToscaOperationFacade {
ComponentParametersView filter) {
Either<Component, StorageOperationStatus> result = null;
CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata belonging to container component {}. ",
- containerComponent.getName());
+ containerComponent.getName());
Either<TopologyTemplate, StorageOperationStatus> updateResult = nodeTemplateOperation
- .updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), filter);
+ .updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), filter);
if (updateResult.isRight()) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata belonging to container component {}. ",
- containerComponent.getName());
+ containerComponent.getName());
result = Either.right(updateResult.right().value());
}
if (result == null) {
Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value());
CommonUtility
- .addRecordToLog(log, LogLevelEnum.TRACE, "The metadata has been updated to container component {}. ", updatedComponent.getName());
+ .addRecordToLog(log, LogLevelEnum.TRACE, "The metadata has been updated to container component {}. ", updatedComponent.getName());
result = Either.left(updatedComponent);
}
return result;
@@ -1286,19 +1285,19 @@ public class ToscaOperationFacade {
String resourceInstanceId) {
Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to delete the component instance {} belonging to container component {}. ",
- resourceInstanceId, containerComponent.getName());
+ resourceInstanceId, containerComponent.getName());
Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation
- .deleteComponentInstanceFromTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), resourceInstanceId);
+ .deleteComponentInstanceFromTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), resourceInstanceId);
if (updateResult.isRight()) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete the component instance {} belonging to container component {}. ",
- resourceInstanceId, containerComponent.getName());
+ resourceInstanceId, containerComponent.getName());
result = Either.right(updateResult.right().value());
}
if (result == null) {
Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
String deletedInstanceId = updateResult.left().value().getRight();
CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been deleted from container component {}. ",
- deletedInstanceId, updatedComponent.getName());
+ deletedInstanceId, updatedComponent.getName());
result = Either.left(new ImmutablePair<>(updatedComponent, deletedInstanceId));
}
return result;
@@ -1321,11 +1320,11 @@ public class ToscaOperationFacade {
*/
private Integer getMaxCounterFromNamesAndIds(Component containerComponent, String normalizedName) {
List<String> countersInNames = containerComponent.getComponentInstances().stream()
- .filter(ci -> ci.getNormalizedName() != null && ci.getNormalizedName().startsWith(normalizedName))
- .map(ci -> ci.getNormalizedName().split(normalizedName)[1]).collect(Collectors.toList());
+ .filter(ci -> ci.getNormalizedName() != null && ci.getNormalizedName().startsWith(normalizedName))
+ .map(ci -> ci.getNormalizedName().split(normalizedName)[1]).collect(Collectors.toList());
List<String> countersInIds = containerComponent.getComponentInstances().stream()
- .filter(ci -> ci.getUniqueId() != null && ci.getUniqueId().contains(normalizedName)).map(ci -> ci.getUniqueId().split(normalizedName)[1])
- .collect(Collectors.toList());
+ .filter(ci -> ci.getUniqueId() != null && ci.getUniqueId().contains(normalizedName)).map(ci -> ci.getUniqueId().split(normalizedName)[1])
+ .collect(Collectors.toList());
List<String> namesAndIdsList = new ArrayList<>(countersInNames);
namesAndIdsList.addAll(countersInIds);
return getMaxInteger(namesAndIdsList);
@@ -1360,7 +1359,7 @@ public class ToscaOperationFacade {
}
GraphVertex vertex = getVertexEither.left().value();
Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream()
- .collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
+ .collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
StorageOperationStatus status = topologyTemplateOperation.associateInputsToComponent(vertex, inputsMap, componentId);
if (StorageOperationStatus.OK == status) {
log.debug(COMPONENT_CREATED_SUCCESSFULLY);
@@ -1381,9 +1380,9 @@ public class ToscaOperationFacade {
}
GraphVertex vertex = getVertexEither.left().value();
Map<String, PropertyDefinition> inputsMap = inputs.entrySet().stream()
- .collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDefinition(e.getValue())));
+ .collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDefinition(e.getValue())));
StorageOperationStatus status = topologyTemplateOperation
- .addToscaDataToToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsMap, JsonPresentationFields.NAME);
+ .addToscaDataToToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsMap, JsonPresentationFields.NAME);
if (StorageOperationStatus.OK == status) {
log.debug(COMPONENT_CREATED_SUCCESSFULLY);
List<InputDefinition> inputsResList = null;
@@ -1403,9 +1402,9 @@ public class ToscaOperationFacade {
}
GraphVertex vertex = getVertexEither.left().value();
Map<String, AttributeDefinition> outputsMap = outputs.entrySet().stream()
- .collect(Collectors.toMap(Map.Entry::getKey, e -> new AttributeDefinition(e.getValue())));
+ .collect(Collectors.toMap(Map.Entry::getKey, e -> new AttributeDefinition(e.getValue())));
StorageOperationStatus status = topologyTemplateOperation
- .addToscaDataToToscaElement(vertex, EdgeLabelEnum.OUTPUTS, VertexTypeEnum.OUTPUTS, outputsMap, JsonPresentationFields.NAME);
+ .addToscaDataToToscaElement(vertex, EdgeLabelEnum.OUTPUTS, VertexTypeEnum.OUTPUTS, outputsMap, JsonPresentationFields.NAME);
if (StorageOperationStatus.OK == status) {
log.debug(COMPONENT_CREATED_SUCCESSFULLY);
List<OutputDefinition> outputsResList = null;
@@ -1429,7 +1428,7 @@ public class ToscaOperationFacade {
log.trace("#addDataTypesToComponent - enter, componentId={}", componentId);
/* get component vertex */
Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
- .getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ .getVertexById(componentId, JsonParseFlagEnum.NoParse);
if (getVertexEither.isRight()) {
/* not found / error */
log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
@@ -1439,12 +1438,12 @@ public class ToscaOperationFacade {
log.trace("#addDataTypesToComponent - get vertex ok");
// convert DataTypeDefinition to DataTypeDataDefinition
Map<String, DataTypeDataDefinition> dataTypeDataMap = dataTypes.entrySet().stream()
- .collect(Collectors.toMap(Map.Entry::getKey, e -> convertDataTypeToDataTypeData(e.getValue())));
+ .collect(Collectors.toMap(Map.Entry::getKey, e -> convertDataTypeToDataTypeData(e.getValue())));
// add datatype(s) to the Component.
// if child vertex does not exist, it will be created.
StorageOperationStatus status = topologyTemplateOperation
- .addToscaDataToToscaElement(vertex, EdgeLabelEnum.DATA_TYPES, VertexTypeEnum.DATA_TYPES, dataTypeDataMap, JsonPresentationFields.NAME);
+ .addToscaDataToToscaElement(vertex, EdgeLabelEnum.DATA_TYPES, VertexTypeEnum.DATA_TYPES, dataTypeDataMap, JsonPresentationFields.NAME);
if (StorageOperationStatus.OK == status) {
log.debug(COMPONENT_CREATED_SUCCESSFULLY);
List<DataTypeDefinition> inputsResList = null;
@@ -1461,7 +1460,7 @@ public class ToscaOperationFacade {
DataTypeDataDefinition dataTypeData = new DataTypeDataDefinition(dataType);
if (CollectionUtils.isNotEmpty(dataType.getProperties())) {
List<PropertyDataDefinition> propertyDataList = dataType.getProperties().stream().map(PropertyDataDefinition::new)
- .collect(Collectors.toList());
+ .collect(Collectors.toList());
dataTypeData.setPropertiesData(propertyDataList);
}
// if "derivedFrom" data_type exists, copy the name to "derivedFromName"
@@ -1469,7 +1468,7 @@ public class ToscaOperationFacade {
// if names are different, log it
if (!StringUtils.equals(dataTypeData.getDerivedFromName(), dataType.getDerivedFrom().getName())) {
log.debug("#convertDataTypeToDataTypeData - derivedFromName(={}) overwritten by derivedFrom.name(={})", dataType.getDerivedFromName(),
- dataType.getDerivedFrom().getName());
+ dataType.getDerivedFrom().getName());
}
dataTypeData.setDerivedFromName(dataType.getDerivedFrom().getName());
}
@@ -1506,7 +1505,7 @@ public class ToscaOperationFacade {
GraphVertex vertex = getVertexEither.left().value();
List<PropertyDataDefinition> inputsAsDataDef = inputs.stream().map(PropertyDataDefinition::new).collect(Collectors.toList());
StorageOperationStatus status = topologyTemplateOperation
- .updateToscaDataOfToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsAsDataDef, JsonPresentationFields.NAME);
+ .updateToscaDataOfToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsAsDataDef, JsonPresentationFields.NAME);
if (StorageOperationStatus.OK == status) {
log.debug(COMPONENT_CREATED_SUCCESSFULLY);
List<InputDefinition> inputsResList = null;
@@ -1520,7 +1519,7 @@ public class ToscaOperationFacade {
// region - ComponentInstance
public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> associateComponentInstancePropertiesToComponent(
- Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
+ Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
if (getVertexEither.isRight()) {
log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
@@ -1533,7 +1532,7 @@ public class ToscaOperationFacade {
for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
propertiesMap = new MapPropertiesDataDefinition();
propertiesMap.setMapToscaDataDefinition(
- entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e)));
+ entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e)));
instPropsMap.put(entry.getKey(), propertiesMap);
}
}
@@ -1549,7 +1548,7 @@ public class ToscaOperationFacade {
* saves the instInputs as the updated instance inputs of the component container in DB
*/
public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> updateComponentInstanceInputsToComponent(
- Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
+ Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
if (instInputs == null || instInputs.isEmpty()) {
return Either.left(instInputs);
}
@@ -1559,11 +1558,11 @@ public class ToscaOperationFacade {
List<String> pathKeysPerInst = new ArrayList<>();
pathKeysPerInst.add(inputsPerIntance.getKey());
status = topologyTemplateOperation
- .updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, toscaDataListPerInst,
- pathKeysPerInst, JsonPresentationFields.NAME);
+ .updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, toscaDataListPerInst,
+ pathKeysPerInst, JsonPresentationFields.NAME);
if (status != StorageOperationStatus.OK) {
log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}",
- inputsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_INPUTS, status);
+ inputsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_INPUTS, status);
return Either.right(status);
}
}
@@ -1574,7 +1573,7 @@ public class ToscaOperationFacade {
* saves the instProps as the updated instance properties of the component container in DB
*/
public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> updateComponentInstancePropsToComponent(
- Map<String, List<ComponentInstanceProperty>> instProps, String componentId) {
+ Map<String, List<ComponentInstanceProperty>> instProps, String componentId) {
if (instProps == null || instProps.isEmpty()) {
return Either.left(instProps);
}
@@ -1584,11 +1583,11 @@ public class ToscaOperationFacade {
List<String> pathKeysPerInst = new ArrayList<>();
pathKeysPerInst.add(propsPerIntance.getKey());
status = topologyTemplateOperation
- .updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES,
- toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME);
+ .updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES,
+ toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME);
if (status != StorageOperationStatus.OK) {
log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}",
- propsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_PROPERTIES, status);
+ propsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_PROPERTIES, status);
return Either.right(status);
}
}
@@ -1596,7 +1595,7 @@ public class ToscaOperationFacade {
}
public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> associateComponentInstanceInputsToComponent(
- Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
+ Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
if (getVertexEither.isRight()) {
log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
@@ -1609,7 +1608,7 @@ public class ToscaOperationFacade {
for (Entry<String, List<ComponentInstanceInput>> entry : instInputs.entrySet()) {
propertiesMap = new MapPropertiesDataDefinition();
propertiesMap.setMapToscaDataDefinition(
- entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e)));
+ entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e)));
instPropsMap.put(entry.getKey(), propertiesMap);
}
}
@@ -1622,7 +1621,7 @@ public class ToscaOperationFacade {
}
public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addComponentInstanceInputsToComponent(
- Component containerComponent, Map<String, List<ComponentInstanceInput>> instProperties) {
+ Component containerComponent, Map<String, List<ComponentInstanceInput>> instProperties) {
requireNonNull(instProperties);
StorageOperationStatus status;
for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) {
@@ -1632,7 +1631,7 @@ public class ToscaOperationFacade {
for (ComponentInstanceInput property : props) {
List<ComponentInstanceInput> componentInstancesInputs = containerComponent.getComponentInstancesInputs().get(componentInstanceId);
Optional<ComponentInstanceInput> instanceProperty = componentInstancesInputs.stream()
- .filter(p -> p.getName().equals(property.getName())).findAny();
+ .filter(p -> p.getName().equals(property.getName())).findAny();
if (instanceProperty.isPresent()) {
status = updateComponentInstanceInput(containerComponent, componentInstanceId, property);
} else {
@@ -1651,7 +1650,7 @@ public class ToscaOperationFacade {
}
public Either<Map<String, List<ComponentInstanceOutput>>, StorageOperationStatus> addComponentInstanceOutputsToComponent(
- Component containerComponent, Map<String, List<ComponentInstanceOutput>> instProperties) {
+ Component containerComponent, Map<String, List<ComponentInstanceOutput>> instProperties) {
requireNonNull(instProperties);
StorageOperationStatus status;
for (final Entry<String, List<ComponentInstanceOutput>> entry : instProperties.entrySet()) {
@@ -1660,9 +1659,9 @@ public class ToscaOperationFacade {
if (!isEmpty(props)) {
for (final ComponentInstanceOutput property : props) {
final List<ComponentInstanceOutput> componentInstancesInputs = containerComponent.getComponentInstancesOutputs()
- .get(componentInstanceId);
+ .get(componentInstanceId);
final Optional<ComponentInstanceOutput> instanceProperty = componentInstancesInputs.stream()
- .filter(p -> p.getName().equals(property.getName())).findAny();
+ .filter(p -> p.getName().equals(property.getName())).findAny();
if (instanceProperty.isPresent()) {
status = updateComponentInstanceOutput(containerComponent, componentInstanceId, property);
} else {
@@ -1681,13 +1680,13 @@ public class ToscaOperationFacade {
}
public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addComponentInstancePropertiesToComponent(
- Component containerComponent, Map<String, List<ComponentInstanceProperty>> instProperties) {
+ Component containerComponent, Map<String, List<ComponentInstanceProperty>> instProperties) {
requireNonNull(instProperties);
for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
List<ComponentInstanceProperty> props = entry.getValue();
String componentInstanceId = entry.getKey();
List<ComponentInstanceProperty> originalComponentInstProps = containerComponent.getComponentInstancesProperties()
- .get(componentInstanceId);
+ .get(componentInstanceId);
Map<String, List<CapabilityDefinition>> containerComponentCapabilities = containerComponent.getCapabilities();
if (isEmpty(props)) {
continue;
@@ -1698,7 +1697,7 @@ public class ToscaOperationFacade {
Optional<CapabilityDefinition> capPropDefinition = getPropertyCapability(propertyParentUniqueId, containerComponent);
if (capPropDefinition.isPresent() && MapUtils.isNotEmpty(containerComponentCapabilities)) {
status = populateAndUpdateInstanceCapProperty(containerComponent, componentInstanceId, containerComponentCapabilities, property,
- capPropDefinition.get());
+ capPropDefinition.get());
}
if (status == null) {
status = updateOrAddComponentInstanceProperty(containerComponent, componentInstanceId, originalComponentInstProps, property);
@@ -1712,7 +1711,7 @@ public class ToscaOperationFacade {
}
public Either<Map<String, List<ComponentInstanceAttribute>>, StorageOperationStatus> addComponentInstanceAttributesToComponent(
- final Component containerComponent, final Map<String, List<ComponentInstanceAttribute>> instProperties) {
+ final Component containerComponent, final Map<String, List<ComponentInstanceAttribute>> instProperties) {
requireNonNull(instProperties);
for (final Entry<String, List<ComponentInstanceAttribute>> entry : instProperties.entrySet()) {
final List<ComponentInstanceAttribute> props = entry.getValue();
@@ -1721,10 +1720,10 @@ public class ToscaOperationFacade {
}
final String componentInstanceId = entry.getKey();
final List<ComponentInstanceAttribute> originalComponentInstProps = containerComponent.getComponentInstancesAttributes()
- .get(componentInstanceId);
+ .get(componentInstanceId);
for (final ComponentInstanceAttribute property : props) {
final StorageOperationStatus status = updateOrAddComponentInstanceAttribute(containerComponent, componentInstanceId,
- originalComponentInstProps, property);
+ originalComponentInstProps, property);
if (status != StorageOperationStatus.OK) {
return Either.right(status);
}
@@ -1742,7 +1741,7 @@ public class ToscaOperationFacade {
return null;
}
Optional<CapabilityDefinition> capDefToGetProp = capabilityDefinitions.stream()
- .filter(cap -> cap.getUniqueId().equals(capabilityDefinition.getUniqueId()) && cap.getPath().size() == 1).findAny();
+ .filter(cap -> cap.getUniqueId().equals(capabilityDefinition.getUniqueId()) && cap.getPath().size() == 1).findAny();
if (capDefToGetProp.isPresent()) {
return updateInstanceCapabilityProperty(containerComponent, componentInstanceId, property, capDefToGetProp.get());
}
@@ -1755,7 +1754,7 @@ public class ToscaOperationFacade {
StorageOperationStatus status;
// check if the property already exists or not
Optional<ComponentInstanceProperty> instanceProperty = originalComponentInstProps.stream()
- .filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
+ .filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
if (instanceProperty.isPresent()) {
status = updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
} else {
@@ -1773,7 +1772,7 @@ public class ToscaOperationFacade {
StorageOperationStatus status;
// check if the property already exists or not
Optional<ComponentInstanceAttribute> instanceProperty = originalComponentInstProps.stream()
- .filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
+ .filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
if (instanceProperty.isPresent()) {
status = updateComponentInstanceAttribute(containerComponent, componentInstanceId, property);
} else {
@@ -1805,7 +1804,7 @@ public class ToscaOperationFacade {
StorageOperationStatus status;
StringBuilder sb = new StringBuilder(componentInstanceId);
sb.append(ModelConverter.CAP_PROP_DELIM).append(propOwner).append(ModelConverter.CAP_PROP_DELIM).append(capabilityDefinition.getType())
- .append(ModelConverter.CAP_PROP_DELIM).append(capabilityDefinition.getName());
+ .append(ModelConverter.CAP_PROP_DELIM).append(capabilityDefinition.getName());
String capKey = sb.toString();
status = updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceId, capKey, property);
if (status != StorageOperationStatus.OK) {
@@ -1836,7 +1835,7 @@ public class ToscaOperationFacade {
GraphVertex vertex = getVertexEither.left().value();
if (MapUtils.isNotEmpty(capabilities)) {
Either<GraphVertex, StorageOperationStatus> associateElementToData = topologyTemplateOperation
- .associateElementToData(vertex, VertexTypeEnum.CAPABILITIES, EdgeLabelEnum.CAPABILITIES, capabilities);
+ .associateElementToData(vertex, VertexTypeEnum.CAPABILITIES, EdgeLabelEnum.CAPABILITIES, capabilities);
if (associateElementToData.isRight()) {
return associateElementToData.right().value();
}
@@ -1853,7 +1852,7 @@ public class ToscaOperationFacade {
GraphVertex vertex = getVertexEither.left().value();
if (MapUtils.isNotEmpty(requirements)) {
Either<GraphVertex, StorageOperationStatus> associateElementToData = topologyTemplateOperation
- .associateElementToData(vertex, VertexTypeEnum.REQUIREMENTS, EdgeLabelEnum.REQUIREMENTS, requirements);
+ .associateElementToData(vertex, VertexTypeEnum.REQUIREMENTS, EdgeLabelEnum.REQUIREMENTS, requirements);
if (associateElementToData.isRight()) {
return associateElementToData.right().value();
}
@@ -1864,7 +1863,7 @@ public class ToscaOperationFacade {
public StorageOperationStatus associateDeploymentArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
Component component, User user) {
Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
- .getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
+ .getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
if (getVertexEither.isRight()) {
log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
@@ -1876,9 +1875,9 @@ public class ToscaOperationFacade {
for (Entry<String, Map<String, ArtifactDefinition>> entry : instDeploymentArtifacts.entrySet()) {
Map<String, ArtifactDefinition> artList = entry.getValue();
Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream()
- .collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
+ .collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
artifactsMap = nodeTemplateOperation
- .prepareInstDeploymentArtifactPerInstance(artifacts, entry.getKey(), user, NodeTemplateOperation.HEAT_VF_ENV_NAME);
+ .prepareInstDeploymentArtifactPerInstance(artifacts, entry.getKey(), user, NodeTemplateOperation.HEAT_VF_ENV_NAME);
instArtMap.put(entry.getKey(), artifactsMap);
}
}
@@ -1888,7 +1887,7 @@ public class ToscaOperationFacade {
public StorageOperationStatus associateArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instArtifacts, Component component) {
Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
- .getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
+ .getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
if (getVertexEither.isRight()) {
log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
@@ -1900,7 +1899,7 @@ public class ToscaOperationFacade {
for (Entry<String, Map<String, ArtifactDefinition>> entry : instArtifacts.entrySet()) {
Map<String, ArtifactDefinition> artList = entry.getValue();
Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream()
- .collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
+ .collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
artifactsMap = new MapArtifactDataDefinition(artifacts);
instArtMap.put(entry.getKey(), artifactsMap);
}
@@ -1912,7 +1911,7 @@ public class ToscaOperationFacade {
public StorageOperationStatus associateInstAttributeToComponentToInstances(Map<String, List<AttributeDefinition>> instArttributes,
Component component) {
Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
- .getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
+ .getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
if (getVertexEither.isRight()) {
log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
@@ -1925,7 +1924,7 @@ public class ToscaOperationFacade {
final List<AttributeDefinition> value = entry.getValue();
attributesMap = new MapAttributesDataDefinition();
attributesMap.setMapToscaDataDefinition(
- value.stream().map(AttributeDefinition::new).collect(Collectors.toMap(AttributeDefinition::getName, e -> e)));
+ value.stream().map(AttributeDefinition::new).collect(Collectors.toMap(AttributeDefinition::getName, e -> e)));
instAttr.put(entry.getKey(), attributesMap);
}
}
@@ -1947,7 +1946,7 @@ public class ToscaOperationFacade {
Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg,
Component component) {
Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
- .getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
+ .getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
if (getVertexEither.isRight()) {
log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
@@ -1962,13 +1961,13 @@ public class ToscaOperationFacade {
Map<String, ListCapabilityDataDefinition> mapToscaDataDefinition = new HashMap<>();
for (Entry<String, List<CapabilityDefinition>> instCapability : caps.entrySet()) {
mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(
- instCapability.getValue().stream().map(CapabilityDataDefinition::new).collect(Collectors.toList())));
+ instCapability.getValue().stream().map(CapabilityDataDefinition::new).collect(Collectors.toList())));
}
ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(entry.getKey());
MapListCapabilityDataDefinition capMap = nodeTemplateOperation
- .prepareCalculatedCapabiltyForNodeType(mapToscaDataDefinition, componentInstance);
+ .prepareCalculatedCapabiltyForNodeType(mapToscaDataDefinition, componentInstance);
MapCapabilityProperty mapCapabilityProperty = ModelConverter
- .convertToMapOfMapCapabiltyProperties(caps, componentInstance.getUniqueId(), true);
+ .convertToMapOfMapCapabiltyProperties(caps, componentInstance.getUniqueId(), true);
calcCapabilty.put(entry.getKey().getUniqueId(), capMap);
calculatedCapabilitiesProperties.put(entry.getKey().getUniqueId(), mapCapabilityProperty);
}
@@ -1979,24 +1978,24 @@ public class ToscaOperationFacade {
Map<String, ListRequirementDataDefinition> mapToscaDataDefinition = new HashMap<>();
for (Entry<String, List<RequirementDefinition>> instReq : req.entrySet()) {
mapToscaDataDefinition.put(instReq.getKey(), new ListRequirementDataDefinition(
- instReq.getValue().stream().map(RequirementDataDefinition::new).collect(Collectors.toList())));
+ instReq.getValue().stream().map(RequirementDataDefinition::new).collect(Collectors.toList())));
}
MapListRequirementDataDefinition reqMap = nodeTemplateOperation
- .prepareCalculatedRequirementForNodeType(mapToscaDataDefinition, new ComponentInstanceDataDefinition(entry.getKey()));
+ .prepareCalculatedRequirementForNodeType(mapToscaDataDefinition, new ComponentInstanceDataDefinition(entry.getKey()));
String componentInstanceId = entry.getKey().getUniqueId();
calcRequirements.put(componentInstanceId, reqMap);
}
}
StorageOperationStatus storageOperationStatus = topologyTemplateOperation
- .associateOrAddCalcCapReqToComponent(vertex, calcRequirements, calcCapabilty, calculatedCapabilitiesProperties);
+ .associateOrAddCalcCapReqToComponent(vertex, calcRequirements, calcCapabilty, calculatedCapabilitiesProperties);
updateInstancesCapAndReqOnComponentFromDB(component);
return storageOperationStatus;
}
public StorageOperationStatus updateCalculatedCapabilitiesRequirements(
- final Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
- final Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg,
- final Component component) {
+ final Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
+ final Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg,
+ final Component component) {
StorageOperationStatus storageOperationStatus = StorageOperationStatus.OK;
if (instCapabilties != null) {
for (Entry<ComponentInstance, Map<String, List<CapabilityDefinition>>> entry : instCapabilties.entrySet()) {
@@ -2014,7 +2013,7 @@ public class ToscaOperationFacade {
for (List<RequirementDefinition> requirementList : req.values()) {
for (RequirementDefinition requirement : requirementList) {
storageOperationStatus = nodeTemplateOperation.updateComponentInstanceRequirement(component.getUniqueId(),
- entry.getKey().getUniqueId(), requirement);
+ entry.getKey().getUniqueId(), requirement);
if (storageOperationStatus != StorageOperationStatus.OK) {
return storageOperationStatus;
}
@@ -2071,14 +2070,14 @@ public class ToscaOperationFacade {
Map<GraphPropertyEnum, Object> hasNotProps = new EnumMap<>(GraphPropertyEnum.class);
fillPropsMap(hasProps, hasNotProps, internalComponentType, componentTypeEnum, isAbstract, vertexType, modelName);
Either<List<GraphVertex>, JanusGraphOperationStatus> getRes = janusGraphDao
- .getByCriteria(vertexType, hasProps, hasNotProps, JsonParseFlagEnum.ParseMetadata, modelName, includeNormativeExtensionModels);
+ .getByCriteria(vertexType, hasProps, hasNotProps, JsonParseFlagEnum.ParseMetadata, modelName, includeNormativeExtensionModels);
if (getRes.isRight() && !JanusGraphOperationStatus.NOT_FOUND.equals(getRes.right().value())) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value()));
}
// region -> Fetch non checked-out services
if (internalComponentType != null && internalComponentType.toLowerCase().trim().equals(SERVICE) && VertexTypeEnum.NODE_TYPE == vertexType) {
Either<List<Service>, StorageOperationStatus> result = getLatestVersionNonCheckoutServicesMetadataOnly(
- new EnumMap<>(GraphPropertyEnum.class), new EnumMap<>(GraphPropertyEnum.class), modelName);
+ new EnumMap<>(GraphPropertyEnum.class), new EnumMap<>(GraphPropertyEnum.class), modelName);
if (result.isRight()) {
log.debug("Failed to fetch services for");
return Either.right(result.right().value());
@@ -2095,7 +2094,7 @@ public class ToscaOperationFacade {
if (getRes.isLeft()) {
for (GraphVertex vertexComponent : getRes.left().value()) {
Either<ToscaElement, StorageOperationStatus> componentRes = topologyTemplateOperation
- .getLightComponent(vertexComponent, componentTypeEnum, params);
+ .getLightComponent(vertexComponent, componentTypeEnum, params);
if (componentRes.isRight()) {
log.debug("Failed to fetch light element for {} error {}", vertexComponent.getUniqueId(), componentRes.right().value());
return Either.right(componentRes.right().value());
@@ -2123,15 +2122,15 @@ public class ToscaOperationFacade {
propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
propertiesNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683
Either<List<GraphVertex>, JanusGraphOperationStatus> getRes = janusGraphDao
- .getByCriteria(null, hasProperties, propertiesNotToMatch, parseFlag);
+ .getByCriteria(null, hasProperties, propertiesNotToMatch, parseFlag);
if (getRes.isRight()) {
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value()));
} else {
List<ComponentMetadataData> latestVersionList = getRes.left().value().stream().map(ModelConverter::convertToComponentMetadata)
- .collect(Collectors.toList());
+ .collect(Collectors.toList());
ComponentMetadataData latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0) : latestVersionList.stream().max(
- (c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()),
- Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get();
+ (c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()),
+ Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get();
result = Either.left(latestVersion);
}
return result;
@@ -2169,7 +2168,7 @@ public class ToscaOperationFacade {
componentParametersView.setIgnoreRequirements(false);
}
Either<ToscaElement, StorageOperationStatus> getToscaElementRes = nodeTemplateOperation.getToscaElementOperation(componentTypeEnum)
- .getLightComponent(componentUid, componentTypeEnum, componentParametersView);
+ .getLightComponent(componentUid, componentTypeEnum, componentParametersView);
if (getToscaElementRes.isRight()) {
log.debug("Failed to fetch resource for error is {}", getToscaElementRes.right().value());
return Either.right(getToscaElementRes.right().value());
@@ -2196,7 +2195,7 @@ public class ToscaOperationFacade {
private Either<List<String>, StorageOperationStatus> getComponentUids(boolean isAbstract, ComponentTypeEnum componentTypeEnum,
String internalComponentType) {
Either<List<Component>, StorageOperationStatus> getToscaElementsRes = getLatestVersionNotAbstractMetadataOnly(isAbstract, componentTypeEnum,
- internalComponentType, null, false);
+ internalComponentType, null, false);
if (getToscaElementsRes.isRight()) {
return Either.right(getToscaElementsRes.right().value());
}
@@ -2231,7 +2230,7 @@ public class ToscaOperationFacade {
ComponentTypeEnum componentType) {
String normalizedName = ValidationUtils.normaliseComponentName(name);
Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
- .getByCriteria(getVertexTypeEnum(resourceType), propertiesToMatch(normalizedName, componentType), JsonParseFlagEnum.NoParse);
+ .getByCriteria(getVertexTypeEnum(resourceType), propertiesToMatch(normalizedName, componentType), JsonParseFlagEnum.NoParse);
if (vertexEither.isRight() && vertexEither.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
log.debug("failed to get vertex from graph with property normalizedName: {}", normalizedName);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
@@ -2254,14 +2253,14 @@ public class ToscaOperationFacade {
final ComponentTypeEnum componentType) {
final String normalizedName = ValidationUtils.normaliseComponentName(resourceName);
final Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
- .getByCriteria(getVertexTypeEnum(resourceType), propertiesToMatch(normalizedName, componentType), null, null, JsonParseFlagEnum.NoParse,
- modelName);
+ .getByCriteria(getVertexTypeEnum(resourceType), propertiesToMatch(normalizedName, componentType), null, null, JsonParseFlagEnum.NoParse,
+ modelName);
if (vertexEither.isRight() && vertexEither.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
log.debug("failed to get vertex from graph with property normalizedName: {} and model: {}", normalizedName, modelName);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
}
return Either.left(CollectionUtils.isEmpty(vertexEither.isLeft() ? vertexEither.left().value().stream()
- .collect(Collectors.toList()) : null));
+ .collect(Collectors.toList()) : null));
}
private VertexTypeEnum getVertexTypeEnum(final ResourceTypeEnum resourceType) {
@@ -2336,7 +2335,7 @@ public class ToscaOperationFacade {
internalVertexTypes.add(VertexTypeEnum.NODE_TYPE);
}
if (ComponentTypeEnum.SERVICE == componentTypeEnum || SERVICE.equalsIgnoreCase(internalComponentType) || VF.equalsIgnoreCase(
- internalComponentType)) {
+ internalComponentType)) {
internalVertexTypes.add(VertexTypeEnum.TOPOLOGY_TEMPLATE);
}
return internalVertexTypes;
@@ -2351,7 +2350,7 @@ public class ToscaOperationFacade {
List<Component> result = new ArrayList<>();
for (VertexTypeEnum vertexType : internalVertexTypes) {
Either<List<Component>, StorageOperationStatus> listByVertexType = getLatestVersionNotAbstractToscaElementsMetadataOnly(isAbstract,
- componentTypeEnum, internalComponentType, vertexType, modelName, includeNormativeExtensionModels);
+ componentTypeEnum, internalComponentType, vertexType, modelName, includeNormativeExtensionModels);
if (listByVertexType.isRight()) {
return listByVertexType;
}
@@ -2377,7 +2376,7 @@ public class ToscaOperationFacade {
Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
- .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
+ .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
if (vertexEither.isRight()) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
}
@@ -2399,7 +2398,7 @@ public class ToscaOperationFacade {
propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
propertiesNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683
Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
- .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
+ .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
if (vertexEither.isRight()) {
log.debug("Couldn't fetch metadata for component with uuid {}, error: {}", componentUuid, vertexEither.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
@@ -2451,7 +2450,7 @@ public class ToscaOperationFacade {
return Either.right(StorageOperationStatus.NOT_FOUND);
}
Component component = latestVersionList.size() == 1 ? latestVersionList.get(0)
- : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getVersion()), Double.parseDouble(c2.getVersion())))
+ : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getVersion()), Double.parseDouble(c2.getVersion())))
.get();
return Either.left(component);
}
@@ -2468,7 +2467,7 @@ public class ToscaOperationFacade {
propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
Either<List<GraphVertex>, JanusGraphOperationStatus> getResourcesRes = janusGraphDao
- .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
+ .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
if (getResourcesRes.isRight()) {
log.debug("Failed to fetch all certified resources. Status is {}", getResourcesRes.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getResourcesRes.right().value()));
@@ -2494,7 +2493,7 @@ public class ToscaOperationFacade {
hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
Either<List<GraphVertex>, JanusGraphOperationStatus> getResourceRes = janusGraphDao
- .getByCriteria(null, hasProperties, hasNotProperties, parseFlag, model);
+ .getByCriteria(null, hasProperties, hasNotProperties, parseFlag, model);
if (getResourceRes.isRight()) {
JanusGraphOperationStatus status = getResourceRes.right().value();
log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
@@ -2522,7 +2521,7 @@ public class ToscaOperationFacade {
GraphVertex resourceMetadataData = null;
List<GraphVertex> resourceMetadataDataList = null;
Either<List<GraphVertex>, JanusGraphOperationStatus> byCsar = janusGraphDao
- .getByCriteria(null, props, propsHasNot, JsonParseFlagEnum.ParseMetadata);
+ .getByCriteria(null, props, propsHasNot, JsonParseFlagEnum.ParseMetadata);
if (byCsar.isRight()) {
if (JanusGraphOperationStatus.NOT_FOUND == byCsar.right().value()) {
// Fix Defect DE256036
@@ -2533,16 +2532,16 @@ public class ToscaOperationFacade {
props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
props.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
Either<List<GraphVertex>, JanusGraphOperationStatus> bySystemname = janusGraphDao
- .getByCriteria(null, props, JsonParseFlagEnum.ParseMetadata);
+ .getByCriteria(null, props, JsonParseFlagEnum.ParseMetadata);
if (bySystemname.isRight()) {
log.debug("getLatestResourceByCsarOrName - Failed to find by system name {} error {} ", systemName,
- bySystemname.right().value());
+ bySystemname.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(bySystemname.right().value()));
}
if (bySystemname.left().value().size() > 2) {
log.debug(
- "getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}",
- bySystemname.left().value().size());
+ "getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}",
+ bySystemname.left().value().size());
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
resourceMetadataDataList = bySystemname.left().value();
@@ -2563,7 +2562,7 @@ public class ToscaOperationFacade {
final Object csarUuid = resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID);
if (csarUuid != null && !csarUuid.equals(csarUUID)) {
log.debug("getLatestResourceByCsarOrName - same system name {} but different csarUUID. exist {} and new {} ", systemName,
- csarUuid, csarUUID);
+ csarUuid, csarUUID);
// correct error will be returned from create flow. with all
// correct audit records!!!!!
@@ -2575,7 +2574,7 @@ public class ToscaOperationFacade {
resourceMetadataDataList = byCsar.left().value();
if (resourceMetadataDataList.size() > 2) {
log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) must return only 2 latest version, but was returned - {}",
- byCsar.left().value().size());
+ byCsar.left().value().size());
return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
if (resourceMetadataDataList.size() == 1) {
@@ -2604,7 +2603,7 @@ public class ToscaOperationFacade {
Either<Resource, StorageOperationStatus> latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked, model);
if (latestByToscaResourceName.isRight()) {
return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false)
- : Either.right(latestByToscaResourceName.right().value());
+ : Either.right(latestByToscaResourceName.right().value());
}
Resource value = latestByToscaResourceName.left().value();
if (value.getDerivedFrom() != null) {
@@ -2614,7 +2613,7 @@ public class ToscaOperationFacade {
}
}
return (currentTemplateNameChecked != null && currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) ? Either.left(true)
- : Either.left(false);
+ : Either.left(false);
}
public Either<List<Component>, StorageOperationStatus> fetchMetaDataByResourceType(String resourceType, ComponentParametersView filterBy) {
@@ -2624,7 +2623,7 @@ public class ToscaOperationFacade {
Map<GraphPropertyEnum, Object> propsHasNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
propsHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
Either<List<GraphVertex>, JanusGraphOperationStatus> resourcesByTypeEither = janusGraphDao
- .getByCriteria(null, props, propsHasNotToMatch, JsonParseFlagEnum.ParseMetadata);
+ .getByCriteria(null, props, propsHasNotToMatch, JsonParseFlagEnum.ParseMetadata);
if (resourcesByTypeEither.isRight()) {
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(resourcesByTypeEither.right().value()));
}
@@ -2642,7 +2641,7 @@ public class ToscaOperationFacade {
public Either<Service, StorageOperationStatus> updateDistributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) {
Either<GraphVertex, StorageOperationStatus> updateDistributionStatus = topologyTemplateOperation
- .updateDistributionStatus(service.getUniqueId(), user, distributionStatus);
+ .updateDistributionStatus(service.getUniqueId(), user, distributionStatus);
if (updateDistributionStatus.isRight()) {
return Either.right(updateDistributionStatus.right().value());
}
@@ -2702,7 +2701,7 @@ public class ToscaOperationFacade {
for (DistributionStatusEnum state : distStatus) {
propertiesToMatch.put(GraphPropertyEnum.DISTRIBUTION_STATUS, state.name());
Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria = fetchServicesByCriteria(servicesAll, propertiesToMatch,
- propertiesNotToMatch, null);
+ propertiesNotToMatch, null);
if (fetchServicesByCriteria.isRight()) {
return fetchServicesByCriteria;
} else {
@@ -2720,21 +2719,21 @@ public class ToscaOperationFacade {
Map<GraphPropertyEnum, Object> propertiesNotToMatch,
String modelName) {
Either<List<GraphVertex>, JanusGraphOperationStatus> getRes = janusGraphDao
- .getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll, modelName);
+ .getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll, modelName);
if (getRes.isRight()) {
if (getRes.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
- "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch,
- propertiesNotToMatch, getRes.right().value());
+ "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch,
+ propertiesNotToMatch, getRes.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value()));
}
} else {
for (final GraphVertex vertex : getRes.left().value()) {
Either<ToscaElement, StorageOperationStatus> getServiceRes = topologyTemplateOperation
- .getLightComponent(vertex, ComponentTypeEnum.SERVICE, new ComponentParametersView(true));
+ .getLightComponent(vertex, ComponentTypeEnum.SERVICE, new ComponentParametersView(true));
if (getServiceRes.isRight()) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ",
- vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value());
+ vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value());
return Either.right(getServiceRes.right().value());
} else {
servicesAll.add(ModelConverter.convertFromToscaElement(getServiceRes.left().value()));
@@ -2751,7 +2750,7 @@ public class ToscaOperationFacade {
public StorageOperationStatus addDeploymentArtifactsToInstance(String componentId, ComponentInstance componentInstance,
Map<String, ArtifactDefinition> finalDeploymentArtifacts) {
Map<String, ArtifactDataDefinition> instDeplArtifacts = finalDeploymentArtifacts.entrySet().stream()
- .collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
+ .collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
return nodeTemplateOperation.addDeploymentArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
}
@@ -2760,7 +2759,7 @@ public class ToscaOperationFacade {
StorageOperationStatus status = StorageOperationStatus.OK;
if (MapUtils.isNotEmpty(artifacts)) {
Map<String, ArtifactDataDefinition> instDeplArtifacts = artifacts.entrySet().stream()
- .collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
+ .collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
status = nodeTemplateOperation.addInformationalArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
}
return status;
@@ -2774,15 +2773,15 @@ public class ToscaOperationFacade {
return nodeTemplateOperation.generateCustomizationUUIDOnInstanceGroup(componentId, instanceId, groupInstances);
}
- public Either<PropertyDefinition, StorageOperationStatus> addPropertyToComponent(String propertyName, PropertyDefinition newPropertyDefinition,
+ public Either<PropertyDefinition, StorageOperationStatus> addPropertyToComponent(PropertyDefinition newPropertyDefinition,
Component component) {
- newPropertyDefinition.setName(propertyName);
+ final String propertyName = newPropertyDefinition.getName();
StorageOperationStatus status = getToscaElementOperation(component)
- .addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition,
- JsonPresentationFields.NAME);
+ .addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition,
+ JsonPresentationFields.NAME);
if (status != StorageOperationStatus.OK) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the component {}. Status is {}. ", propertyName,
- component.getName(), status);
+ component.getName(), status);
return Either.right(status);
}
ComponentParametersView filter = new ComponentParametersView(true);
@@ -2791,21 +2790,21 @@ public class ToscaOperationFacade {
Either<Component, StorageOperationStatus> getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
if (getUpdatedComponentRes.isRight()) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated component {}. Status is {}. ", component.getUniqueId(),
- getUpdatedComponentRes.right().value());
+ getUpdatedComponentRes.right().value());
return Either.right(status);
}
PropertyDefinition newProperty = null;
List<PropertyDefinition> properties = (getUpdatedComponentRes.left().value()).getProperties();
if (CollectionUtils.isNotEmpty(properties)) {
Optional<PropertyDefinition> propertyOptional = properties.stream().filter(propertyEntry -> propertyEntry.getName().equals(propertyName))
- .findAny();
+ .findAny();
if (propertyOptional.isPresent()) {
newProperty = propertyOptional.get();
}
}
if (newProperty == null) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the component {}. Status is {}. ",
- propertyName, component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
+ propertyName, component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
return Either.right(StorageOperationStatus.NOT_FOUND);
}
return Either.left(newProperty);
@@ -2815,11 +2814,11 @@ public class ToscaOperationFacade {
Component component) {
newInputDefinition.setName(inputName);
StorageOperationStatus status = getToscaElementOperation(component)
- .addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition,
- JsonPresentationFields.NAME);
+ .addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition,
+ JsonPresentationFields.NAME);
if (status != StorageOperationStatus.OK) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the input {} to the component {}. Status is {}. ", inputName,
- component.getName(), status);
+ component.getName(), status);
return Either.right(status);
}
ComponentParametersView filter = new ComponentParametersView(true);
@@ -2828,7 +2827,7 @@ public class ToscaOperationFacade {
Either<Component, StorageOperationStatus> getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
if (getUpdatedComponentRes.isRight()) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated component {}. Status is {}. ", component.getUniqueId(),
- getUpdatedComponentRes.right().value());
+ getUpdatedComponentRes.right().value());
return Either.right(status);
}
InputDefinition newInput = null;
@@ -2841,8 +2840,8 @@ public class ToscaOperationFacade {
}
if (newInput == null) {
CommonUtility
- .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added input {} " + "on the component {}. Status is {}. ", inputs,
- component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added input {} " + "on the component {}. Status is {}. ", inputs,
+ component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
return Either.right(StorageOperationStatus.NOT_FOUND);
}
return Either.left(newInput);
@@ -2850,24 +2849,24 @@ public class ToscaOperationFacade {
public StorageOperationStatus deletePropertyOfComponent(Component component, String propertyName) {
return getToscaElementOperation(component)
- .deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, propertyName,
- JsonPresentationFields.NAME);
+ .deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, propertyName,
+ JsonPresentationFields.NAME);
}
public StorageOperationStatus deleteAttributeOfResource(Component component, String attributeName) {
return getToscaElementOperation(component)
- .deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, attributeName,
- JsonPresentationFields.NAME);
+ .deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, attributeName,
+ JsonPresentationFields.NAME);
}
public StorageOperationStatus deleteInputOfResource(Component resource, String inputName) {
return getToscaElementOperation(resource)
- .deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputName, JsonPresentationFields.NAME);
+ .deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputName, JsonPresentationFields.NAME);
}
public StorageOperationStatus deleteOutputOfResource(final Component resource, final String outputName) {
return getToscaElementOperation(resource)
- .deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.OUTPUTS, VertexTypeEnum.OUTPUTS, outputName, JsonPresentationFields.NAME);
+ .deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.OUTPUTS, VertexTypeEnum.OUTPUTS, outputName, JsonPresentationFields.NAME);
}
/**
@@ -2879,8 +2878,8 @@ public class ToscaOperationFacade {
*/
public StorageOperationStatus deleteDataTypeOfComponent(Component component, String dataTypeName) {
return getToscaElementOperation(component)
- .deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.DATA_TYPES, VertexTypeEnum.DATA_TYPES, dataTypeName,
- JsonPresentationFields.NAME);
+ .deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.DATA_TYPES, VertexTypeEnum.DATA_TYPES, dataTypeName,
+ JsonPresentationFields.NAME);
}
public Either<PropertyDefinition, StorageOperationStatus> updatePropertyOfComponent(Component component,
@@ -2888,12 +2887,12 @@ public class ToscaOperationFacade {
Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
Either<PropertyDefinition, StorageOperationStatus> result = null;
StorageOperationStatus status = getToscaElementOperation(component)
- .updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition,
- JsonPresentationFields.NAME);
+ .updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition,
+ JsonPresentationFields.NAME);
if (status != StorageOperationStatus.OK) {
CommonUtility
- .addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newPropertyDefinition.getName(),
- component.getName(), status);
+ .addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newPropertyDefinition.getName(),
+ component.getName(), status);
result = Either.right(status);
}
if (result == null) {
@@ -2902,18 +2901,18 @@ public class ToscaOperationFacade {
getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
if (getUpdatedComponentRes.isRight()) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(),
- getUpdatedComponentRes.right().value());
+ getUpdatedComponentRes.right().value());
result = Either.right(status);
}
}
if (result == null) {
Optional<PropertyDefinition> newProperty = (getUpdatedComponentRes.left().value()).getProperties().stream()
- .filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny();
+ .filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny();
if (newProperty.isPresent()) {
result = Either.left(newProperty.get());
} else {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS,
- newPropertyDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
+ newPropertyDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
result = Either.right(StorageOperationStatus.NOT_FOUND);
}
}
@@ -2925,12 +2924,12 @@ public class ToscaOperationFacade {
Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
Either<AttributeDefinition, StorageOperationStatus> result = null;
StorageOperationStatus status = getToscaElementOperation(component)
- .updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newPropertyDefinition,
- JsonPresentationFields.NAME);
+ .updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newPropertyDefinition,
+ JsonPresentationFields.NAME);
if (status != StorageOperationStatus.OK) {
CommonUtility
- .addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newPropertyDefinition.getName(),
- component.getName(), status);
+ .addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newPropertyDefinition.getName(),
+ component.getName(), status);
result = Either.right(status);
}
if (result == null) {
@@ -2939,18 +2938,18 @@ public class ToscaOperationFacade {
getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
if (getUpdatedComponentRes.isRight()) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(),
- getUpdatedComponentRes.right().value());
+ getUpdatedComponentRes.right().value());
result = Either.right(status);
}
}
if (result == null) {
Optional<AttributeDefinition> newProperty = (getUpdatedComponentRes.left().value()).getAttributes().stream()
- .filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny();
+ .filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny();
if (newProperty.isPresent()) {
result = Either.left(newProperty.get());
} else {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS,
- newPropertyDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
+ newPropertyDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
result = Either.right(StorageOperationStatus.NOT_FOUND);
}
}
@@ -2966,11 +2965,11 @@ public class ToscaOperationFacade {
newAttributeDef.setOwnerId(component.getUniqueId());
}
StorageOperationStatus status = getToscaElementOperation(component)
- .addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef,
- JsonPresentationFields.NAME);
+ .addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef,
+ JsonPresentationFields.NAME);
if (status != StorageOperationStatus.OK) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(),
- component.getName(), status);
+ component.getName(), status);
result = Either.right(status);
}
if (result == null) {
@@ -2979,18 +2978,18 @@ public class ToscaOperationFacade {
getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
if (getUpdatedComponentRes.isRight()) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(),
- getUpdatedComponentRes.right().value());
+ getUpdatedComponentRes.right().value());
result = Either.right(status);
}
}
if (result == null) {
Optional<AttributeDefinition> newAttribute = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream()
- .filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
+ .filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
if (newAttribute.isPresent()) {
result = Either.left(newAttribute.get());
} else {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS,
- newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
+ newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
result = Either.right(StorageOperationStatus.NOT_FOUND);
}
}
@@ -3001,11 +3000,11 @@ public class ToscaOperationFacade {
Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
Either<AttributeDefinition, StorageOperationStatus> result = null;
StorageOperationStatus status = getToscaElementOperation(component)
- .updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef,
- JsonPresentationFields.NAME);
+ .updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef,
+ JsonPresentationFields.NAME);
if (status != StorageOperationStatus.OK) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(),
- component.getName(), status);
+ component.getName(), status);
result = Either.right(status);
}
if (result == null) {
@@ -3014,18 +3013,18 @@ public class ToscaOperationFacade {
getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
if (getUpdatedComponentRes.isRight()) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(),
- getUpdatedComponentRes.right().value());
+ getUpdatedComponentRes.right().value());
result = Either.right(status);
}
}
if (result == null) {
Optional<AttributeDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream()
- .filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
+ .filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
if (newProperty.isPresent()) {
result = Either.left(newProperty.get());
} else {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS,
- newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
+ newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
result = Either.right(StorageOperationStatus.NOT_FOUND);
}
}
@@ -3036,11 +3035,11 @@ public class ToscaOperationFacade {
Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
Either<InputDefinition, StorageOperationStatus> result = null;
StorageOperationStatus status = getToscaElementOperation(component)
- .updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition,
- JsonPresentationFields.NAME);
+ .updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition,
+ JsonPresentationFields.NAME);
if (status != StorageOperationStatus.OK) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the input {} to the component {}. Status is {}. ",
- newInputDefinition.getName(), component.getName(), status);
+ newInputDefinition.getName(), component.getName(), status);
result = Either.right(status);
}
if (result == null) {
@@ -3049,18 +3048,18 @@ public class ToscaOperationFacade {
getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
if (getUpdatedComponentRes.isRight()) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(),
- getUpdatedComponentRes.right().value());
+ getUpdatedComponentRes.right().value());
result = Either.right(status);
}
}
if (result == null) {
Optional<InputDefinition> updatedInput = getUpdatedComponentRes.left().value().getInputs().stream()
- .filter(p -> p.getName().equals(newInputDefinition.getName())).findAny();
+ .filter(p -> p.getName().equals(newInputDefinition.getName())).findAny();
if (updatedInput.isPresent()) {
result = Either.left(updatedInput.get());
} else {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently updated inputs {} on the resource {}. Status is {}. ",
- newInputDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
+ newInputDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
result = Either.right(StorageOperationStatus.NOT_FOUND);
}
}
@@ -3080,19 +3079,19 @@ public class ToscaOperationFacade {
String componentInstanceId) {
String uniqueId = componentInstance.getUniqueId();
StorageOperationStatus status = nodeTemplateOperation
- .deleteToscaDataDeepElementsBlockOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS,
- uniqueId);
+ .deleteToscaDataDeepElementsBlockOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS,
+ uniqueId);
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
CommonUtility
- .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete group instances for container {}. error {] ", componentInstanceId, status);
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete group instances for container {}. error {] ", componentInstanceId, status);
return Either.right(status);
}
if (componentInstance.getGroupInstances() != null) {
status = addGroupInstancesToComponentInstance(containerComponent, componentInstance, componentInstance.getGroupInstances());
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
CommonUtility
- .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add group instances for container {}. error {] ", componentInstanceId,
- status);
+ .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add group instances for container {}. error {] ", componentInstanceId,
+ status);
return Either.right(status);
}
}
@@ -3196,25 +3195,25 @@ public class ToscaOperationFacade {
public StorageOperationStatus deleteComponentInstanceInputsFromTopologyTemplate(Component containerComponent,
List<InputDefinition> inputsToDelete) {
return topologyTemplateOperation.deleteToscaDataElements(containerComponent.getUniqueId(), EdgeLabelEnum.INPUTS,
- inputsToDelete.stream().map(PropertyDataDefinition::getName).collect(Collectors.toList()));
+ inputsToDelete.stream().map(PropertyDataDefinition::getName).collect(Collectors.toList()));
}
public StorageOperationStatus deleteComponentInstanceOutputsFromTopologyTemplate(final Component containerComponent,
final List<OutputDefinition> outputsToDelete) {
return topologyTemplateOperation.deleteToscaDataElements(containerComponent.getUniqueId(), EdgeLabelEnum.OUTPUTS,
- outputsToDelete.stream().map(AttributeDataDefinition::getName).collect(Collectors.toList()));
+ outputsToDelete.stream().map(AttributeDataDefinition::getName).collect(Collectors.toList()));
}
public StorageOperationStatus updateComponentInstanceCapabiltyProperty(Component containerComponent, String componentInstanceUniqueId,
String capabilityPropertyKey, ComponentInstanceProperty property) {
return nodeTemplateOperation
- .updateComponentInstanceCapabilityProperty(containerComponent, componentInstanceUniqueId, capabilityPropertyKey, property);
+ .updateComponentInstanceCapabilityProperty(containerComponent, componentInstanceUniqueId, capabilityPropertyKey, property);
}
public StorageOperationStatus updateComponentInstanceCapabilityProperties(Component containerComponent, String componentInstanceUniqueId) {
return convertComponentInstanceProperties(containerComponent, componentInstanceUniqueId).map(instanceCapProps -> topologyTemplateOperation
- .updateComponentInstanceCapabilityProperties(containerComponent, componentInstanceUniqueId, instanceCapProps))
- .orElse(StorageOperationStatus.NOT_FOUND);
+ .updateComponentInstanceCapabilityProperties(containerComponent, componentInstanceUniqueId, instanceCapProps))
+ .orElse(StorageOperationStatus.NOT_FOUND);
}
public StorageOperationStatus updateComponentInstanceRequirement(String containerComponentId, String componentInstanceUniqueId,
@@ -3247,15 +3246,15 @@ public class ToscaOperationFacade {
final ToscaElementOperation toscaElementOperation = getToscaElementOperation(component);
if (match) {
status = toscaElementOperation.updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INTERFACE_ARTIFACTS,
- VertexTypeEnum.INTERFACE_ARTIFACTS, interfaceDefinition, JsonPresentationFields.TYPE);
+ VertexTypeEnum.INTERFACE_ARTIFACTS, interfaceDefinition, JsonPresentationFields.TYPE);
} else {
status = toscaElementOperation.addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.INTERFACE_ARTIFACTS,
- VertexTypeEnum.INTERFACE_ARTIFACTS, interfaceDefinition, JsonPresentationFields.TYPE);
+ VertexTypeEnum.INTERFACE_ARTIFACTS, interfaceDefinition, JsonPresentationFields.TYPE);
}
if (status != StorageOperationStatus.OK) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the interface {} to the component {}. Status is {}. ",
- interfaceName, component.getName(), status);
+ interfaceName, component.getName(), status);
return Either.right(status);
}
final ComponentParametersView filter = new ComponentParametersView(true);
@@ -3264,7 +3263,7 @@ public class ToscaOperationFacade {
final Either<Component, StorageOperationStatus> getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
if (getUpdatedComponentRes.isRight()) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated component {}. Status is {}. ",
- component.getUniqueId(), getUpdatedComponentRes.right().value());
+ component.getUniqueId(), getUpdatedComponentRes.right().value());
return Either.right(getUpdatedComponentRes.right().value());
}
InterfaceDefinition newInterfaceDefinition = null;
@@ -3277,7 +3276,7 @@ public class ToscaOperationFacade {
}
if (newInterfaceDefinition == null) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added interface {} on the component {}. Status is {}. ",
- interfaceName, component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
+ interfaceName, component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
return Either.right(StorageOperationStatus.NOT_FOUND);
}
return Either.left(newInterfaceDefinition);
@@ -3290,14 +3289,14 @@ public class ToscaOperationFacade {
public StorageOperationStatus deleteAllCalculatedCapabilitiesRequirements(String topologyTemplateId) {
StorageOperationStatus status = topologyTemplateOperation
- .removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES);
+ .removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES);
if (status == StorageOperationStatus.OK) {
status = topologyTemplateOperation
- .removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS);
+ .removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS);
}
if (status == StorageOperationStatus.OK) {
status = topologyTemplateOperation
- .removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES);
+ .removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES);
}
return status;
}
@@ -3312,10 +3311,10 @@ public class ToscaOperationFacade {
GraphVertex nodeTypeV = getVertexEither.left().value();
ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(clonedResource);
Either<ToscaElement, StorageOperationStatus> shouldUpdateDerivedVersion = nodeTypeOperation
- .shouldUpdateDerivedVersion(toscaElementToUpdate, nodeTypeV);
+ .shouldUpdateDerivedVersion(toscaElementToUpdate, nodeTypeV);
if (shouldUpdateDerivedVersion.isRight() && StorageOperationStatus.OK != shouldUpdateDerivedVersion.right().value()) {
log.debug("Failed to update derived version for node type {} derived {}, error: {}", componentId, clonedResource.getDerivedFrom().get(0),
- shouldUpdateDerivedVersion.right().value());
+ shouldUpdateDerivedVersion.right().value());
return Either.right(shouldUpdateDerivedVersion.right().value());
}
if (shouldUpdateDerivedVersion.isLeft()) {
@@ -3360,7 +3359,7 @@ public class ToscaOperationFacade {
private Optional<MapCapabilityProperty> convertComponentInstanceProperties(Component component, String instanceId) {
return component.fetchInstanceById(instanceId)
- .map(ci -> ModelConverter.convertToMapOfMapCapabilityProperties(ci.getCapabilities(), instanceId, ci.getOriginType().isAtomicType()));
+ .map(ci -> ModelConverter.convertToMapOfMapCapabilityProperties(ci.getCapabilities(), instanceId, ci.getOriginType().isAtomicType()));
}
public Either<PolicyDefinition, StorageOperationStatus> associatePolicyToComponent(String componentId, PolicyDefinition policyDefinition,
@@ -3379,7 +3378,7 @@ public class ToscaOperationFacade {
}
if (result == null) {
StorageOperationStatus status = topologyTemplateOperation
- .addPolicyToToscaElement(getVertexEither.left().value(), policyDefinition, counter);
+ .addPolicyToToscaElement(getVertexEither.left().value(), policyDefinition, counter);
if (status != StorageOperationStatus.OK) {
return Either.right(status);
}
@@ -3393,8 +3392,8 @@ public class ToscaOperationFacade {
public StorageOperationStatus associatePoliciesToComponent(String componentId, List<PolicyDefinition> policies) {
log.debug("#associatePoliciesToComponent - associating policies for component {}.", componentId);
return janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata)
- .either(containerVertex -> topologyTemplateOperation.addPoliciesToToscaElement(containerVertex, policies),
- DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
+ .either(containerVertex -> topologyTemplateOperation.addPoliciesToToscaElement(containerVertex, policies),
+ DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
}
public Either<PolicyDefinition, StorageOperationStatus> updatePolicyOfComponent(String componentId, PolicyDefinition policyDefinition,
@@ -3422,8 +3421,8 @@ public class ToscaOperationFacade {
public StorageOperationStatus updatePoliciesOfComponent(String componentId, List<PolicyDefinition> policyDefinition) {
log.debug("#updatePoliciesOfComponent - updating policies for component {}", componentId);
return janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse).right()
- .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus)
- .either(containerVertex -> topologyTemplateOperation.updatePoliciesOfToscaElement(containerVertex, policyDefinition), err -> err);
+ .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus)
+ .either(containerVertex -> topologyTemplateOperation.updatePoliciesOfToscaElement(containerVertex, policyDefinition), err -> err);
}
public StorageOperationStatus removePolicyFromComponent(String componentId, String policyId) {
@@ -3475,7 +3474,7 @@ public class ToscaOperationFacade {
private TopologyTemplate getTopologyTemplate(String componentId) {
return (TopologyTemplate) topologyTemplateOperation.getToscaElement(componentId, getFilterComponentWithCapProperties()).left()
- .on(this::throwStorageException);
+ .on(this::throwStorageException);
}
private ComponentParametersView getFilterComponentWithCapProperties() {
@@ -3490,7 +3489,7 @@ public class ToscaOperationFacade {
public Either<Boolean, StorageOperationStatus> isComponentInUse(String componentId) {
final List<EdgeLabelEnum> forbiddenEdgeLabelEnums = Arrays
- .asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF);
+ .asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF);
Either<GraphVertex, JanusGraphOperationStatus> vertexById = janusGraphDao.getVertexById(componentId);
if (vertexById.isLeft()) {
for (EdgeLabelEnum edgeLabelEnum : forbiddenEdgeLabelEnums) {
@@ -3511,10 +3510,10 @@ public class ToscaOperationFacade {
}
propertiesToMatch.put(GraphPropertyEnum.INVARIANT_UUID, componentInvariantUuid);
Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
- .getByCriteria(null, propertiesToMatch, JsonParseFlagEnum.ParseMetadata);
+ .getByCriteria(null, propertiesToMatch, JsonParseFlagEnum.ParseMetadata);
if (vertexEither.isRight()) {
log.debug("Couldn't fetch metadata for component with type {} and invariantUUId {}, error: {}", componentInvariantUuid,
- vertexEither.right().value());
+ vertexEither.right().value());
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
}
List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
@@ -3541,7 +3540,7 @@ public class ToscaOperationFacade {
if (vertexById.isLeft()) {
for (EdgeLabelEnum edgeLabelEnum : relationEdgeLabelEnums) {
Either<GraphVertex, JanusGraphOperationStatus> parentVertexEither = janusGraphDao
- .getParentVertex(vertexById.left().value(), edgeLabelEnum, JsonParseFlagEnum.ParseJson);
+ .getParentVertex(vertexById.left().value(), edgeLabelEnum, JsonParseFlagEnum.ParseJson);
if (parentVertexEither.isLeft()) {
Either<Component, StorageOperationStatus> componentEither = getToscaElement(parentVertexEither.left().value().getUniqueId());
if (componentEither.isLeft()) {
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PropertyDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PropertyDataDefinition.java
index ff72f1f361..6b17c419e4 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PropertyDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PropertyDataDefinition.java
@@ -40,8 +40,8 @@ import org.openecomp.sdc.be.datatypes.tosca.ToscaGetFunctionType;
@Data
public class PropertyDataDefinition extends ToscaDataDefinition {
- protected boolean definition = false;
- protected Boolean hidden = Boolean.FALSE;
+ private boolean definition = false;
+ private Boolean hidden = Boolean.FALSE;
private String uniqueId;
// "boolean", "string", "float", "integer", "version" })
private String type;
@@ -80,6 +80,7 @@ public class PropertyDataDefinition extends ToscaDataDefinition {
private List<GetPolicyValueDataDefinition> getPolicyValues;
private List<String> propertyConstraints;
private Map<String, String> metadata;
+ private boolean userCreated;
public PropertyDataDefinition() {
super();
@@ -132,6 +133,7 @@ public class PropertyDataDefinition extends ToscaDataDefinition {
setPropertyConstraints(new ArrayList<>(propertyDataDefinition.getPropertyConstraints()));
}
this.setIsDeclaredListInput(propertyDataDefinition.getIsDeclaredListInput());
+ this.setUserCreated(propertyDataDefinition.isUserCreated());
}
// @Override