aboutsummaryrefslogtreecommitdiffstats
path: root/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl
diff options
context:
space:
mode:
Diffstat (limited to 'catalog-be/src/main/java/org/openecomp/sdc/be/components/impl')
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java109
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AnnotationBusinessLogic.java68
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArchiveBusinessLogic.java156
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java18
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java356
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java50
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java393
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManager.java108
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java33
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java16
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java432
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java380
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogicProvider.java37
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java143
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentLocker.java55
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java52
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java37
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java123
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeImportManager.java86
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypesService.java39
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogic.java51
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java269
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ExternalRefsBusinessLogic.java58
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java649
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogicNew.java231
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeBusinessLogic.java52
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java138
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java372
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java180
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java21
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogic.java67
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/MonitoringBusinessLogic.java8
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OnDeleteEntityOperation.java16
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java115
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogic.java44
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java68
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java160
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java172
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementsBusinessLogic.java5
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java5366
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java406
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResponseFormatManager.java5
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java934
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ComponentException.java7
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/SdcResourceNotFoundException.java12
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogic.java14
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/group/GroupMembersUpdater.java56
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/ComponentInstanceChangeOperationOrchestrator.java43
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/GroupMembersUpdateOperation.java62
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/OnChangeVersionOperation.java18
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/OnComponentInstanceChangeOperation.java9
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/PolicyTargetsUpdateOperation.java33
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/lock/ComponentLockAspect.java38
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/lock/LockingTransactional.java13
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/model/ToscaTypeImportData.java24
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdateHandler.java58
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdater.java57
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CapabilityTypeImportUtils.java28
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/ExceptionUtils.java44
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtils.java22
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/GroupMembersUpdateOperation.java66
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PolicyTargetsUpdateOperation.java67
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperation.java11
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestrator.java32
64 files changed, 5550 insertions, 7242 deletions
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java
index 90f2148195..7f6565c88e 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java
@@ -20,10 +20,7 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.List;
-
-import javax.servlet.ServletContext;
-
+import fj.data.Either;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -31,27 +28,24 @@ import org.openecomp.sdc.be.dao.graph.datatype.AdditionalInformationEnum;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
import org.openecomp.sdc.be.model.AdditionalInformationDefinition;
-import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.operations.api.IAdditionalInformationOperation;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
-import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
import org.openecomp.sdc.be.model.tosca.converters.StringConvertor;
import org.openecomp.sdc.be.model.tosca.validators.StringValidator;
import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
-import fj.data.Either;
+import javax.servlet.ServletContext;
+import java.util.List;
@Component("additionalInformationBusinessLogic")
public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
@@ -64,17 +58,12 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
private static final String GET_ADDITIONAL_INFORMATION = "GetAdditionalInformation";
- private static final Logger log = LoggerFactory.getLogger(AdditionalInformationBusinessLogic.class);
+ private static final Logger log = Logger.getLogger(AdditionalInformationBusinessLogic.class.getName());
+ private static final String FAILED_TO_LOCK_COMPONENT_ERROR = "Failed to lock component {} error - {}";
@javax.annotation.Resource
private IAdditionalInformationOperation additionalInformationOperation = null;
- @javax.annotation.Resource
- private IGraphLockOperation graphLockOperation;
-
- @javax.annotation.Resource
- private ComponentsUtils componentsUtils;
-
protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) {
WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
@@ -85,19 +74,15 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
/**
* Create new additional information on resource/service on graph
- *
+ * @param nodeType
* @param resourceId
- * @param propertyName
- * @param newPropertyDefinition
+ * @param additionalInfoParameterInfo
* @param userId
- * @return Either<PropertyDefinition, ActionStatus>
+ * @return Either<AdditionalInfoParameterInfo, ResponseFormat>
*/
- public Either<AdditionalInfoParameterInfo, ResponseFormat> createAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String additionalInformationUid, String userId) {
+ public Either<AdditionalInfoParameterInfo, ResponseFormat> createAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String userId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "create Additional Information", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "create Additional Information", false);
Either<AdditionalInfoParameterInfo, ResponseFormat> result = null;
ResponseFormat responseFormat = verifyCanWorkOnComponent(nodeType, resourceId, userId);
@@ -110,7 +95,7 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, nodeType);
if (!lockResult.equals(StorageOperationStatus.OK)) {
BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_ADDITIONAL_INFORMATION, nodeType.getName(), resourceId);
- log.info("Failed to lock component {} error - {}", resourceId, lockResult);
+ log.info(FAILED_TO_LOCK_COMPONENT_ERROR, resourceId, lockResult);
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
return result;
}
@@ -180,7 +165,7 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
} else {
String newValue = valueValidRes.left().value();
if (log.isTraceEnabled()) {
- if (value != null && false == value.equals(newValue)) {
+ if (value != null && !value.equals(newValue)) {
log.trace("The additional information value was normalized from {} to {}", value, newValue);
}
}
@@ -209,10 +194,8 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
} else {
String convertedKey = validateKeyRes.left().value();
- if (log.isTraceEnabled()) {
- if (key != null && false == key.equals(convertedKey)) {
- log.trace("The additional information key {} was normalized to {}", key, convertedKey);
- }
+ if (log.isTraceEnabled() && key != null && !key.equals(convertedKey)) {
+ log.trace("The additional information key {} was normalized to {}", key, convertedKey);
}
additionalInfoParameterInfo.setKey(convertedKey);
}
@@ -259,12 +242,12 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
private Either<String, ResponseFormat> validateValue(String value) {
boolean isNonEmptyString = ValidationUtils.validateStringNotEmpty(value);
- if (false == isNonEmptyString) {
+ if (!isNonEmptyString) {
return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED));
}
boolean valid = StringValidator.getInstance().isValid(value, null);
- if (false == valid) {
+ if (!valid) {
return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_VALUE_NOT_ALLOWED_CHARACTERS, new AdditionalInfoParameterInfo(null, value), null, AdditionalInformationEnum.Value));
}
@@ -285,29 +268,28 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
/**
* validate and normalize the key
- *
- * @param additionalInfoParameterInfo
- * @return
+ * @param key
+ * @return Either<String, ResponseFormat>
*/
private Either<String, ResponseFormat> validateAndNormalizeKey(String key) {
AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo();
additionalInfoParameterInfo.setKey(key);
- key = ValidationUtils.normalizeAdditionalInformation(key);
- boolean isNonEmptyString = ValidationUtils.validateStringNotEmpty(key);
- if (false == isNonEmptyString) {
+ String normKey = ValidationUtils.normalizeAdditionalInformation(key);
+ boolean isNonEmptyString = ValidationUtils.validateStringNotEmpty(normKey);
+ if (!isNonEmptyString) {
return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED, null, null, AdditionalInformationEnum.Label));
}
- boolean isValidString = ValidationUtils.validateAdditionalInformationKeyName(key);
- if (false == isValidString) {
- if (false == ValidationUtils.validateLength(key, ValidationUtils.ADDITIONAL_INFORMATION_KEY_MAX_LENGTH)) {
+ boolean isValidString = ValidationUtils.validateAdditionalInformationKeyName(normKey);
+ if (!isValidString) {
+ if (!ValidationUtils.validateLength(normKey, ValidationUtils.ADDITIONAL_INFORMATION_KEY_MAX_LENGTH)) {
return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EXCEEDS_LIMIT, additionalInfoParameterInfo, null, AdditionalInformationEnum.Label));
}
return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_KEY_NOT_ALLOWED_CHARACTERS, additionalInfoParameterInfo, null, AdditionalInformationEnum.Label));
}
- return Either.left(key);
+ return Either.left(normKey);
}
/**
@@ -316,17 +298,12 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
* @param nodeType
* @param resourceId
* @param additionalInfoParameterInfo
- * @param additionalInformationUid
- * - Future use
* @param userId
* @return
*/
- public Either<AdditionalInfoParameterInfo, ResponseFormat> updateAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String additionalInformationUid, String userId) {
+ public Either<AdditionalInfoParameterInfo, ResponseFormat> updateAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String userId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "create Additional Information", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "create Additional Information", false);
Either<AdditionalInfoParameterInfo, ResponseFormat> result = null;
ResponseFormat responseFormat = verifyCanWorkOnComponent(nodeType, resourceId, userId);
@@ -338,7 +315,7 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, nodeType);
if (!lockResult.equals(StorageOperationStatus.OK)) {
BeEcompErrorManager.getInstance().logBeFailedLockObjectError(UPDATE_ADDITIONAL_INFORMATION, nodeType.getName(), resourceId);
- log.info("Failed to lock component {} error - {}", resourceId, lockResult);
+ log.info(FAILED_TO_LOCK_COMPONENT_ERROR, resourceId, lockResult);
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
return result;
}
@@ -387,17 +364,12 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
* @param nodeType
* @param resourceId
* @param additionalInfoParameterInfo
- * @param additionalInformationUid
- * - Null. Future use.
* @param userId
* @return
*/
- public Either<AdditionalInfoParameterInfo, ResponseFormat> deleteAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String additionalInformationUid, String userId) {
+ public Either<AdditionalInfoParameterInfo, ResponseFormat> deleteAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String userId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Additional Information", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "delete Additional Information", false);
Either<AdditionalInfoParameterInfo, ResponseFormat> result = null;
ResponseFormat responseFormat = verifyCanWorkOnComponent(nodeType, resourceId, userId);
@@ -408,7 +380,7 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, nodeType);
if (!lockResult.equals(StorageOperationStatus.OK)) {
BeEcompErrorManager.getInstance().logBeFailedLockObjectError(DELETE_ADDITIONAL_INFORMATION, nodeType.getName(), resourceId);
- log.info("Failed to lock component {} error - {}", resourceId, lockResult);
+ log.info(FAILED_TO_LOCK_COMPONENT_ERROR, resourceId, lockResult);
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
return result;
}
@@ -453,16 +425,12 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
* @param nodeType
* @param resourceId
* @param additionalInfoParameterInfo
- * @param additionalInformationUid
* @param userId
* @return
*/
- public Either<AdditionalInfoParameterInfo, ResponseFormat> getAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String additionalInformationUid, String userId) {
+ public Either<AdditionalInfoParameterInfo, ResponseFormat> getAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String userId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Additional Information", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "get Additional Information", false);
Either<AdditionalInfoParameterInfo, ResponseFormat> result = null;
try {
@@ -492,17 +460,12 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
*
* @param nodeType
* @param resourceId
- * @param additionalInformationUid
- * - Future use
* @param userId
* @return
*/
- public Either<AdditionalInformationDefinition, ResponseFormat> getAllAdditionalInformation(NodeTypeEnum nodeType, String resourceId, String additionalInformationUid, String userId) {
+ public Either<AdditionalInformationDefinition, ResponseFormat> getAllAdditionalInformation(NodeTypeEnum nodeType, String resourceId, String userId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get All Additional Information", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "get All Additional Information", false);
Either<AdditionalInformationDefinition, ResponseFormat> result = null;
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AnnotationBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AnnotationBusinessLogic.java
new file mode 100644
index 0000000000..c73f168c9a
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AnnotationBusinessLogic.java
@@ -0,0 +1,68 @@
+package org.openecomp.sdc.be.components.impl;
+
+import org.openecomp.sdc.be.components.validation.AnnotationValidator;
+import org.openecomp.sdc.be.dao.utils.MapUtil;
+import org.openecomp.sdc.be.datatypes.elements.Annotation;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.model.AnnotationTypeDefinition;
+import org.openecomp.sdc.be.model.InputDefinition;
+import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.operations.impl.AnnotationTypeOperations;
+import org.springframework.stereotype.Component;
+
+import java.util.*;
+
+import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
+
+@Component
+public class AnnotationBusinessLogic {
+
+ private final AnnotationTypeOperations annotationTypeOperations;
+
+ private final AnnotationValidator annotationValidator;
+
+ public AnnotationBusinessLogic(AnnotationTypeOperations annotationTypeOperations,
+ AnnotationValidator annotationValidator){
+ this.annotationTypeOperations = annotationTypeOperations;
+ this.annotationValidator = annotationValidator;
+ }
+
+ public void validateAndMergeAnnotationsAndAssignToInput(Map<String, InputDefinition> inputs) {
+ if (!inputs.isEmpty()){
+ for (InputDefinition input : inputs.values()) {
+ List<Annotation> inputAnnotationList = input.getAnnotations();
+ if (isNotEmpty(inputAnnotationList)) {
+ for (Annotation annotation : inputAnnotationList) {
+ AnnotationTypeDefinition dbAnnotationTypeDefinition = annotationTypeOperations.getLatestType(annotation.getType());
+ validateMergeAndSetAnnoProps(annotation, dbAnnotationTypeDefinition);
+ }
+ }
+ input.setAnnotations(inputAnnotationList);
+ }
+ }
+ }
+
+ public AnnotationTypeOperations getAnnotationTypeOperations() {
+ return annotationTypeOperations;
+ }
+
+ private void validateMergeAndSetAnnoProps(Annotation annotation, AnnotationTypeDefinition dbAnnotationTypeDefinition) {
+ annotationValidator.validateAnnotationsProperties(annotation, dbAnnotationTypeDefinition);
+ List<PropertyDataDefinition> mergedPropertiesList = mergePropsOfAnnoDataTypeWithParsedAnnoProps(annotation.getProperties(), dbAnnotationTypeDefinition.getProperties());
+ annotation.setProperties(mergedPropertiesList);
+ }
+
+ private List<PropertyDataDefinition> mergePropsOfAnnoDataTypeWithParsedAnnoProps(List<PropertyDataDefinition> annoProperties, List<PropertyDefinition> typePropertiesList) {
+ Set<PropertyDataDefinition> mergedPropertiesSet = new HashSet<>(typePropertiesList);
+ Map<String, PropertyDefinition> typePropsMap = MapUtil.toMap(typePropertiesList, PropertyDefinition::getName);
+ for (PropertyDataDefinition propertyDataDefinitionObject : annoProperties) {
+ PropertyDefinition foundTypePropertyDefinitionObject = typePropsMap.get(propertyDataDefinitionObject.getName());
+ //The case of unexisting property was already handled in the validation process (result: failure)
+ PropertyDataDefinition modifiedPropertyDataObject = new PropertyDataDefinition(foundTypePropertyDefinitionObject);
+ modifiedPropertyDataObject.setValue(propertyDataDefinitionObject.getValue());
+ mergedPropertiesSet.add(modifiedPropertyDataObject);
+ }
+ return new ArrayList<>(mergedPropertiesSet);
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArchiveBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArchiveBusinessLogic.java
new file mode 100644
index 0000000000..70898fbec2
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArchiveBusinessLogic.java
@@ -0,0 +1,156 @@
+package org.openecomp.sdc.be.components.impl;
+
+import com.google.common.annotations.VisibleForTesting;
+import fj.data.Either;
+import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
+import org.openecomp.sdc.be.components.validation.AccessValidations;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentParametersView;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.catalog.CatalogComponent;
+import org.openecomp.sdc.be.model.jsontitan.operations.ArchiveOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
+import org.openecomp.sdc.common.log.wrappers.Logger;
+
+import java.util.*;
+import java.util.stream.Collectors;
+
+@org.springframework.stereotype.Component
+public class ArchiveBusinessLogic {
+
+ private static final Logger log = Logger.getLogger(ArchiveBusinessLogic.class.getName());
+
+ private final TitanDao titanDao;
+ private final AccessValidations accessValidations;
+ private final ArchiveOperation archiveOperation;
+ private final ToscaOperationFacade toscaOperationFacade;
+ private final ComponentsUtils componentUtils;
+
+ public ArchiveBusinessLogic(TitanDao titanDao, AccessValidations accessValidations, ArchiveOperation archiveOperation, ToscaOperationFacade tof, ComponentsUtils componentsUtils) {
+ this.titanDao = titanDao;
+ this.accessValidations = accessValidations;
+ this.archiveOperation = archiveOperation;
+ this.toscaOperationFacade = tof;
+ this.componentUtils = componentsUtils;
+ }
+
+ public void archiveComponent(String containerComponentType, String userId, String componentId) {
+ User user = accessValidations.userIsAdminOrDesigner(userId, containerComponentType + "_ARCHIVE");
+ Either<List<String>, ActionStatus> result = this.archiveOperation.archiveComponent(componentId);
+
+ if (result.isRight()){
+ throw new ComponentException(result.right().value(), componentId);
+ }
+ this.auditAction(ArchiveOperation.Action.ARCHIVE, result.left().value(), user, containerComponentType);
+ }
+
+ public void restoreComponent(String containerComponentType, String userId, String componentId) {
+ User user = accessValidations.userIsAdminOrDesigner(userId, containerComponentType + "_RESTORE");
+ Either<List<String>, ActionStatus> result = this.archiveOperation.restoreComponent(componentId);
+ if (result.isRight()){
+ throw new ComponentException(result.right().value(), componentId);
+ }
+ this.auditAction(ArchiveOperation.Action.RESTORE, result.left().value(), user, containerComponentType);
+ }
+
+ public List<String> onVspArchive(String userId, List<String> csarUuids){
+ return this.onVspArchiveOrRestore(userId, csarUuids, ArchiveOperation.Action.ARCHIVE);
+ }
+
+ public List<String> onVspRestore(String userId, List<String> csarUuids){
+ return this.onVspArchiveOrRestore(userId, csarUuids, ArchiveOperation.Action.RESTORE);
+ }
+
+ private List<String> onVspArchiveOrRestore(String userId, List<String> csarUuids, ArchiveOperation.Action action) {
+
+ accessValidations.userIsAdminOrDesigner(userId, action.name() + "_VSP");
+
+ ActionStatus actionStatus;
+ List<String> failedCsarIDs = new LinkedList<>();
+
+ for (String csarUuid : csarUuids) {
+ try {
+
+ if (action.equals(ArchiveOperation.Action.ARCHIVE)) {
+ actionStatus = this.archiveOperation.onVspArchived(csarUuid);
+ } else {
+ actionStatus = this.archiveOperation.onVspRestored(csarUuid);
+ }
+
+ //If not found VFs with this CSAR ID we still want a success (nothing is actually done)
+ if (actionStatus == ActionStatus.RESOURCE_NOT_FOUND) {
+ actionStatus = ActionStatus.OK;
+ }
+
+ if (actionStatus != ActionStatus.OK) {
+ failedCsarIDs.add(csarUuid);
+ }
+
+ } catch (Exception e) {
+ log.error("Failed to handle notification: {} on VSP for csarUuid: {}", action.name(), csarUuid);
+ log.error("Exception Thrown:", e);
+ failedCsarIDs.add(csarUuid);
+ }
+ }
+
+ return failedCsarIDs;
+ }
+
+ public Map<String, List<CatalogComponent>> getArchiveComponents(String userId, List<OriginTypeEnum> excludeTypes) {
+ try {
+
+ accessValidations.validateUserExist(userId, "GET ARCHIVED COMPONENTS");
+
+ Either<List<CatalogComponent>, StorageOperationStatus> components = toscaOperationFacade.getCatalogOrArchiveComponents(false, excludeTypes);
+ if (components.isLeft()) {
+ List<CatalogComponent> comps = components.left().value();
+ return comps.stream().collect(Collectors.groupingBy(cmpt -> ComponentTypeEnum.findParamByType(cmpt.getComponentType())));
+ } else {
+ log.info("No components found");
+ return new HashMap();
+ }
+ } catch (Exception e){
+ log.error("Error fetching archived elements", e);
+ throw e;
+ }
+ finally {
+ titanDao.commit();
+ }
+ }
+
+
+ @VisibleForTesting
+ void auditAction(ArchiveOperation.Action action, List<String> affectedCompIds, User user, String containerComponentType) {
+ String comment = String.format("All versions of this component were %s", action == ArchiveOperation.Action.ARCHIVE ? "archived" : "restored");
+ HashSet<String> auditDoneUUIDs = new HashSet<>();
+ for (String componentId : affectedCompIds){
+ Either<Component, StorageOperationStatus> result = toscaOperationFacade.getToscaElement(componentId, new ComponentParametersView());
+ if (result.isRight()) {
+ log.error(EcompLoggerErrorCode.DATA_ERROR, null, "GetToscaElement",
+ result.right().value().name() + "for component with id {}", componentId);
+ continue;
+ }
+ if (auditDoneUUIDs.add(result.left().value().getUUID())) {
+ //a component with this UUID is not added to audit DB/log for current archive/restore operation yet - add to audit DB now
+ AuditingActionEnum auditAction = action == ArchiveOperation.Action.ARCHIVE ? AuditingActionEnum.ARCHIVE_COMPONENT : AuditingActionEnum.RESTORE_COMPONENT; //The audit Action
+ result.left().foreachDoEffect(
+ c -> {
+ // The archive/restore records have been retrieved from Cassandra using the separate queries.
+ // Setting current version as null allows to avoid appearing same records in ActivityLog twice:
+ // - first time as per current version query
+ //- second type as per archive/restore query
+ c.setVersion(null);
+ componentUtils.auditComponentAdmin(componentUtils.getResponseFormat(ActionStatus.OK), user, c, auditAction, ComponentTypeEnum.findByParamName(containerComponentType), comment);
+ });
+ }
+ }
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java
index b7dfabf071..c7f92d2184 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java
@@ -20,23 +20,13 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.stream.Collectors;
-
import org.apache.commons.collections.MapUtils;
import org.openecomp.sdc.be.components.ArtifactsResolver;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.InterfaceDefinition;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.*;
+
+import java.util.*;
+import java.util.stream.Collectors;
@org.springframework.stereotype.Component("artifact-resolver")
public class ArtifactResolverImpl implements ArtifactsResolver {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java
index b7c4b924c2..f104079e21 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java
@@ -20,28 +20,10 @@
package org.openecomp.sdc.be.components.impl;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.math.BigDecimal;
-import java.util.ArrayList;
-import java.util.Comparator;
-import java.util.EnumMap;
-import java.util.HashMap;
-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.Predicate;
-import java.util.function.Supplier;
-import java.util.stream.Collectors;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.xml.XMLConstants;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.parsers.SAXParserFactory;
-
+import com.google.common.annotations.VisibleForTesting;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import fj.data.Either;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
@@ -50,7 +32,7 @@ import org.apache.commons.lang3.tuple.ImmutablePair;
import org.elasticsearch.common.Strings;
import org.openecomp.sdc.be.components.ArtifactsResolver;
import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
-import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
+import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
@@ -65,41 +47,24 @@ import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.info.ArtifactTemplateInfo;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.ArtifactType;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.ComponentParametersView;
-import org.openecomp.sdc.be.model.GroupDefinition;
-import org.openecomp.sdc.be.model.GroupInstance;
-import org.openecomp.sdc.be.model.HeatParameterDefinition;
-import org.openecomp.sdc.be.model.InterfaceDefinition;
-import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.Operation;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.heat.HeatParameterType;
import org.openecomp.sdc.be.model.jsontitan.operations.InterfaceOperation;
import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation;
import org.openecomp.sdc.be.model.jsontitan.utils.InterfaceUtils;
-import org.openecomp.sdc.be.model.operations.api.IElementOperation;
-import org.openecomp.sdc.be.model.operations.api.IHeatParametersOperation;
-import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
-import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.api.*;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
import org.openecomp.sdc.be.resources.data.ESArtifactData;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
-import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
import org.openecomp.sdc.be.servlets.RepresentationUtils;
import org.openecomp.sdc.be.tosca.CsarUtils;
import org.openecomp.sdc.be.tosca.ToscaError;
@@ -108,10 +73,10 @@ import org.openecomp.sdc.be.tosca.ToscaRepresentation;
import org.openecomp.sdc.be.user.IUserBusinessLogic;
import org.openecomp.sdc.be.user.Role;
import org.openecomp.sdc.be.user.UserBusinessLogic;
+import org.openecomp.sdc.be.utils.TypeUtils;
import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
import org.openecomp.sdc.common.api.ArtifactTypeEnum;
import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import org.openecomp.sdc.common.datastructure.Wrapper;
import org.openecomp.sdc.common.util.GeneralUtility;
import org.openecomp.sdc.common.util.ValidationUtils;
@@ -120,18 +85,21 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-import org.xml.sax.SAXNotRecognizedException;
-import org.xml.sax.SAXNotSupportedException;
-import org.xml.sax.XMLReader;
+import org.xml.sax.*;
import org.yaml.snakeyaml.Yaml;
-import com.google.common.annotations.VisibleForTesting;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-
-import fj.data.Either;
+import javax.servlet.http.HttpServletRequest;
+import javax.xml.XMLConstants;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.parsers.SAXParserFactory;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.math.BigDecimal;
+import java.util.*;
+import java.util.Map.Entry;
+import java.util.function.Predicate;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
@org.springframework.stereotype.Component("artifactBusinessLogic")
public class ArtifactsBusinessLogic extends BaseBusinessLogic {
@@ -152,6 +120,21 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension";
private static final Logger log = LoggerFactory.getLogger(ArtifactsBusinessLogic.class);
+ public static final String FAILED_UPDATE_GROUPS = "Failed to update groups of the component {}. ";
+ public static final String FAILED_UPDATE_ARTIFACT = "Failed to delete or update the artifact {}. Parent uniqueId is {}";
+ public static final String FAILED_SAVE_ARTIFACT = "Failed to save the artifact.";
+ public static final String UPDATE_ARTIFACT_LOCK = "Update Artifact - lock ";
+ public static final String FAILED_DOWNLOAD_ARTIFACT = "Download artifact {} failed";
+ public static final String FAILED_UPLOAD_ARTIFACT_TO_COMPONENT = "Failed to upload artifact to component with type {} and uuid {}. Status is {}. ";
+ public static final String FAILED_UPLOAD_ARTIFACT_TO_INSTANCE = "Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ";
+ public static final String FAILED_FETCH_COMPONENT = "Could not fetch component with type {} and uuid {}. Status is {}. ";
+ public static final String NULL_PARAMETER = "One of the function parameteres is null";
+ public static final String COMPONENT_INSTANCE_NOT_FOUND = "Component instance {} was not found for component {}";
+ public static final String ROLLBACK = "all changes rollback";
+ public static final String COMMIT = "all changes committed";
+ public static final String ARTIFACT_SAVED = "Artifact saved into ES - {}";
+ public static final String UPDATE_ARTIFACT = "Update Artifact";
+ public static final String FOUND_DEPLOYMENT_ARTIFACT = "Found deployment artifact {}";
private Gson gson = new GsonBuilder().setPrettyPrinting().create();
@javax.annotation.Resource
@@ -555,7 +538,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
}
}
- Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, componentType, parentId, updatedGroupInstances);
+ Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, parentId, updatedGroupInstances);
if (status.isRight()) {
log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
return componentsUtils.convertFromStorageResponse(status.right().value());
@@ -713,15 +696,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
// step 4
// check user's role
- Either<User, ResponseFormat> userResult = validateUserExists(userId, "get artifacts", false);
- if (userResult.isRight()) {
-
- resultOp = Either.right(userResult.right().value());
- return resultOp;
- }
-
- userResult.left().value();
-
+ validateUserExists(userId, "get artifacts", false);
// steps 5 - 6 - 7
// 5. check service/resource existence
// 6. check service/resource check out
@@ -1002,16 +977,18 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat,
ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
- if (auditingActionEnum != null && auditingActionEnum.getAuditingEsType()
- .equals(AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE)) {
+ if (componentsUtils.isExternalApiEvent(auditingActionEnum)) {
return;
}
- String artifactData = buildAuditingArtifactData(artifactDefinition);
if (user == null) {
user = new User();
user.setUserId("UNKNOWN");
}
+ handleInternalAuditEvent(auditingActionEnum, component, componentId, user, artifactDefinition, prevArtifactUuid, currentArtifactUuid, responseFormat, componentTypeEnum, resourceInstanceName);
+ }
+
+ private void handleInternalAuditEvent(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat, ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
switch (componentTypeEnum) {
case RESOURCE:
Resource resource = (Resource) component;
@@ -1021,9 +998,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
resource.setName(componentId);
}
componentsUtils.auditResource(responseFormat, user, resource, resource.getName(), auditingActionEnum,
- ResourceAuditData.newBuilder()
- .artifactUuid(prevArtifactUuid)
- .build(), currentArtifactUuid, artifactData);
+ ResourceVersionInfo.newBuilder()
+ .artifactUuid(prevArtifactUuid)
+ .build(), currentArtifactUuid, artifactDefinition);
break;
case SERVICE:
@@ -1033,20 +1010,29 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
service = new Service();
service.setName(componentId);
}
- componentsUtils.auditComponent(responseFormat, user, service, auditingActionEnum, ComponentTypeEnum.SERVICE,
- ResourceAuditData.newBuilder().artifactUuid(prevArtifactUuid).build(),
- ResourceAuditData.newBuilder().artifactUuid(currentArtifactUuid).build(),
- null, null, artifactData, null);
+ componentsUtils.auditComponent(responseFormat, user, service, auditingActionEnum, new ResourceCommonInfo(ComponentTypeEnum.SERVICE.getValue()),
+ ResourceVersionInfo.newBuilder()
+ .artifactUuid(prevArtifactUuid)
+ .build(),
+ ResourceVersionInfo.newBuilder()
+ .artifactUuid(currentArtifactUuid)
+ .build(),
+ null, artifactDefinition, null);
break;
case RESOURCE_INSTANCE:
if (resourceInstanceName == null) {
resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId);
}
- componentsUtils.auditComponent(responseFormat, user, component, auditingActionEnum, ComponentTypeEnum.RESOURCE_INSTANCE,
- ResourceAuditData.newBuilder().artifactUuid(prevArtifactUuid).build(),
- ResourceAuditData.newBuilder().artifactUuid(currentArtifactUuid).build(),
- resourceInstanceName, null, artifactData, null);
+ componentsUtils.auditComponent(responseFormat, user, component, auditingActionEnum,
+ new ResourceCommonInfo(resourceInstanceName, ComponentTypeEnum.RESOURCE_INSTANCE.getValue()),
+ ResourceVersionInfo.newBuilder()
+ .artifactUuid(prevArtifactUuid)
+ .build(),
+ ResourceVersionInfo.newBuilder()
+ .artifactUuid(currentArtifactUuid)
+ .build(),
+ null, artifactDefinition, null);
break;
default:
break;
@@ -1066,18 +1052,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return resourceInstanceName;
}
- public Map<AuditingFieldsKeysEnum, Object> createArtifactAuditingFields(ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid) {
- Map<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- // Putting together artifact info
- String artifactData = buildAuditingArtifactData(artifactDefinition);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, artifactData);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, prevArtifactUuid);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, currentArtifactUuid);
- return auditingFields;
- }
-
- // -----
-
private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) {
StringBuilder sb = new StringBuilder();
if (artifactDefinition != null) {
@@ -1444,7 +1418,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
.getRight()
.getGroupInstances());
if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
- Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(fetchedContainerComponent, componentType, parentId, updatedGroupInstances);
+ Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(fetchedContainerComponent, parentId, updatedGroupInstances);
if (status.isRight()) {
log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId());
responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status
@@ -1598,7 +1572,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
else if (cloneIsNeeded) {
log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId);
- result = artifactToscaOperation.deleteArtifactWithClonnigOnGraph(componentId, foundArtifact, parentType, instanceId, false);
+ result = artifactToscaOperation.deleteArtifactWithCloningOnGraph(componentId, foundArtifact, parentType, instanceId, false);
}
else {
log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId);
@@ -1836,6 +1810,84 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return isUnique;
}
+ boolean validateArtifactNameUniqueness(String componentId, Component parentComponent, ArtifactDefinition artifactInfo,
+ ComponentTypeEnum componentType) {
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = getArtifacts(componentType,
+ parentComponent, componentId, artifactInfo.getArtifactGroupType());
+ String artifactName = artifactInfo.getArtifactName();
+ if (artifacts.isLeft() && Objects.nonNull(artifacts.left().value())){
+ if (artifacts.left().value().values().stream()
+ .anyMatch(ad -> artifactName.equals(ad.getArtifactName())
+ //check whether it is the same artifact we hold (by label)
+ && !artifactInfo.getArtifactLabel().equals(ad.getArtifactLabel()))){
+ return false;
+ }
+ }
+ if (ComponentTypeEnum.RESOURCE.equals(componentType)) {
+ return isUniqueArtifactNameInResourceInterfaces(componentId, artifactName, artifactInfo.getArtifactLabel());
+ }
+ return true;
+ }
+
+ private boolean isUniqueArtifactNameInResourceInterfaces(String componentId, String artifactName, String artifactLabel) {
+ Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
+ .getAllInterfacesOfResource(componentId, true, true);
+
+ if (allInterfacesOfResource.isLeft() && Objects.nonNull(allInterfacesOfResource)){
+ return !allInterfacesOfResource.left().value()
+ .values()
+ .stream().map(InterfaceDefinition :: getOperationsMap)
+ .flatMap(map -> map.values().stream())
+ .map(OperationDataDefinition::getImplementation)
+ .filter(Objects::nonNull)
+ .anyMatch(add -> artifactName.equals(add.getArtifactName())
+ && !artifactLabel.equals(add.getArtifactLabel()));
+ }
+ return true;
+ }
+
+ private boolean isUniqueLabelInResourceInterfaces(String componentId, String artifactLabel) {
+ Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
+ .getAllInterfacesOfResource(componentId, true, true);
+
+ if (allInterfacesOfResource.isLeft()){
+ return !allInterfacesOfResource.left().value()
+ .values()
+ .stream().map(InterfaceDefinition :: getOperationsMap)
+ .flatMap(map -> map.values().stream())
+ .map(OperationDataDefinition::getImplementation)
+ .filter(Objects::nonNull)
+ .anyMatch(add -> artifactLabel.equals(add.getArtifactLabel()));
+ }
+ return true;
+ }
+
+ private Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(ComponentTypeEnum componentType, Component parentComponent,
+ String componentId, ArtifactGroupTypeEnum artifactGroupType) {
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsResponse;
+ if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
+ artifactsResponse = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
+ }
+ else {
+ artifactsResponse = artifactToscaOperation.getArtifacts(componentId);
+ }
+ if (artifactsResponse.isRight() && artifactsResponse.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
+ log.debug("failed to retrieve artifacts for {} ", componentId);
+ return Either.right(artifactsResponse.right().value());
+ }
+ return Either.left(artifactsResponse.left().value().entrySet()
+ .stream()
+ .filter(x -> artifactGroupType.equals(x.getValue().getArtifactGroupType()))
+ .collect(Collectors.toMap(Entry::getKey, Entry::getValue)));
+ }
+
+ private List<String> getListOfArtifactName(Map<String, ArtifactDefinition> artifacts) {
+ return artifacts.entrySet()
+ .stream()
+ .map(x -> x.getValue().getArtifactName())
+ .collect(Collectors.toList());
+ }
+
// ***************************************************************
private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createAndLinkArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, User user,
@@ -2292,8 +2344,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData));
Map<String, Object> heatToscaJson = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
- Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, ToscaTagNamesEnum.PARAMETERS);
- Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, ToscaTagNamesEnum.PARAMETERS);
+ Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS);
+ Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS);
if (eitherHeatEnvProperties.isRight()) {
ResponseFormat responseFormat = ResponseFormatManager.getInstance()
.getResponseFormat(ActionStatus.CORRUPTED_FORMAT, "Heat Env");
@@ -3703,16 +3755,18 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
private Either<User, ResponseFormat> validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) {
- Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, auditingAction.getName(), inTransaction);
-
- if (validateUserExists.isRight()) {
- User user = new User();
+ User user;
+ try{
+ user = validateUserExists(userId, auditingAction.getName(), inTransaction);
+ } catch(ComponentException e){
+ user = new User();
user.setUserId(userId);
- handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, validateUserExists.right()
- .value(), componentType, null);
- return Either.right(validateUserExists.right().value());
+ ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat() :
+ componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
+ handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
+ throw e;
}
- return Either.left(validateUserExists.left().value());
+ return Either.left(user);
}
protected AuditingActionEnum detectAuditingType(ArtifactOperationInfo operation, String origMd5) {
@@ -3907,7 +3961,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
gi.getGroupInstanceArtifacts().add(updatedArtDef.getUniqueId());
gi.getGroupInstanceArtifactsUuid().add(updatedArtDef.getArtifactUUID());
});
- Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, componentType, instanceId, updatedGroupInstances);
+ Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, instanceId, updatedGroupInstances);
if (status.isRight()) {
log.debug("Failed to update groups of the component {}. ", component.getUniqueId());
ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils
@@ -4638,16 +4692,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @param componentType
* @param componentUuid
* @param artifactUUID
- * @param auditAdditionalParam
+ * @param resourceCommonInfo
* @return
*/
- public Either<byte[], ResponseFormat> downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
+ public Either<byte[], ResponseFormat> downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo) {
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
Either<byte[], ResponseFormat> result;
byte[] downloadedArtifact = null;
Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
- if (errorWrapper.isEmpty()) {
- auditAdditionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
+ if (errorWrapper.isEmpty() && component != null) {
+ resourceCommonInfo.setResourceName(component.getName());
downloadedArtifact = downloadArtifact(component.getAllArtifacts(), artifactUUID, errorWrapper, component.getName());
}
if (errorWrapper.isEmpty()) {
@@ -4666,10 +4720,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @param componentUuid
* @param resourceInstanceName
* @param artifactUUID
- * @param auditAdditionalParam
* @return
*/
- public Either<byte[], ResponseFormat> downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
+ public Either<byte[], ResponseFormat> downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID) {
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
Either<byte[], ResponseFormat> result;
byte[] downloadedArtifact = null;
@@ -4694,12 +4747,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @param request
* @param componentType
* @param componentUuid
- * @param additionalParams
+ * @param resourceCommonInfo
* @param operation
* @return
*/
- public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, Map<AuditingFieldsKeysEnum, Object> additionalParams,
- ArtifactOperationInfo operation) {
+ public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, ResourceCommonInfo resourceCommonInfo,ArtifactOperationInfo operation) {
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
@@ -4713,7 +4765,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
if (getComponentRes.isRight()) {
StorageOperationStatus status = getComponentRes.right().value();
- log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
+ log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status);
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
}
if (errorWrapper.isEmpty()) {
@@ -4721,22 +4773,22 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
if (!getComponentRes.left()
- .value()
- .getMetadataDataDefinition()
- .getState()
- .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
+ .value()
+ .getMetadataDataDefinition()
+ .getState()
+ .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
if (component != null) {
componentId = component.getUniqueId();
componentName = component.getName();
}
}
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
+ resourceCommonInfo.setResourceName(componentName);
}
if (errorWrapper.isEmpty()) {
actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null);
if (actionResult.isRight()) {
- log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult
+ log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
.right()
.value());
errorWrapper.setInnerElement(actionResult.right().value());
@@ -4749,10 +4801,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
else {
uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
}
- updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
return uploadArtifactResult;
}
-
/**
* upload an artifact to a resource instance by UUID
*
@@ -4761,12 +4811,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @param componentType
* @param componentUuid
* @param resourceInstanceName
- * @param additionalParams
* @param operation
* @return
*/
public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
- Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
+ ArtifactOperationInfo operation) {
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
@@ -4823,7 +4872,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
else {
uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
}
- updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
return uploadArtifactResult;
}
@@ -4835,12 +4883,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @param componentType
* @param componentUuid
* @param artifactUUID
- * @param additionalParams
- * @param operation TODO
+ * @param operation
* @return
*/
public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID,
- Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
+ ResourceCommonInfo resourceCommonInfo, ArtifactOperationInfo operation) {
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
@@ -4873,7 +4920,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
componentName = component.getName();
}
}
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
+ resourceCommonInfo.setResourceName(componentName);
}
if (errorWrapper.isEmpty()) {
artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
@@ -4895,7 +4942,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
else {
updateArtifactResult = Either.right(errorWrapper.getInnerElement());
}
- updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
return updateArtifactResult;
}
@@ -4908,12 +4954,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @param componentUuid
* @param resourceInstanceName
* @param artifactUUID
- * @param additionalParams
* @param operation TODO
* @return
*/
public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
- Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
+ ArtifactOperationInfo operation) {
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
@@ -4975,7 +5020,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
else {
updateArtifactResult = Either.right(errorWrapper.getInnerElement());
}
- updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
return updateArtifactResult;
}
@@ -4987,14 +5031,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @param componentType
* @param componentUuid
* @param artifactUUID
- * @param additionalParams
* @param operation TODO
* @return
*/
public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnInterfaceOperationByResourceUUID(
String data, HttpServletRequest request, ComponentTypeEnum componentType,
String componentUuid, String artifactUUID, String operationUUID,
- Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
+ ResourceCommonInfo resourceCommonInfo,ArtifactOperationInfo operation) {
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
@@ -5023,8 +5066,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
componentId = component.getUniqueId();
componentName = component.getName();
}
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
+
}
+ resourceCommonInfo.setResourceName(componentName);
}
if (errorWrapper.isEmpty()) {
Either<String, ResponseFormat> interfaceName = fetchInterfaceName(componentId);
@@ -5051,7 +5095,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
else {
updateArtifactResult = Either.right(errorWrapper.getInnerElement());
}
- updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
return updateArtifactResult;
}
@@ -5078,11 +5121,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @param componentType
* @param componentUuid
* @param artifactUUID
- * @param additionalParams
+ * @param resourceCommonInfo
* @param operation TODO
* @return
*/
- public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> additionalParams,
+ public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo,
ArtifactOperationInfo operation) {
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
@@ -5115,7 +5158,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
componentName = component.getName();
}
}
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
+ resourceCommonInfo.setResourceName(componentName);
}
if (errorWrapper.isEmpty()) {
artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
@@ -5136,7 +5179,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
else {
deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
}
- updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
return deleteArtifactResult;
}
@@ -5148,12 +5190,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* @param componentUuid
* @param resourceInstanceName
* @param artifactUUID
- * @param additionalParams
* @param operation TODO
* @return
*/
public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
- Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
+ ArtifactOperationInfo operation) {
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
@@ -5214,7 +5255,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
else {
deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
}
- updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
return deleteArtifactResult;
}
@@ -5296,15 +5336,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
artifactToscaOperation.generateUUID(heatEnvPlaceholder, heatEnvPlaceholder.getArtifactVersion());
setHeatCurrentValuesOnHeatEnvDefaultValues(heatArtifact, heatEnvPlaceholder);
}
- String artifactData = buildAuditingArtifactData(heatEnvPlaceholder);
+
ComponentTypeEnum componentType = component.getComponentType();
if (parentType == NodeTypeEnum.ResourceInstance) {
componentType = ComponentTypeEnum.RESOURCE_INSTANCE;
}
- componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, AuditingActionEnum.ARTIFACT_UPLOAD, componentType,
- ResourceAuditData.newBuilder().build(),
- ResourceAuditData.newBuilder().artifactUuid(heatEnvPlaceholder.getUniqueId()).build(),
- parentName, null, artifactData, null);
+ componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, AuditingActionEnum.ARTIFACT_UPLOAD,
+ new ResourceCommonInfo(parentName, componentType.getValue()),
+ ResourceVersionInfo.newBuilder().build(),
+ ResourceVersionInfo.newBuilder().artifactUuid(heatEnvPlaceholder.getUniqueId()).build(),
+ null, heatEnvPlaceholder, null);
return Either.left(heatEnvPlaceholder);
}
@@ -5608,21 +5649,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return component;
}
- private void updateAuditParametersWithArtifactDefinition(Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactDefinition artifact) {
- if (artifact == null) {
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, "");
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, "");
- if (!additionalParams.containsKey(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID)) {
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, "");
- }
- }
- else {
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifact.getArtifactUUID());
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, buildAuditingArtifactData(artifact));
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, artifact.getUpdaterFullName());
- }
- }
-
private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) {
Map<String, Object> json = new HashMap<>();
String artifactName = artifact.getArtifactName();
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java
index bc813b9abb..ef0cd463db 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java
@@ -20,26 +20,23 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Optional;
-
+import fj.data.Either;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
+import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
-import fj.data.Either;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
/**
* This class holds the business logic relevant for attributes manipulation.
@@ -54,7 +51,8 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
private static final String UPDATE_ATTRIBUTE = "UpdateAttribute";
private static final String DELETE_ATTRIBUTE = "DeleteAttribute";
- private static final Logger log = LoggerFactory.getLogger(AttributeBusinessLogic.class);
+ private static final Logger log = Logger.getLogger(AttributeBusinessLogic.class.getName());
+ private static final String FAILED_TO_LOCK_COMPONENT_ERROR = "Failed to lock component {}. Error - {}";
/**
* Created attribute on the resource with resourceId
@@ -66,15 +64,12 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
*/
public Either<PropertyDefinition, ResponseFormat> createAttribute(String resourceId, PropertyDefinition newAttributeDef, String userId) {
Either<PropertyDefinition, ResponseFormat> result = null;
- Either<User, ResponseFormat> resp = validateUserExists(userId, "create Attribute", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "create Attribute", false);
StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource);
if (lockResult != StorageOperationStatus.OK) {
BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId);
- log.info("Failed to lock component {}. Error - {}", resourceId, lockResult);
+ log.info(FAILED_TO_LOCK_COMPONENT_ERROR, resourceId, lockResult);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
@@ -128,7 +123,7 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
private boolean isAttributeExist(List<PropertyDefinition> attributes, String resourceUid, String propertyName) {
boolean isExist = false;
if (attributes != null) {
- isExist = attributes.stream().filter(p -> Objects.equals(p.getName(), propertyName) && Objects.equals(p.getParentUniqueId(), resourceUid)).findAny().isPresent();
+ isExist = attributes.stream().anyMatch(p -> Objects.equals(p.getName(), propertyName) && Objects.equals(p.getParentUniqueId(), resourceUid));
}
return isExist;
@@ -142,10 +137,7 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
*/
public Either<PropertyDefinition, ResponseFormat> getAttribute(String resourceId, String attributeId, String userId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Attribute", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "get Attribute", false);
// Get the resource from DB
Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId);
@@ -158,16 +150,9 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
if (attributes == null) {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_NOT_FOUND, ""));
} else {
- Either<PropertyDefinition, ResponseFormat> result;
// verify attribute exist in resource
Optional<PropertyDefinition> optionalAtt = attributes.stream().filter(att -> att.getUniqueId().equals(attributeId) && att.getParentUniqueId().equals(resourceId)).findAny();
-
- if (optionalAtt.isPresent()) {
- result = Either.left(optionalAtt.get());
- } else {
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_NOT_FOUND, ""));
- }
- return result;
+ return optionalAtt.<Either<PropertyDefinition, ResponseFormat>>map(Either::left).orElseGet(() -> Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_NOT_FOUND, "")));
}
}
@@ -187,7 +172,7 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource);
if (lockResult != StorageOperationStatus.OK) {
BeEcompErrorManager.getInstance().logBeFailedLockObjectError(UPDATE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId);
- log.info("Failed to lock component {}. Error - {}", resourceId, lockResult);
+ log.info(FAILED_TO_LOCK_COMPONENT_ERROR, resourceId, lockResult);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
try {
@@ -256,15 +241,12 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
Either<PropertyDefinition, ResponseFormat> result = null;
- Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Attribute", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "delete Attribute", false);
StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource);
if (lockResult != StorageOperationStatus.OK) {
BeEcompErrorManager.getInstance().logBeFailedLockObjectError(DELETE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId);
- log.info("Failed to lock component {}. Error - {}", resourceId, lockResult);
+ log.info(FAILED_TO_LOCK_COMPONENT_ERROR, resourceId, lockResult);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java
index 4b15081968..e7ae0612f4 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java
@@ -20,16 +20,10 @@
package org.openecomp.sdc.be.components.impl;
-import static org.apache.commons.collections.CollectionUtils.isEmpty;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.function.Function;
-
-import org.apache.commons.lang3.StringUtils;
+import com.google.gson.JsonElement;
+import fj.data.Either;
import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
import org.openecomp.sdc.be.components.validation.UserValidations;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
@@ -43,26 +37,12 @@ import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstanceInput;
-import org.openecomp.sdc.be.model.ComponentInstanceProperty;
-import org.openecomp.sdc.be.model.ComponentParametersView;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.GroupProperty;
-import org.openecomp.sdc.be.model.IComplexDefaultValue;
-import org.openecomp.sdc.be.model.IPropertyInputCommon;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
import org.openecomp.sdc.be.model.jsontitan.operations.ArtifactsOperations;
-import org.openecomp.sdc.be.model.jsontitan.operations.ForwardingPathOperation;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
-import org.openecomp.sdc.be.model.operations.api.IElementOperation;
-import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
-import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
-import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
-import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.StorageException;
+import org.openecomp.sdc.be.model.operations.api.*;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
import org.openecomp.sdc.be.model.operations.impl.PolicyTypeOperation;
import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
@@ -71,27 +51,29 @@ import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter;
import org.openecomp.sdc.be.model.tosca.validators.DataTypeValidatorConverter;
import org.openecomp.sdc.be.model.tosca.validators.PropertyTypeValidator;
-import org.openecomp.sdc.be.resources.data.PropertyValueData;
import org.openecomp.sdc.be.user.IUserBusinessLogic;
import org.openecomp.sdc.be.user.Role;
import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.datastructure.Wrapper;
-import org.openecomp.sdc.common.util.ValidationUtils;
+import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import com.google.gson.JsonElement;
-
-import fj.data.Either;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Function;
public abstract class BaseBusinessLogic {
- private static final Logger log = LoggerFactory.getLogger(BaseBusinessLogic.class);
+ private static final String FAILED_TO_LOCK_COMPONENT_ERROR = "Failed to lock component {} error - {}";
+
+ private static final Logger log = Logger.getLogger(BaseBusinessLogic.class.getName());
private static final String EMPTY_VALUE = null;
+ private static final String SCHEMA_DOESN_T_EXISTS_FOR_PROPERTY_OF_TYPE = "Schema doesn't exists for property of type {}";
+ private static final String PROPERTY_IN_SCHEMA_DEFINITION_INSIDE_PROPERTY_OF_TYPE_DOESN_T_EXIST = "Property in Schema Definition inside property of type {} doesn't exist";
+ private static final String ADD_PROPERTY_VALUE = "Add property value";
@Autowired
protected ComponentsUtils componentsUtils;
@@ -114,7 +96,7 @@ public abstract class BaseBusinessLogic {
protected IGroupOperation groupOperation;
@Autowired
- protected IGroupInstanceOperation groupInstanceOperation;
+ IGroupInstanceOperation groupInstanceOperation;
@Autowired
protected IGroupTypeOperation groupTypeOperation;
@@ -123,7 +105,7 @@ public abstract class BaseBusinessLogic {
protected GroupBusinessLogic groupBusinessLogic;
@Autowired
- protected PolicyTypeOperation policyTypeOperation;
+ PolicyTypeOperation policyTypeOperation;
@javax.annotation.Resource
protected ArtifactsOperations artifactToscaOperation;
@@ -140,13 +122,10 @@ public abstract class BaseBusinessLogic {
@Autowired
protected ApplicationDataTypeCache dataTypeCache;
- @Autowired
- protected ForwardingPathOperation forwardingPathOperation;
-
@javax.annotation.Resource
private UserValidations userValidations;
- protected DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance();
+ DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance();
public void setUserAdmin(UserBusinessLogic userAdmin) {
@@ -169,15 +148,6 @@ public abstract class BaseBusinessLogic {
this.toscaOperationFacade = toscaOperationFacade;
}
- public void setForwardingPathOperation(ForwardingPathOperation forwardingPathOperation){
- this.forwardingPathOperation = forwardingPathOperation;
- }
-
- public void setPolicyTypeOperation(PolicyTypeOperation policyTypeOperation) {
- this.policyTypeOperation = policyTypeOperation;
- }
-
-
public void setDataTypeCache(ApplicationDataTypeCache dataTypeCache) {
this.dataTypeCache = dataTypeCache;
}
@@ -186,28 +156,28 @@ public abstract class BaseBusinessLogic {
this.propertyOperation = propertyOperation;
}
- protected Either<User, ResponseFormat> validateUserNotEmpty(User user, String ecompErrorContext) {
+ User validateUserNotEmpty(User user, String ecompErrorContext) {
return userValidations.validateUserNotEmpty(user, ecompErrorContext);
}
- protected Either<User, ResponseFormat> validateUserExists(User user, String ecompErrorContext, boolean inTransaction) {
+ protected User validateUserExists(User user, String ecompErrorContext, boolean inTransaction) {
return userValidations.validateUserExists(user.getUserId(), ecompErrorContext, inTransaction);
}
- protected void validateUserExist(String userId, String ecompErrorContext, Wrapper<ResponseFormat> errorWrapper) {
- userValidations.validateUserExist(userId, ecompErrorContext, errorWrapper);
+ void validateUserExist(String userId, String ecompErrorContext) {
+ userValidations.validateUserExist(userId, ecompErrorContext);
}
- public Either<User, ActionStatus> validateUserExistsActionStatus(String userId, String ecompErrorContext) {
+ Either<User, ActionStatus> validateUserExistsActionStatus(String userId, String ecompErrorContext) {
return userValidations.validateUserExistsActionStatus(userId, ecompErrorContext);
}
- public Either<User, ResponseFormat> validateUserExists(String userId, String ecompErrorContext, boolean inTransaction) {
+ public User validateUserExists(String userId, String ecompErrorContext, boolean inTransaction) {
return userValidations.validateUserExists(userId, ecompErrorContext, inTransaction);
}
- protected Either<Boolean, ResponseFormat> validateUserRole(User user, List<Role> roles) {
- return userValidations.validateUserRole(user, roles);
+ protected void validateUserRole(User user, List<Role> roles) {
+ userValidations.validateUserRole(user, roles);
}
protected Either<Boolean, ResponseFormat> lockComponent(Component component, String ecompErrorContext) {
@@ -220,6 +190,31 @@ public abstract class BaseBusinessLogic {
}
protected Either<Boolean, ResponseFormat> lockComponent(String componentId, Component component, String ecompErrorContext) {
+ return lockElement( componentId, component, ecompErrorContext)
+ .right()
+ .map(r -> logAndConvertError(r, component.getUniqueId(), component.getName()) );
+ }
+
+ protected void lockComponent(String componentId, Component component, boolean needLock, String ecompErrorContext) {
+ if (needLock){
+ lockElement( componentId, component, ecompErrorContext)
+ .left()
+ .on(r -> logAndThrowException(r, component.getUniqueId(), component.getName()) );
+ }
+ }
+
+ private Boolean logAndThrowException(ActionStatus status, String componentId, String name){
+ log.debug(FAILED_TO_LOCK_COMPONENT_ERROR, componentId, status);
+ throw new ComponentException(status, name);
+ }
+
+ private ResponseFormat logAndConvertError(ActionStatus status, String componentId, String name){
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, name);
+ log.debug(FAILED_TO_LOCK_COMPONENT_ERROR, componentId, status);
+ return responseFormat;
+ }
+
+ private Either<Boolean, ActionStatus> lockElement(String componentId, Component component, String ecompErrorContext) {
ComponentTypeEnum componentType = component.getComponentType();
NodeTypeEnum nodeType = componentType.getNodeType();
StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponent(componentId, nodeType);
@@ -229,9 +224,7 @@ public abstract class BaseBusinessLogic {
} else {
BeEcompErrorManager.getInstance().logBeFailedLockObjectError(ecompErrorContext, nodeType.getName(), componentId);
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(lockResourceStatus, componentType);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, component.getName());
- log.debug("Failed to lock component {} error - {}", componentId, actionStatus);
- return Either.right(responseFormat);
+ return Either.right(actionStatus);
}
}
@@ -252,14 +245,14 @@ public abstract class BaseBusinessLogic {
protected void unlockComponent(Either<?, ?> either, Component component) {
unlockComponent(either, component, false);
}
- protected void unlockComponentById(Either<?, ?> either, String componentId) {
+ void unlockComponentById(Either<?, ?> either, String componentId) {
Either<Component, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(componentId);
- if(component.isLeft() && component != null) {
+ if(component.isLeft()) {
unlockComponent(either, component.left().value(), false);
}
}
- protected <T> Either<Boolean, ResponseFormat> validateJsonBody(T bodyObject, Class<T> clazz) {
+ <T> Either<Boolean, ResponseFormat> validateJsonBody(T bodyObject, Class<T> clazz) {
if (bodyObject == null) {
log.debug("Invalid JSON received for object of type {}", clazz.getSimpleName());
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
@@ -268,7 +261,7 @@ public abstract class BaseBusinessLogic {
}
}
- protected Either<ComponentTypeEnum, ResponseFormat> validateComponentType(String componentType) {
+ Either<ComponentTypeEnum, ResponseFormat> validateComponentType(String componentType) {
ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
if (componentTypeEnum == null) {
log.debug("Invalid component type {}", componentType);
@@ -279,10 +272,7 @@ public abstract class BaseBusinessLogic {
}
protected Either<Component, ResponseFormat> validateComponentExists(String componentId, ComponentTypeEnum componentType, ComponentParametersView filter) {
- if (filter == null) {
- filter = new ComponentParametersView();
- }
- return toscaOperationFacade.getToscaElement(componentId, filter)
+ return toscaOperationFacade.getToscaElement(componentId, filter == null ? new ComponentParametersView() : filter)
.right()
.map(err -> handleGetComponentError(componentId, componentType, err))
.left()
@@ -298,7 +288,7 @@ public abstract class BaseBusinessLogic {
return Either.left(cmpt);
}
- protected <T extends PropertyDataDefinition> Either<String, ResponseFormat> updatePropertyObjectValue(T property, boolean isInput) {
+ <T extends PropertyDataDefinition> Either<String, ResponseFormat> updateInputPropertyObjectValue(T property) {
Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypesEither = dataTypeCache.getAll();
if (allDataTypesEither.isRight()) {
TitanOperationStatus status = allDataTypesEither.right().value();
@@ -306,24 +296,8 @@ public abstract class BaseBusinessLogic {
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
}
Map<String, DataTypeDefinition> allDataTypes = allDataTypesEither.left().value();
- String innerType = null;
String propertyType = property.getType();
- ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
- log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
-
- if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
- SchemaDefinition def = property.getSchema();
- if (def == null) {
- log.debug("Schema doesn't exists for property of type {}", type);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
- }
- PropertyDataDefinition propDef = def.getProperty();
- if (propDef == null) {
- log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
- }
- innerType = propDef.getType();
- }
+ String innerType = getInnerType(property);
// Specific Update Logic
Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes);
String newValue = property.getValue();
@@ -338,14 +312,26 @@ public abstract class BaseBusinessLogic {
newValue = object.toString();
}
}
- if (!isInput) {
- ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
- if (Boolean.FALSE.equals(pair.getRight())) {
- BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
+ return Either.left(newValue);
+ }
+
+ private <T extends PropertyDataDefinition> String getInnerType(T property){
+ ToscaPropertyType type = ToscaPropertyType.isValidType(property.getType());
+ log.debug("#getInnerType - The type of the property {} is {}", property.getUniqueId(), property.getType());
+ String innerType = null;
+ if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
+ if (property.getSchema() == null) {
+ log.debug(SCHEMA_DOESN_T_EXISTS_FOR_PROPERTY_OF_TYPE, type);
+ throw new ComponentException(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE));
}
+ PropertyDataDefinition innerProperty = property.getSchema().getProperty();
+ if (innerProperty == null) {
+ log.debug(PROPERTY_IN_SCHEMA_DEFINITION_INSIDE_PROPERTY_OF_TYPE_DOESN_T_EXIST, type);
+ throw new ComponentException(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE));
+ }
+ innerType = innerProperty.getType();
}
- return Either.left(newValue);
+ return innerType;
}
public Either<Boolean, ResponseFormat> validateCanWorkOnComponent(Component component, String userId) {
@@ -377,7 +363,7 @@ public abstract class BaseBusinessLogic {
return Either.left(true);
}
- public ComponentTypeEnum getComponentTypeByParentComponentType(ComponentTypeEnum parentComponentType) {
+ ComponentTypeEnum getComponentTypeByParentComponentType(ComponentTypeEnum parentComponentType) {
switch (parentComponentType) {
case SERVICE:
return ComponentTypeEnum.RESOURCE;
@@ -411,8 +397,8 @@ public abstract class BaseBusinessLogic {
return Either.left(allDataTypes.left().value());
}
- protected Either<Boolean, ResponseFormat> validatePropertyDefaultValue(IComplexDefaultValue property, Map<String, DataTypeDefinition> dataTypes) {
- String type = null;
+ Either<Boolean, ResponseFormat> validatePropertyDefaultValue(IComplexDefaultValue property, Map<String, DataTypeDefinition> dataTypes) {
+ String type;
String innerType = null;
if (!propertyOperation.isPropertyTypeValid(property)) {
log.info("Invalid type for property {} type {}", property.getName(), property.getType());
@@ -423,7 +409,7 @@ public abstract class BaseBusinessLogic {
if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property, dataTypes);
innerType = propertyInnerTypeValid.getLeft();
- if (!propertyInnerTypeValid.getRight().booleanValue()) {
+ if (!propertyInnerTypeValid.getRight()) {
log.info("Invalid inner type for property {} type {}", property.getName(), property.getType());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
return Either.right(responseFormat);
@@ -444,30 +430,28 @@ public abstract class BaseBusinessLogic {
}
- protected void handleDefaultValue(IComplexDefaultValue newAttributeDef, Map<String, DataTypeDefinition> dataTypes) {
+ void handleDefaultValue(IComplexDefaultValue newAttributeDef, Map<String, DataTypeDefinition> dataTypes) {
// convert property
ToscaPropertyType type = ToscaPropertyType.isValidType(newAttributeDef.getType());
PropertyValueConverter converter = type.getConverter();
// get inner type
String innerType = null;
- if (newAttributeDef != null) {
- SchemaDefinition schema = newAttributeDef.getSchema();
- if (schema != null) {
- PropertyDataDefinition prop = schema.getProperty();
- if (schema.getProperty() != null) {
- innerType = prop.getType();
- }
- }
- String convertedValue = null;
- if (newAttributeDef.getDefaultValue() != null) {
- convertedValue = converter.convert(newAttributeDef.getDefaultValue(), innerType, dataTypes);
- newAttributeDef.setDefaultValue(convertedValue);
+ SchemaDefinition schema = newAttributeDef.getSchema();
+ if (schema != null) {
+ PropertyDataDefinition prop = schema.getProperty();
+ if (schema.getProperty() != null) {
+ innerType = prop.getType();
}
}
+ String convertedValue;
+ if (newAttributeDef.getDefaultValue() != null) {
+ convertedValue = converter.convert(newAttributeDef.getDefaultValue(), innerType, dataTypes);
+ newAttributeDef.setDefaultValue(convertedValue);
+ }
}
- protected void validateComponentTypeEnum(ComponentTypeEnum componentTypeEnum, String errorContext, Wrapper<ResponseFormat> errorWrapper) {
+ void validateComponentTypeEnum(ComponentTypeEnum componentTypeEnum, String errorContext, Wrapper<ResponseFormat> errorWrapper) {
if (componentTypeEnum == null) {
BeEcompErrorManager.getInstance().logInvalidInputError(errorContext, "invalid component type", ErrorSeverity.INFO);
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
@@ -483,7 +467,7 @@ public abstract class BaseBusinessLogic {
}
- protected void validateComponentLock(String componentId, ComponentTypeEnum componentTypeEnum, Wrapper<ResponseFormat> errorWrapper) {
+ void validateComponentLock(String componentId, ComponentTypeEnum componentTypeEnum, Wrapper<ResponseFormat> errorWrapper) {
StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
if (lockStatus != StorageOperationStatus.OK) {
log.debug("Failed to lock {} {}", componentTypeEnum.getValue(), componentId);
@@ -496,7 +480,7 @@ public abstract class BaseBusinessLogic {
return ToscaPropertyType.isValidType(propertyType);
}
- protected void commitOrRollback(Either<? extends Object, ResponseFormat> result) {
+ void commitOrRollback(Either<?, ResponseFormat> result) {
if (result == null || result.isRight()) {
log.warn("operation failed. do rollback");
titanDao.rollback();
@@ -517,7 +501,7 @@ public abstract class BaseBusinessLogic {
BeEcompErrorManager.getInstance().logBeFailedLockObjectError(ecompErrorContext, nodeType.getName(), name);
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(lockResourceStatus, componentType);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, component.getName());
- log.debug("Failed to lock component {} error - {}", name, actionStatus);
+ log.debug(FAILED_TO_LOCK_COMPONENT_ERROR, name, actionStatus);
return Either.right(responseFormat);
}
}
@@ -531,66 +515,26 @@ public abstract class BaseBusinessLogic {
private ResponseFormat handleGetComponentError(String componentId, ComponentTypeEnum componentType, StorageOperationStatus getComponentError) {
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentError, componentType);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, componentId);
log.debug("error fetching component with id {}. error status: {}", componentId, getComponentError);
return responseFormat;
}
- protected Either<GroupProperty, ResponseFormat> validateFreeText(GroupProperty groupPropertyToUpdate) {
-
- Either<GroupProperty, ResponseFormat> ret;
- final String groupTypeValue = groupPropertyToUpdate.getValue();
- if (!StringUtils.isEmpty(groupTypeValue)) {
- if (!ValidationUtils.validateDescriptionLength(groupTypeValue)) {
- ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT,
- NodeTypeEnum.Property.getName(),
- String.valueOf(ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH)));
- } else if (!ValidationUtils.validateIsEnglish(groupTypeValue)) {
- ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_DESCRIPTION,
- NodeTypeEnum.Property.getName()));
- } else {
- ret = Either.left(groupPropertyToUpdate);
- }
-
- } else {
- ret = Either.left(groupPropertyToUpdate);
- }
- return ret;
- }
-
-
@SafeVarargs
static <T extends Enum<T>> boolean enumHasValueFilter(String name, Function<String, T> enumGetter, T... enumValues) {
T enumFound = enumGetter.apply(name);
return Arrays.asList(enumValues).contains(enumFound);
}
- Either<String, StorageOperationStatus> validatePropValueBeforeCreate(IPropertyInputCommon property, String value, boolean isValidate, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
+ String validatePropValueBeforeCreate(IPropertyInputCommon property, String value, boolean isValidate, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
String propertyType = property.getType();
- ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
-
- if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
- SchemaDefinition def = property.getSchema();
- if (def == null) {
- log.debug("Schema doesn't exists for property of type {}", type);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
- }
- PropertyDataDefinition propDef = def.getProperty();
- if (propDef == null) {
- log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
-
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
- }
- innerType = propDef.getType();
- }
-
- Either<Object, Boolean> isValid = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, allDataTypes);
-
+ String updatedInnerType = updateInnerType(property, innerType);
+ Either<Object, Boolean> isValid = validateAndUpdatePropertyValue(propertyType, value, isValidate, updatedInnerType, allDataTypes);
String newValue = value;
if (isValid.isRight()) {
Boolean res = isValid.right().value();
if (Boolean.FALSE.equals(res)) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
+ throw new StorageException(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
}
} else {
Object object = isValid.left().value();
@@ -598,59 +542,37 @@ public abstract class BaseBusinessLogic {
newValue = object.toString();
}
}
-
- ImmutablePair<String, Boolean> pair = validateAndUpdateRules(propertyType, property.getRules(), innerType, allDataTypes, isValidate);
+ ImmutablePair<String, Boolean> pair = validateAndUpdateRules(propertyType, property.getRules(), updatedInnerType, allDataTypes, isValidate);
log.trace("After validateAndUpdateRules. pair = {}", pair);
if (Boolean.FALSE.equals(pair.getRight())) {
- BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
+ BeEcompErrorManager.getInstance().logBeInvalidValueError(ADD_PROPERTY_VALUE, pair.getLeft(), property.getName(), propertyType);
+ throw new StorageException(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
}
-
- return Either.left(newValue);
+ return newValue;
}
- protected Either<String, StorageOperationStatus> validateInputValueBeforeCreate(ComponentInstanceInput property, String value, boolean isValidate, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
- String propertyType = property.getType();
- ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
-
+ private String updateInnerType(IPropertyInputCommon property, String innerType) {
+ ToscaPropertyType type = ToscaPropertyType.isValidType(property.getType());
if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
SchemaDefinition def = property.getSchema();
if (def == null) {
- log.debug("Schema doesn't exists for property of type {}", type);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
+ log.debug(SCHEMA_DOESN_T_EXISTS_FOR_PROPERTY_OF_TYPE, type);
+ failOnIllegalArgument();
}
PropertyDataDefinition propDef = def.getProperty();
if (propDef == null) {
- log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
-
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
- }
- innerType = propDef.getType();
- }
-
- Either<Object, Boolean> isValid = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, allDataTypes);
-
- String newValue = value;
- if (isValid.isRight()) {
- Boolean res = isValid.right().value();
- if (Boolean.FALSE.equals(res)) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
- }
- } else {
- Object object = isValid.left().value();
- if (object != null) {
- newValue = object.toString();
+ log.debug(PROPERTY_IN_SCHEMA_DEFINITION_INSIDE_PROPERTY_OF_TYPE_DOESN_T_EXIST, type);
+ failOnIllegalArgument();
}
+ return propDef.getType();
}
+ return innerType;
+ }
- ImmutablePair<String, Boolean> pair = validateAndUpdateRules(propertyType, property.getRules(), innerType, allDataTypes, isValidate);
- log.debug("After validateAndUpdateRules. pair = {}", pair);
- if (Boolean.FALSE.equals(pair.getRight())) {
- BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
- }
-
- return Either.left(newValue);
+ private void failOnIllegalArgument() {
+ throw new ComponentException(
+ componentsUtils.convertFromStorageResponse(
+ DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)));
}
public Either<Object, Boolean> validateAndUpdatePropertyValue(String propertyType, String value, boolean isValidate, String innerType, Map<String, DataTypeDefinition> dataTypes) {
@@ -685,7 +607,7 @@ public abstract class BaseBusinessLogic {
return Either.left(convertedValue);
}
- public ImmutablePair<String, Boolean> validateAndUpdateRules(String propertyType, List<PropertyRule> rules, String innerType, Map<String, DataTypeDefinition> dataTypes, boolean isValidate) {
+ private ImmutablePair<String, Boolean> validateAndUpdateRules(String propertyType, List<PropertyRule> rules, String innerType, Map<String, DataTypeDefinition> dataTypes, boolean isValidate) {
if (rules == null || rules.isEmpty()) {
return ImmutablePair.of(null, true);
@@ -723,72 +645,21 @@ public abstract class BaseBusinessLogic {
}
public boolean isEmptyValue(String value) {
- if (value == null) {
- return true;
- }
- return false;
- }
-
- public boolean isNullParam(String value) {
- if (value == null) {
- return true;
- }
- return false;
- }
-
- public void addRulesToNewPropertyValue(PropertyValueData propertyValueData, ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId) {
-
- List<PropertyRule> rules = resourceInstanceProperty.getRules();
- if (rules == null) {
- PropertyRule propertyRule = buildRuleFromPath(propertyValueData, resourceInstanceProperty, resourceInstanceId);
- rules = new ArrayList<>();
- rules.add(propertyRule);
- } else {
- rules = sortRules(rules);
- }
-
- propertyValueData.setRules(rules);
- }
-
- private PropertyRule buildRuleFromPath(PropertyValueData propertyValueData, ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId) {
- List<String> path = resourceInstanceProperty.getPath();
- // FOR BC. Since old Property values on VFC/VF does not have rules on
- // graph.
- // Update could be done on one level only, thus we can use this
- // operation to avoid migration.
- if (isEmpty(path)) {
- path = new ArrayList<>();
- path.add(resourceInstanceId);
- }
- PropertyRule propertyRule = new PropertyRule();
- propertyRule.setRule(path);
- propertyRule.setValue(propertyValueData.getValue());
- return propertyRule;
- }
-
- private List<PropertyRule> sortRules(List<PropertyRule> rules) {
-
- // TODO: sort the rules by size and binary representation.
- // (x, y, .+) --> 110 6 priority 1
- // (x, .+, z) --> 101 5 priority 2
-
- return rules;
+ return value == null;
}
protected String getValueFromJsonElement(JsonElement jsonElement) {
- String value = null;
-
if (jsonElement == null || jsonElement.isJsonNull()) {
- value = EMPTY_VALUE;
- } else {
- if (jsonElement.toString().isEmpty()) {
- value = "";
- } else {
- value = jsonElement.toString();
- }
+ return EMPTY_VALUE;
}
-
- return value;
+ if (jsonElement.toString().isEmpty()) {
+ return "";
+ }
+ return jsonElement.toString();
+ }
+
+ protected void rollbackWithException(ActionStatus actionStatus, String... params) {
+ titanDao.rollback();
+ throw new ComponentException(actionStatus, params);
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManager.java
index b350c7b4c9..b54a8050ce 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManager.java
@@ -20,85 +20,65 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.function.Consumer;
-
-import javax.annotation.Resource;
-
-import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import fj.data.Either;
+import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation;
+import org.openecomp.sdc.be.model.utils.TypeCompareUtils;
+import org.openecomp.sdc.be.utils.TypeUtils;
+import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
-import fj.data.Either;
+import java.util.List;
+import java.util.Map;
@Component("capabilityTypeImportManager")
public class CapabilityTypeImportManager {
- private static final Logger log = LoggerFactory.getLogger(CapabilityTypeImportManager.class);
- @Resource
- private CapabilityTypeOperation capabilityTypeOperation;
- @Resource
- private ComponentsUtils componentsUtils;
- @Resource
- private CommonImportManager commonImportManager;
-
- public Either<List<CapabilityTypeDefinition>, ResponseFormat> createCapabilityTypes(String capabilityYml) {
- Either<List<CapabilityTypeDefinition>, ActionStatus> capabilityTypes = createCapabilityTypesFromYml(capabilityYml);
- if (capabilityTypes.isRight()) {
- ActionStatus status = capabilityTypes.right().value();
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByCapabilityType(status, null);
- return Either.right(responseFormat);
- }
- return createCapabilityTypesByDao(capabilityTypes.left().value());
+ private static final Logger log = Logger.getLogger(CapabilityTypeImportManager.class.getName());
+ private final CapabilityTypeOperation capabilityTypeOperation;
+ private final CommonImportManager commonImportManager;
+
+ public CapabilityTypeImportManager(CapabilityTypeOperation capabilityTypeOperation, CommonImportManager commonImportManager) {
+ this.capabilityTypeOperation = capabilityTypeOperation;
+ this.commonImportManager = commonImportManager;
}
- private Either<List<CapabilityTypeDefinition>, ActionStatus> createCapabilityTypesFromYml(String capabilityYml) {
- return commonImportManager.createElementTypesFromYml(capabilityYml, (capTypeName, capTypeJsonData) -> createCapabilityType(capTypeName, capTypeJsonData));
+ public Either<List<ImmutablePair<CapabilityTypeDefinition, Boolean>>, ResponseFormat> createCapabilityTypes(String capabilityTypesYml) {
+ return commonImportManager.createElementTypes(capabilityTypesYml, this::createCapabilityTypesFromYml, this::upsertCapabilityTypesByDao, CommonImportManager.ElementTypeEnum.CAPABILITY_TYPE);
}
- private Either<List<CapabilityTypeDefinition>, ResponseFormat> createCapabilityTypesByDao(List<CapabilityTypeDefinition> capabilityTypesToCreate) {
- List<CapabilityTypeDefinition> createdCapabilities = new ArrayList<>();
- Either<List<CapabilityTypeDefinition>, ResponseFormat> eitherResult = Either.left(createdCapabilities);
- Iterator<CapabilityTypeDefinition> capTypeItr = capabilityTypesToCreate.iterator();
- boolean stopDao = false;
- while (capTypeItr.hasNext() && !stopDao) {
- CapabilityTypeDefinition capabilityType = capTypeItr.next();
-
- log.info("send capabilityType {} to dao for create", capabilityType.getType());
- Either<CapabilityTypeDefinition, StorageOperationStatus> dataModelResponse = capabilityTypeOperation.addCapabilityType(capabilityType);
- if (dataModelResponse.isRight()) {
- BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError("Create CapabilityTypes", "capability type");
- log.debug("failed to create capabilityType: {}", capabilityType.getType());
- if (dataModelResponse.right().value() != StorageOperationStatus.SCHEMA_VIOLATION) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByCapabilityType(componentsUtils.convertFromStorageResponseForCapabilityType(dataModelResponse.right().value()), capabilityType);
- eitherResult = Either.right(responseFormat);
- stopDao = true;
- }
-
- } else {
- createdCapabilities.add(capabilityType);
- }
- if (!capTypeItr.hasNext()) {
- log.info("capabilityTypes were created successfully!!!");
- }
-
- }
+ private Either<List<CapabilityTypeDefinition>, ActionStatus> createCapabilityTypesFromYml(String capabilityTypesYml) {
+ return commonImportManager.createElementTypesFromYml(capabilityTypesYml, this::createCapabilityType);
- return eitherResult;
+ }
+ private Either<List<ImmutablePair<CapabilityTypeDefinition, Boolean>>, ResponseFormat> upsertCapabilityTypesByDao(List<CapabilityTypeDefinition> capabilityTypesToCreate) {
+ return commonImportManager.createElementTypesByDao(capabilityTypesToCreate,
+ capabilityType -> Either.left(ActionStatus.OK),
+ capabilityType -> new ImmutablePair<>(CommonImportManager.ElementTypeEnum.CAPABILITY_TYPE, capabilityType.getType()),
+ capabilityTypeOperation::getCapabilityType,
+ capabilityTypeOperation::addCapabilityType,
+ this::updateCapabilityType);
+ }
+
+ private Either<CapabilityTypeDefinition, StorageOperationStatus> updateCapabilityType(CapabilityTypeDefinition newCapabilityType, CapabilityTypeDefinition oldCapabilityType) {
+ Either<CapabilityTypeDefinition, StorageOperationStatus> validationRes = capabilityTypeOperation.validateUpdateProperties(newCapabilityType);
+ if (validationRes.isRight()) {
+ log.error("#updateCapabilityType - One or all properties of capability type {} not valid. status is {}", newCapabilityType, validationRes.right().value());
+ return validationRes;
+ }
+
+ if (TypeCompareUtils.isCapabilityTypesEquals(newCapabilityType, oldCapabilityType)) {
+ return TypeCompareUtils.typeAlreadyExists();
+ }
+
+ return capabilityTypeOperation.updateCapabilityType(newCapabilityType, oldCapabilityType);
}
private CapabilityTypeDefinition createCapabilityType(String capabilityTypeName, Map<String, Object> toscaJson) {
@@ -107,13 +87,11 @@ public class CapabilityTypeImportManager {
capabilityType.setType(capabilityTypeName);
// Description
- final Consumer<String> descriptionSetter = description -> capabilityType.setDescription(description);
- commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DESCRIPTION.getElementName(), descriptionSetter);
+ commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName(), capabilityType::setDescription);
// Derived From
- final Consumer<String> derivedFromSetter = derivedFrom -> capabilityType.setDerivedFrom(derivedFrom);
- commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DERIVED_FROM.getElementName(), derivedFromSetter);
+ commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DERIVED_FROM.getElementName(), capabilityType::setDerivedFrom);
// Properties
- commonImportManager.setPropertiesMap(toscaJson, (values) -> capabilityType.setProperties(values));
+ commonImportManager.setPropertiesMap(toscaJson, capabilityType::setProperties);
return capabilityType;
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java
index b4147b8fc5..05a0eb52ef 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java
@@ -1,39 +1,30 @@
package org.openecomp.sdc.be.components.impl;
-import java.io.FileInputStream;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
-
-import javax.annotation.PostConstruct;
-
+import com.datastax.driver.core.Cluster;
+import com.datastax.driver.core.KeyspaceMetadata;
+import com.datastax.driver.core.Metadata;
+import com.datastax.driver.core.Session;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.cassandra.schema.SdcSchemaUtils;
import org.openecomp.sdc.be.dao.cassandra.schema.Table;
+import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.GeneralUtility;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
-import com.datastax.driver.core.Cluster;
-import com.datastax.driver.core.KeyspaceMetadata;
-import com.datastax.driver.core.Metadata;
-import com.datastax.driver.core.Session;
+import javax.annotation.PostConstruct;
+import java.io.FileInputStream;
+import java.io.InputStream;
+import java.util.*;
@Component("cassandra-health-check")
public class CassandraHealthCheck {
- private static final Logger log = LoggerFactory.getLogger(CassandraHealthCheck.class);
+ private static final Logger log = Logger.getLogger(CassandraHealthCheck.class.getName());
private String localDataCenterName = null;
- private Set<String> sdcKeyspaces = new HashSet<String>();
+ private Set<String> sdcKeyspaces = new HashSet<>();
private int HC_FormulaNumber;
@@ -92,7 +83,7 @@ public class CassandraHealthCheck {
log.info("Cluster Metadata: {}", metadata);
List<KeyspaceMetadata> keyspaces = metadata.getKeyspaces();
- List<Integer> replactionFactorList = new ArrayList<Integer>();
+ List<Integer> replactionFactorList = new ArrayList<>();
//Collect the keyspaces Replication Factor of current localDataCenter
for (KeyspaceMetadata keyspace : keyspaces) {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java
index dc836611ff..0df7c7066d 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java
@@ -20,13 +20,7 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
+import fj.data.Either;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datamodel.api.CategoryTypeEnum;
import org.openecomp.sdc.be.datamodel.utils.NodeTypeConvertUtils;
@@ -38,14 +32,14 @@ import org.openecomp.sdc.be.model.category.GroupingDefinition;
import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
+import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.Yaml;
-import fj.data.Either;
+import java.util.*;
+import java.util.Map.Entry;
@Component("categoriesImportManager")
public class CategoriesImportManager {
@@ -56,7 +50,7 @@ public class CategoriesImportManager {
@javax.annotation.Resource
private ComponentsUtils componentsUtils;
- private static final Logger log = LoggerFactory.getLogger(CategoriesImportManager.class);
+ private static final Logger log = Logger.getLogger(CategoriesImportManager.class.getName());
public Either<Map<String, List<CategoryDefinition>>, ResponseFormat> createCategories(String categoriesTypesYml) {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java
index 88e5853489..b60b5c7e09 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java
@@ -20,60 +20,60 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.function.BiFunction;
-import java.util.function.Consumer;
-import java.util.function.Function;
-import java.util.stream.Collectors;
-
-import javax.annotation.Resource;
-
+import fj.data.Either;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
+import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
+import org.openecomp.sdc.be.components.impl.model.ToscaTypeImportData;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.elements.ToscaTypeDataDefinition;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.GroupTypeDefinition;
-import org.openecomp.sdc.be.model.PolicyTypeDefinition;
-import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.*;
+import org.openecomp.sdc.be.model.normatives.ToscaTypeMetadata;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.api.TypeOperations;
import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
+import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.Yaml;
-import fj.data.Either;
+import java.util.*;
+import java.util.Map.Entry;
+import java.util.function.BiFunction;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import static java.util.stream.Collectors.toList;
@Component("commonImportManager")
public class CommonImportManager {
- private static final Logger log = LoggerFactory.getLogger(CommonImportManager.class);
+ private static final Logger log = Logger.getLogger(CommonImportManager.class.getName());
- @Resource
- private ComponentsUtils componentsUtils;
- @Resource
- private PropertyOperation propertyOperation;
+ private final ComponentsUtils componentsUtils;
+ private final PropertyOperation propertyOperation;
- protected void setProperties(Map<String, Object> toscaJson, Consumer<List<PropertyDefinition>> consumer) {
+ public CommonImportManager(ComponentsUtils componentsUtils, PropertyOperation propertyOperation) {
+ this.componentsUtils = componentsUtils;
+ this.propertyOperation = propertyOperation;
+ }
+
+ public static void setProperties(Map<String, Object> toscaJson, Consumer<List<PropertyDefinition>> consumer) {
consumer.accept(getProperties(toscaJson));
}
- private List<PropertyDefinition> getProperties(Map<String, Object> toscaJson) {
+ private static List<PropertyDefinition> getProperties(Map<String, Object> toscaJson) {
List<PropertyDefinition> values = null;
Either<Map<String, PropertyDefinition>, ResultStatusEnum> properties = ImportUtils.getProperties(toscaJson);
if (properties.isLeft()) {
values = new ArrayList<>();
Map<String, PropertyDefinition> propertiesMap = properties.left().value();
- if (propertiesMap != null && propertiesMap.isEmpty() == false) {
+ if (propertiesMap != null && !propertiesMap.isEmpty()) {
for (Entry<String, PropertyDefinition> entry : propertiesMap.entrySet()) {
String propName = entry.getKey();
@@ -91,75 +91,104 @@ public class CommonImportManager {
protected void setPropertiesMap(Map<String, Object> toscaJson, Consumer<Map<String, PropertyDefinition>> consumer) {
final List<PropertyDefinition> properties = getProperties(toscaJson);
if (properties != null) {
- Map<String, PropertyDefinition> collect = properties.stream().collect(Collectors.toMap(e -> e.getName(), e -> e));
+ Map<String, PropertyDefinition> collect = properties.stream()
+ .collect(Collectors.toMap(PropertyDefinition::getName, Function.identity()));
consumer.accept(collect);
}
-
}
- interface ICreateElementType<T1, T2, ElementType> {
- ElementType createElement(T1 firstArg, T2 secondArg);
+ public interface ICreateElementType<T1, T2, T3> {
+ T3 createElement(T1 firstArg, T2 secondArg);
}
- protected <ElementDefinition> Either<List<ElementDefinition>, ActionStatus> createElementTypesFromYml(String elementTypesYml, ICreateElementType<String, Map<String, Object>, ElementDefinition> createApi) {
+ protected <T> Either<List<T>, ActionStatus> createElementTypesFromYml(String elementTypesYml, ICreateElementType<String, Map<String, Object>, T> createApi) {
- List<ElementDefinition> elementTypes = new ArrayList<>();
- try {
- Map<String, Object> toscaJson = (Map<String, Object>) new Yaml().load(elementTypesYml);
+ List<T> elementTypes;
+ Map<String, Object> toscaJson = convertToFieldMap(elementTypesYml);
+ if (toscaJson==null) {
+ return Either.right(ActionStatus.INVALID_YAML_FILE);
+ }
+ elementTypes = createElementTypesFromToscaJsonMap(createApi, toscaJson);
+ return Either.left(elementTypes);
+ }
- elementTypes = createElementTypesFromToscaJsonMap(createApi, toscaJson);
+ @SuppressWarnings("unchecked")
+ private Map<String, Object> convertToFieldMap(String elementTypesYml) {
+ Map<String, Object> toscaJson = null;
+ try {
+ toscaJson = (Map<String, Object>) new Yaml().load(elementTypesYml);
} catch (Exception e) {
log.debug("Failed to yaml file {}", elementTypesYml, e);
- return Either.right(ActionStatus.INVALID_YAML_FILE);
}
- return Either.left(elementTypes);
+ return toscaJson;
+ }
+
+
+ protected <T extends ToscaDataDefinition> List<T> createTypesFromToscaJsonMap(
+ BiFunction<String, Map<String, Object>, T> createApi, Map<String, Object> toscaJson) {
+ List<T> elementTypes = new ArrayList<>();
+
+ for (Entry<String, Object> elementTypeNameDataEntry : toscaJson.entrySet()) {
+ String elementTypeName = elementTypeNameDataEntry.getKey();
+ Map<String, Object> elementTypeJsonData = (Map<String, Object>) elementTypeNameDataEntry.getValue();
+ T elementDefinition = createApi.apply(elementTypeName, elementTypeJsonData);
+ elementTypes.add(elementDefinition);
+ }
+ return elementTypes;
}
- /**
- * @param createApi * @param createApi
- * @param elementTypes
- * @param toscaJson
- */
- protected <ElementDefinition> List<ElementDefinition> createElementTypesFromToscaJsonMap(
- ICreateElementType<String, Map<String, Object>, ElementDefinition> createApi, Map<String, Object> toscaJson) {
- List<ElementDefinition> elementTypes = new ArrayList<>();
+ protected <T> List<T> createElementTypesFromToscaJsonMap(
+ ICreateElementType<String, Map<String, Object>, T> createApi, Map<String, Object> toscaJson) {
+ List<T> elementTypes = new ArrayList<>();
+
+ for (Entry<String, Object> elementTypeNameDataEntry : toscaJson.entrySet()) {
+ String elementTypeName = elementTypeNameDataEntry.getKey();
+ Map<String, Object> elementTypeJsonData = (Map<String, Object>) elementTypeNameDataEntry.getValue();
+ T elementDefinition = createApi.createElement(elementTypeName, elementTypeJsonData);
+ elementTypes.add(elementDefinition);
+ }
+ return elementTypes;
+ }
+
+ protected <T> Map<String, T> createElementTypesMapFromToscaJsonMap(
+ ICreateElementType<String, Map<String, Object>, T> createApi, Map<String, Object> toscaJson) {
+ Map<String, T> elementTypesMap = new HashMap<>();
Iterator<Entry<String, Object>> elementTypesEntryItr = toscaJson.entrySet().iterator();
while (elementTypesEntryItr.hasNext()) {
Entry<String, Object> elementTypeNameDataEntry = elementTypesEntryItr.next();
String elementTypeName = elementTypeNameDataEntry.getKey();
Map<String, Object> elementTypeJsonData = (Map<String, Object>) elementTypeNameDataEntry.getValue();
- ElementDefinition elementDefinition = createApi.createElement(elementTypeName, elementTypeJsonData);
- elementTypes.add(elementDefinition);
+ T elementDefinition = createApi.createElement(elementTypeName, elementTypeJsonData);
+ elementTypesMap.put(elementTypeName, elementDefinition);
}
- return elementTypes;
+ return elementTypesMap;
}
- protected <FieldType> void setField(Map<String, Object> toscaJson, String fieldName, Consumer<FieldType> setter) {
+ protected <F> void setField(Map<String, Object> toscaJson, String fieldName, Consumer<F> setter) {
if (toscaJson.containsKey(fieldName)) {
- FieldType fieldValue = (FieldType) toscaJson.get(fieldName);
+ F fieldValue = (F) toscaJson.get(fieldName);
setter.accept(fieldValue);
}
-
}
public enum ElementTypeEnum {
- PolicyType, GroupType, DataType, CapabilityType, InterfaceLifecycleType
- };
+ POLICY_TYPE, GROUP_TYPE, DATA_TYPE, CAPABILITY_TYPE, INTERFACE_LIFECYCLE_TYPE
+ }
private ActionStatus convertFromStorageResponseForElementType(StorageOperationStatus status, ElementTypeEnum elementTypeEnum) {
ActionStatus ret;
switch (elementTypeEnum) {
- case GroupType:
+ case GROUP_TYPE:
ret = componentsUtils.convertFromStorageResponseForGroupType(status);
break;
- case DataType:
+ case DATA_TYPE:
ret = componentsUtils.convertFromStorageResponseForDataType(status);
break;
- case CapabilityType:
+ case CAPABILITY_TYPE:
ret = componentsUtils.convertFromStorageResponseForCapabilityType(status);
break;
- case InterfaceLifecycleType:
+ case INTERFACE_LIFECYCLE_TYPE:
ret = componentsUtils.convertFromStorageResponseForLifecycleType(status);
break;
default:
@@ -169,19 +198,19 @@ public class CommonImportManager {
return ret;
}
- private <ElementTypeDefinition> ResponseFormat getResponseFormatForElementType(ActionStatus actionStatus, ElementTypeEnum elementTypeEnum, ElementTypeDefinition elementTypeDefinition) {
+ private <T> ResponseFormat getResponseFormatForElementType(ActionStatus actionStatus, ElementTypeEnum elementTypeEnum, T elementTypeDefinition) {
ResponseFormat ret;
switch (elementTypeEnum) {
- case GroupType:
+ case GROUP_TYPE:
ret = componentsUtils.getResponseFormatByGroupType(actionStatus, (GroupTypeDefinition) elementTypeDefinition);
break;
- case PolicyType:
+ case POLICY_TYPE:
ret = componentsUtils.getResponseFormatByPolicyType(actionStatus, (PolicyTypeDefinition) elementTypeDefinition);
break;
- case DataType:
+ case DATA_TYPE:
ret = componentsUtils.getResponseFormatByDataType(actionStatus, (DataTypeDefinition) elementTypeDefinition, null);
break;
- case CapabilityType:
+ case CAPABILITY_TYPE:
ret = componentsUtils.getResponseFormatByCapabilityType(actionStatus, (CapabilityTypeDefinition) elementTypeDefinition);
break;
@@ -192,122 +221,209 @@ public class CommonImportManager {
return ret;
}
- protected <ElementTypeDefinition> Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat> createElementTypesByDao(List<ElementTypeDefinition> elementTypesToCreate,
- Function<ElementTypeDefinition, Either<ActionStatus, ResponseFormat>> validator, Function<ElementTypeDefinition, ImmutablePair<ElementTypeEnum, String>> elementInfoGetter,
- Function<String, Either<ElementTypeDefinition, StorageOperationStatus>> elementFetcher, Function<ElementTypeDefinition, Either<ElementTypeDefinition, StorageOperationStatus>> elementAdder,
- BiFunction<ElementTypeDefinition, ElementTypeDefinition, Either<ElementTypeDefinition, StorageOperationStatus>> elementUpgrader) {
+ private <T extends ToscaDataDefinition> List<ImmutablePair<T, Boolean>> createTypesByDao(List<T> elementTypesToCreate,
+ TypeOperations<T> typeOperations) {
+ List<ImmutablePair<T, Boolean>> createdElementTypes = new ArrayList<>();
+ for (T newTypeDefinition : elementTypesToCreate) {
+ try {
+ String typeName = newTypeDefinition.getType();
+ T existingDefinition = typeOperations.getLatestType(typeName);
+ if (existingDefinition == null /*new type*/) {
+ typeOperations.addType(newTypeDefinition);
+ } else {
+ if (typeOperations.isSameType(newTypeDefinition, existingDefinition)) {
+ propertyOperation.getTitanGenericDao().rollback();
+ createdElementTypes.add(new ImmutablePair<>(newTypeDefinition, null));
+ continue;
+ } else {
+ typeOperations.updateType(existingDefinition, newTypeDefinition);
+ }
+ }
+ propertyOperation.getTitanGenericDao().commit();
+ createdElementTypes.add(new ImmutablePair<>(newTypeDefinition, true));
+ } catch (Exception e) {
+ propertyOperation.getTitanGenericDao().rollback();
+ createdElementTypes.add(new ImmutablePair<>(newTypeDefinition, false));
+ }
- List<ImmutablePair<ElementTypeDefinition, Boolean>> createdElementTypes = new ArrayList<>();
+ }
+ return createdElementTypes;
+ }
+
+ protected <T> Either<List<ImmutablePair<T, Boolean>>, ResponseFormat> createElementTypesByDao(List<T> elementTypesToCreate,
+ Function<T, Either<ActionStatus, ResponseFormat>> validator, Function<T, ImmutablePair<ElementTypeEnum, String>> elementInfoGetter,
+ Function<String, Either<T, StorageOperationStatus>> elementFetcher, Function<T, Either<T, StorageOperationStatus>> elementAdder,
+ BiFunction<T, T, Either<T, StorageOperationStatus>> elementUpgrader) {
- Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat> eitherResult = Either.left(createdElementTypes);
+ List<ImmutablePair<T, Boolean>> createdElementTypes = new ArrayList<>();
- Iterator<ElementTypeDefinition> elementTypeItr = elementTypesToCreate.iterator();
+ Either<List<ImmutablePair<T, Boolean>>, ResponseFormat> eitherResult = Either.left(createdElementTypes);
+ Iterator<T> elementTypeItr = elementTypesToCreate.iterator();
try {
-
while (elementTypeItr.hasNext()) {
- ElementTypeDefinition elementType = elementTypeItr.next();
- final ImmutablePair<ElementTypeEnum, String> elementInfo = elementInfoGetter.apply(elementType);
- ElementTypeEnum elementTypeEnum = elementInfo.left;
- String elementName = elementInfo.right;
-
- Either<ActionStatus, ResponseFormat> validateElementType = validator.apply(elementType);
- if (validateElementType.isRight()) {
- ResponseFormat responseFormat = validateElementType.right().value();
- log.debug("Failed in validation of element type: {}. Response is {}", elementType, responseFormat.getFormattedMessage());
- eitherResult = Either.right(responseFormat);
+ T elementType = elementTypeItr.next();
+ eitherResult = handleType(elementType, validator, elementInfoGetter, elementFetcher, elementAdder, elementUpgrader)
+ .left()
+ .map(elem -> append(createdElementTypes, elem));
+
+ if (eitherResult.isRight()) {
break;
}
+
+ if(!elementTypeItr.hasNext()) {
+ log.info("all {} were created successfully!!!", elementType);
+ }
+ }
+ }
+ catch(Exception e) {
+ eitherResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ throw e;
+ }
+ finally {
+ if (eitherResult.isLeft()) {
+ propertyOperation.getTitanGenericDao().commit();
+ }
+ else {
+ propertyOperation.getTitanGenericDao().rollback();
+ }
+ }
- log.info("send {} : {} to dao for create", elementTypeEnum, elementName);
-
- Either<ElementTypeDefinition, StorageOperationStatus> findElementType = elementFetcher.apply(elementName);
- if (findElementType.isRight()) {
- StorageOperationStatus status = findElementType.right().value();
- log.debug("searched {} finished with result:{}", elementTypeEnum, status.name());
- if (status != StorageOperationStatus.NOT_FOUND) {
- ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(status, elementTypeEnum), elementTypeEnum, elementType);
- eitherResult = Either.right(responseFormat);
- break;
- } else {
- Either<ElementTypeDefinition, StorageOperationStatus> dataModelResponse = elementAdder.apply(elementType);
-
- if (dataModelResponse.isRight()) {
- try {
- BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError("Create {}", elementTypeEnum.name());
- log.debug("failed to create {}: {}", elementTypeEnum, elementName);
- if (dataModelResponse.right().value() != StorageOperationStatus.SCHEMA_VIOLATION) {
- ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(dataModelResponse.right().value(), elementTypeEnum), elementTypeEnum, elementType);
-
- eitherResult = Either.right(responseFormat);
- break;
- } else {
- createdElementTypes.add(new ImmutablePair<ElementTypeDefinition, Boolean>(elementType, false));
- }
- } finally {
- propertyOperation.getTitanGenericDao().rollback();
- }
- } else {
- propertyOperation.getTitanGenericDao().commit();
- createdElementTypes.add(new ImmutablePair<ElementTypeDefinition, Boolean>(elementType, true));
- log.debug("{} : {} was created successfully.", elementTypeEnum, elementName);
- }
- if (!elementTypeItr.hasNext()) {
- log.info("all {} were created successfully!!!", elementTypeEnum);
- }
+ return eitherResult;
+ }
+
+ private static <T> List<T> append(List<T> list, T value) {
+ list.add(value);
+ return list;
+ }
+
+
+ private <T> Either<ImmutablePair<T, Boolean>, ResponseFormat> handleType(T elementType,
+ Function<T, Either<ActionStatus, ResponseFormat>> validator, Function<T, ImmutablePair<ElementTypeEnum, String>> elementInfoGetter,
+ Function<String, Either<T, StorageOperationStatus>> elementFetcher, Function<T, Either<T, StorageOperationStatus>> elementAdder,
+ BiFunction<T, T, Either<T, StorageOperationStatus>> elementUpgrader) {
+
+ final ImmutablePair<ElementTypeEnum, String> elementInfo = elementInfoGetter.apply(elementType);
+ ElementTypeEnum elementTypeEnum = elementInfo.left;
+ String elementName = elementInfo.right;
+
+ Either<ActionStatus, ResponseFormat> validateElementType = validator.apply(elementType);
+ if (validateElementType.isRight()) {
+ ResponseFormat responseFormat = validateElementType.right().value();
+ log.debug("Failed in validation of element type: {}. Response is {}", elementType, responseFormat.getFormattedMessage());
+ return Either.right(responseFormat);
+ }
- }
- } else {
+ log.info("send {} : {} to dao for create", elementTypeEnum, elementName);
+
+ Either<T, StorageOperationStatus> findElementType = elementFetcher.apply(elementName);
+ if (findElementType.isRight()) {
+ StorageOperationStatus status = findElementType.right().value();
+ log.debug("searched {} finished with result:{}", elementTypeEnum, status);
+ if (status != StorageOperationStatus.NOT_FOUND) {
+ ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(status, elementTypeEnum), elementTypeEnum, elementType);
+ return Either.right(responseFormat);
+ } else {
+ return addElementType(elementType, elementAdder, elementTypeEnum, elementName);
+ }
+ } else {
- if (elementUpgrader != null) {
- Either<ElementTypeDefinition, StorageOperationStatus> upgradeResponse = null;
- try {
- upgradeResponse = elementUpgrader.apply(elementType, findElementType.left().value());
- if (upgradeResponse.isRight()) {
- StorageOperationStatus status = upgradeResponse.right().value();
- if (status == StorageOperationStatus.OK) {
- createdElementTypes.add(new ImmutablePair<ElementTypeDefinition, Boolean>(elementType, false));
- } else {
- ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(upgradeResponse.right().value(), elementTypeEnum), elementTypeEnum, elementType);
- eitherResult = Either.right(responseFormat);
- break;
- }
- } else {
- log.debug("{} : {} was upgraded successfully.", elementTypeEnum, elementName);
- createdElementTypes.add(new ImmutablePair<ElementTypeDefinition, Boolean>(elementType, true));
- }
- } finally {
- if (upgradeResponse == null || upgradeResponse.isRight()) {
- propertyOperation.getTitanGenericDao().rollback();
- } else {
- propertyOperation.getTitanGenericDao().commit();
- }
- }
+ if (elementUpgrader != null) {
+ return updateElementType(elementType, elementUpgrader, elementTypeEnum, elementName, findElementType.left().value());
- } else {
- // mshitrit Once GroupType Versions are supported add
- // code here
- createdElementTypes.add(new ImmutablePair<ElementTypeDefinition, Boolean>(elementType, false));
- log.debug("{} : {} already exists.", elementTypeEnum, elementName);
- }
+ } else {
+ // mshitrit Once GroupType Versions are supported add
+ // code here
+ log.debug("{} : {} already exists.", elementTypeEnum, elementName);
+ return Either.left(new ImmutablePair<>(elementType, false));
+ }
- }
+ }
+ }
+ private <T> Either<ImmutablePair<T, Boolean>, ResponseFormat> addElementType(T elementType, Function<T, Either<T, StorageOperationStatus>> elementAdder, ElementTypeEnum elementTypeEnum, String elementName) {
+ Either<T, StorageOperationStatus> dataModelResponse = elementAdder.apply(elementType);
+
+ if (dataModelResponse.isRight()) {
+ BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError("Create {}", elementTypeEnum.name());
+ log.debug("failed to create {}: {}", elementTypeEnum, elementName);
+ if (dataModelResponse.right().value() != StorageOperationStatus.OK) {
+ ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(dataModelResponse.right().value(), elementTypeEnum), elementTypeEnum, elementType);
+
+ return Either.right(responseFormat);
+ } else {
+ return Either.left(new ImmutablePair<>(elementType, false));
}
- } finally {
- if (eitherResult.isRight()) {
- propertyOperation.getTitanGenericDao().rollback();
+ } else {
+ log.debug("{} : {} was created successfully.", elementTypeEnum, elementName);
+ return Either.left(new ImmutablePair<>(elementType, true));
+ }
+ }
+
+
+ private <T> Either<ImmutablePair<T, Boolean>, ResponseFormat> updateElementType(T elementType, BiFunction<T, T, Either<T, StorageOperationStatus>> elementUpgrader,
+ ElementTypeEnum elementTypeEnum, String elementName, T existingElementType) {
+ Either<T, StorageOperationStatus> upgradeResponse = elementUpgrader.apply(elementType, existingElementType);
+ if (upgradeResponse.isRight()) {
+ StorageOperationStatus status = upgradeResponse.right().value();
+ if (status == StorageOperationStatus.OK) {
+ return Either.left(new ImmutablePair<>(elementType, false));
+ } else {
+ ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(upgradeResponse.right().value(), elementTypeEnum), elementTypeEnum, elementType);
+ return Either.right(responseFormat);
}
+ } else {
+ log.debug("{} : {} was upgraded successfully.", elementTypeEnum, elementName);
+ return Either.left(new ImmutablePair<>(elementType, true));
}
+ }
- return eitherResult;
+
+ public <T extends ToscaTypeDataDefinition> Either<List<ImmutablePair<T, Boolean>>, ResponseFormat> createElementTypes(ToscaTypeImportData toscaTypeImportData, Function<String, Either<List<T>, ActionStatus>> elementTypeFromYmlCreater,
+ Function<List<T>, Either<List<ImmutablePair<T, Boolean>>, ResponseFormat>> elementTypeDaoCreater) {
+ Either<List<T>, ActionStatus> elementTypes = elementTypeFromYmlCreater.apply(toscaTypeImportData.getToscaTypesYml());
+ return elementTypes
+ .right()
+ .map(err -> componentsUtils.getResponseFormat(err, ""))
+ .left()
+ .map(toscaTypes -> enrichTypesWithNonToscaMetadata(toscaTypes, toscaTypeImportData.getToscaTypeMetadata()))
+ .left()
+ .bind(elementTypeDaoCreater::apply);
+ }
+ public <T extends ToscaDataDefinition> List<ImmutablePair<T, Boolean>> createElementTypes(String toscaTypesYml,
+ BiFunction<String, Map<String, Object>, T> createApi,
+ TypeOperations<T> typeOperations) {
+ Map<String, Object> fieldMap = convertToFieldMap(toscaTypesYml);
+ if (fieldMap==null) {
+ throw new ComponentException(ActionStatus.INVALID_YAML_FILE);
+ }
+ List<T> elementTypes = createTypesFromToscaJsonMap(createApi, fieldMap);
+ return createTypesByDao(elementTypes, typeOperations);
+ }
+
+ private <T extends ToscaTypeDataDefinition> List<T> enrichTypesWithNonToscaMetadata(List<T> toscaTypes, Map<String, ToscaTypeMetadata> toscaTypeMetadata) {
+ return toscaTypes.stream()
+ .map(toscaType -> setNonToscaMetaDataOnType(toscaTypeMetadata, toscaType))
+ .collect(toList());
+ }
+
+ private <T extends ToscaTypeDataDefinition> T setNonToscaMetaDataOnType(Map<String, ToscaTypeMetadata> toscaTypeMetadata, T toscaTypeDefinition) {
+ String toscaType = toscaTypeDefinition.getType();
+ ToscaTypeMetadata typeMetaData = toscaTypeMetadata.get(toscaType);
+ if (typeMetaData == null) {
+ log.debug("failing while trying to associate metadata for type {}. type not exist", toscaType);
+ throw new ComponentException(ActionStatus.GENERAL_ERROR);
+ }
+ toscaTypeDefinition.setIcon(typeMetaData.getIcon());
+ toscaTypeDefinition.setName(typeMetaData.getDisplayName());
+ return toscaTypeDefinition;
}
- public <ElementTypeDefinition> Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat> createElementTypes(String elementTypesYml, Function<String, Either<List<ElementTypeDefinition>, ActionStatus>> elementTypeFromYmlCreater,
- Function<List<ElementTypeDefinition>, Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat>> elementTypeDaoCreater, ElementTypeEnum elementTypeEnum) {
+ public <T> Either<List<ImmutablePair<T, Boolean>>, ResponseFormat> createElementTypes(String elementTypesYml, Function<String, Either<List<T>, ActionStatus>> elementTypeFromYmlCreater,
+ Function<List<T>, Either<List<ImmutablePair<T, Boolean>>, ResponseFormat>> elementTypeDaoCreater, ElementTypeEnum elementTypeEnum) {
- Either<List<ElementTypeDefinition>, ActionStatus> elementTypes = elementTypeFromYmlCreater.apply(elementTypesYml);
+ Either<List<T>, ActionStatus> elementTypes = elementTypeFromYmlCreater.apply(elementTypesYml);
if (elementTypes.isRight()) {
ActionStatus status = elementTypes.right().value();
ResponseFormat responseFormat = getResponseFormatForElementType(status, elementTypeEnum, null);
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java
index deb6c3de2f..6b17d1c8e9 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java
@@ -20,17 +20,11 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.ArrayList;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.stream.Collectors;
-
+import fj.data.Either;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.ConfigurationManager;
@@ -40,46 +34,32 @@ import org.openecomp.sdc.be.dao.utils.MapUtil;
import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.*;
import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.CapReqDef;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.ComponentInstanceInput;
-import org.openecomp.sdc.be.model.ComponentInstanceProperty;
-import org.openecomp.sdc.be.model.ComponentParametersView;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement;
-import org.openecomp.sdc.be.model.InputDefinition;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.Operation;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.cache.ComponentCache;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
import org.openecomp.sdc.be.user.Role;
import org.openecomp.sdc.be.utils.CommonBeUtils;
import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
import org.openecomp.sdc.common.api.ArtifactTypeEnum;
-import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import fj.data.Either;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.stream.Collectors;
public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
@@ -96,7 +76,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
this.genericTypeBusinessLogic = genericTypeBusinessLogic;
}
- private static final Logger log = LoggerFactory.getLogger(ComponentBusinessLogic.class);
+ private static final Logger log = Logger.getLogger(ComponentBusinessLogic.class.getName());
private static final String TAG_FIELD_LABEL = "tag";
@@ -104,7 +84,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
public abstract ComponentInstanceBusinessLogic getComponentInstanceBL();
- public abstract Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText);
+ public abstract Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, String userId);
/**
*
@@ -114,31 +94,32 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
*/
public abstract Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String componentId, List<String> dataParamsToReturn);
- protected Either<User, ResponseFormat> validateUser(User user, String ecompErrorContext, Component component, AuditingActionEnum auditAction, boolean inTransaction) {
- Either<User, ResponseFormat> userValidationResult = validateUserNotEmpty(user, ecompErrorContext);
+ protected User validateUser(User user, String ecompErrorContext, Component component, AuditingActionEnum auditAction, boolean inTransaction) {
+ User validatedUser;
ResponseFormat responseFormat;
- if (userValidationResult.isRight()) {
- user.setUserId("UNKNOWN");
- responseFormat = userValidationResult.right().value();
- componentsUtils.auditComponentAdmin(responseFormat, user, component, auditAction, component.getComponentType());
- return Either.right(responseFormat);
- }
- Either<User, ResponseFormat> userResult = validateUserExists(user, ecompErrorContext, inTransaction);
- if (userResult.isRight()) {
- responseFormat = userResult.right().value();
+ try{
+ validateUserNotEmpty(user, ecompErrorContext);
+ validatedUser = validateUserExists(user, ecompErrorContext, inTransaction);
+ } catch(ComponentException e){
+ if(e.getActionStatus()== ActionStatus.MISSING_INFORMATION){
+ user.setUserId("UNKNOWN");
+ }
+ responseFormat = e.getResponseFormat() != null ? e.getResponseFormat()
+ : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
componentsUtils.auditComponentAdmin(responseFormat, user, component, auditAction, component.getComponentType());
- return Either.right(responseFormat);
+ throw e;
}
- return userResult;
+ return validatedUser;
}
- protected Either<Boolean, ResponseFormat> validateUserRole(User user, Component component, List<Role> roles, AuditingActionEnum auditAction, String comment) {
+ protected void validateUserRole(User user, Component component, List<Role> roles, AuditingActionEnum auditAction, String comment) {
if (roles != null && roles.isEmpty()) {
roles.add(Role.ADMIN);
roles.add(Role.DESIGNER);
}
- Either<Boolean, ResponseFormat> validationResult = validateUserRole(user, roles);
- if (validationResult.isRight()) {
+ try{
+ validateUserRole(user, roles);
+ } catch(ComponentException e){
String commentStr = null;
String distrStatus = null;
ComponentTypeEnum componentType = component.getComponentType();
@@ -146,80 +127,78 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
distrStatus = ((ServiceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getDistributionStatus();
commentStr = comment;
}
- componentsUtils.auditComponent(validationResult.right().value(), user, component, auditAction, componentType,
- ResourceAuditData.newBuilder().distributionStatus(distrStatus).build(),
- ResourceAuditData.newBuilder().distributionStatus(distrStatus).build(),
- null, commentStr, null, null);
-
-
+ ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat()
+ : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
+ componentsUtils.auditComponent(responseFormat, user, component, auditAction, new ResourceCommonInfo(componentType.getValue()),
+ ResourceVersionInfo.newBuilder().distributionStatus(distrStatus).build(),
+ ResourceVersionInfo.newBuilder().distributionStatus(distrStatus).build(),
+ commentStr, null, null);
+ throw e;
}
- return validationResult;
}
- protected Either<Boolean, ResponseFormat> validateComponentName(User user, Component component, AuditingActionEnum actionEnum) {
+ protected void validateComponentName(User user, Component component, AuditingActionEnum actionEnum) {
ComponentTypeEnum type = component.getComponentType();
String componentName = component.getName();
if (!ValidationUtils.validateStringNotEmpty(componentName)) {
log.debug("component name is empty");
ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_COMPONENT_NAME, type.getValue());
componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type);
- return Either.right(errorResponse);
+ throw new ComponentException(ActionStatus.MISSING_COMPONENT_NAME, type.getValue());
}
if (!ValidationUtils.validateComponentNameLength(componentName)) {
log.debug("Component name exceeds max length {} ", ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type);
- return Either.right(errorResponse);
+ throw new ComponentException(ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT,type.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
}
if (!validateTagPattern(componentName)) {
log.debug("Component name {} has invalid format", componentName);
ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPONENT_NAME, type.getValue());
componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type);
- return Either.right(errorResponse);
+ throw new ComponentException(ActionStatus.INVALID_COMPONENT_NAME, type.getValue());
}
component.setNormalizedName(ValidationUtils.normaliseComponentName(componentName));
component.setSystemName(ValidationUtils.convertToSystemName(componentName));
-
- return Either.left(true);
}
- protected Either<Boolean, ResponseFormat> validateDescriptionAndCleanup(User user, Component component, AuditingActionEnum actionEnum) {
+ protected void validateDescriptionAndCleanup(User user, Component component, AuditingActionEnum actionEnum) {
ComponentTypeEnum type = component.getComponentType();
String description = component.getDescription();
if (!ValidationUtils.validateStringNotEmpty(description)) {
ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_DESCRIPTION, type.getValue());
componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type);
- return Either.right(errorResponse);
+ throw new ComponentException(ActionStatus.COMPONENT_MISSING_DESCRIPTION, type.getValue());
}
description = cleanUpText(description);
- Either<Boolean, ResponseFormat> validatDescription = validateComponentDescription(description, type);
- if (validatDescription.isRight()) {
- ResponseFormat responseFormat = validatDescription.right().value();
+ try{
+ validateComponentDescription(description, type);
+ } catch(ComponentException e){
+ ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat()
+ : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, type);
- return Either.right(responseFormat);
+ throw e;
}
component.setDescription(description);
- return Either.left(true);
}
- public Either<Boolean, ResponseFormat> validateComponentDescription(String description, ComponentTypeEnum type) {
+ private void validateComponentDescription(String description, ComponentTypeEnum type) {
if (description != null) {
if (!ValidationUtils.validateDescriptionLength(description)) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH));
+ throw new ComponentException(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
}
if (!ValidationUtils.validateIsEnglish(description)) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_DESCRIPTION, type.getValue()));
+ throw new ComponentException(ActionStatus.COMPONENT_INVALID_DESCRIPTION, type.getValue());
}
- return Either.left(true);
}
- return Either.left(false);
}
protected Either<Boolean, ResponseFormat> validateComponentNameUnique(User user, Component component, AuditingActionEnum actionEnum) {
+ log.debug("validate component name uniqueness for: {}", component.getName());
ComponentTypeEnum type = component.getComponentType();
ResourceTypeEnum resourceType = null;
if(component instanceof Resource){
@@ -244,7 +223,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
return Either.right(errorResponse);
}
- protected Either<Boolean, ResponseFormat> validateContactId(User user, Component component, AuditingActionEnum actionEnum) {
+ protected void validateContactId(User user, Component component, AuditingActionEnum actionEnum) {
log.debug("validate component contactId");
ComponentTypeEnum type = component.getComponentType();
String contactId = component.getContactId();
@@ -253,27 +232,18 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
log.info("contact is missing.");
ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CONTACT, type.getValue());
componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type);
- return Either.right(errorResponse);
- }
-
- Either<Boolean, ResponseFormat> validateContactIdResponse = validateContactId(contactId, type);
- if (validateContactIdResponse.isRight()) {
- ResponseFormat responseFormat = validateContactIdResponse.right().value();
- componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, type);
+ throw new ComponentException(ActionStatus.COMPONENT_MISSING_CONTACT, type.getValue());
}
- return validateContactIdResponse;
+ validateContactId(contactId, user, component, actionEnum, type);
}
- private Either<Boolean, ResponseFormat> validateContactId(String contactId, ComponentTypeEnum type) {
- if (contactId != null) {
- if (!ValidationUtils.validateContactId(contactId)) {
- log.info("contact is invalid.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CONTACT, type.getValue());
- return Either.right(errorResponse);
- }
- return Either.left(true);
+ private void validateContactId(String contactId, User user, Component component, AuditingActionEnum actionEnum, ComponentTypeEnum type) {
+ if (contactId != null && !ValidationUtils.validateContactId(contactId)) {
+ log.info("contact is invalid.");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CONTACT, type.getValue());
+ componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type);
+ throw new ComponentException(ActionStatus.COMPONENT_INVALID_CONTACT, type.getValue());
}
- return Either.left(false);
}
@@ -286,11 +256,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
return Either.right(errorResponse);
}
- Either<User, ResponseFormat> resp = validateUserExists(userId, "validateConformanceLevel", false);
- if (resp.isRight()) {
- log.error("can't validate conformance level, user is not validated, uuid {}, userId {}", componentUuid, userId);
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "validateConformanceLevel", false);
Either<ComponentMetadataData, StorageOperationStatus> eitherComponent = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, null);
if (eitherComponent.isRight()) {
@@ -321,7 +287,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
return Either.left(result);
}
- protected Either<Boolean, ResponseFormat> validateIcon(User user, Component component, AuditingActionEnum actionEnum) {
+ protected void validateIcon(User user, Component component, AuditingActionEnum actionEnum) {
log.debug("validate Icon");
ComponentTypeEnum type = component.getComponentType();
String icon = component.getIcon();
@@ -329,56 +295,57 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
log.info("icon is missing.");
ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_ICON, type.getValue());
componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type);
- return Either.right(errorResponse);
+ throw new ComponentException(ActionStatus.COMPONENT_MISSING_ICON, type.getValue());
}
-
- Either<Boolean, ResponseFormat> validateIcon = validateIcon(icon, type);
- if (validateIcon.isRight()) {
- ResponseFormat responseFormat = validateIcon.right().value();
+ try {
+ validateIcon(icon, type);
+ } catch(ComponentException e){
+ ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat()
+ : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, type);
+ throw e;
}
- return validateIcon;
}
- private Either<Boolean, ResponseFormat> validateIcon(String icon, ComponentTypeEnum type) {
+ private void validateIcon(String icon, ComponentTypeEnum type) {
if (icon != null) {
if (!ValidationUtils.validateIconLength(icon)) {
log.debug("icon exceeds max length");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH));
+ throw new ComponentException(ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH);
}
if (!ValidationUtils.validateIcon(icon)) {
log.info("icon is invalid.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_ICON, type.getValue());
- return Either.right(errorResponse);
+ throw new ComponentException(ActionStatus.COMPONENT_INVALID_ICON, type.getValue());
}
- return Either.left(true);
}
- return Either.left(false);
}
- protected Either<Boolean, ResponseFormat> validateTagsListAndRemoveDuplicates(User user, Component component, AuditingActionEnum actionEnum) {
+ protected void validateTagsListAndRemoveDuplicates(User user, Component component, AuditingActionEnum actionEnum) {
List<String> tagsList = component.getTags();
-
- Either<Boolean, ResponseFormat> validateTags = validateComponentTags(tagsList, component.getName(), component.getComponentType());
- if (validateTags.isRight()) {
- ResponseFormat responseFormat = validateTags.right().value();
+ try {
+ validateComponentTags(tagsList, component.getName(), component.getComponentType(), user, component, actionEnum);
+ } catch(ComponentException e){
+ ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat()
+ : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, component.getComponentType());
- return Either.right(responseFormat);
+ throw e;
}
ValidationUtils.removeDuplicateFromList(tagsList);
- return Either.left(true);
}
- protected Either<Boolean, ResponseFormat> validateComponentTags(List<String> tags, String name, ComponentTypeEnum componentType) {
+ protected void validateComponentTags(List<String> tags, String name, ComponentTypeEnum componentType, User user, Component component, AuditingActionEnum action) {
log.debug("validate component tags");
boolean includesComponentName = false;
int tagListSize = 0;
+ ResponseFormat responseFormat;
if (tags != null && !tags.isEmpty()) {
for (String tag : tags) {
if (!ValidationUtils.validateTagLength(tag)) {
log.debug("tag length exceeds limit {}", ValidationUtils.TAG_MAX_LENGTH);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH));
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH);
+ componentsUtils.auditComponentAdmin(responseFormat, user, component, action, componentType);
+ throw new ComponentException(ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH);
}
if (validateTagPattern(tag)) {
if (!includesComponentName) {
@@ -386,7 +353,9 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
}
} else {
log.debug("invalid tag {}", tag);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_FIELD_FORMAT, componentType.getValue(), TAG_FIELD_LABEL));
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_FIELD_FORMAT, componentType.getValue(), TAG_FIELD_LABEL);
+ componentsUtils.auditComponentAdmin(responseFormat, user, component, action, componentType);
+ throw new ComponentException(ActionStatus.INVALID_FIELD_FORMAT, componentType.getValue(), TAG_FIELD_LABEL);
}
tagListSize += tag.length() + 1;
}
@@ -396,15 +365,21 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
if (!includesComponentName) {
log.debug("tags must include component name");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME));
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME);
+ componentsUtils.auditComponentAdmin(responseFormat, user, component, action, componentType);
+ throw new ComponentException(ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME);
}
if (!ValidationUtils.validateTagListLength(tagListSize)) {
log.debug("overall tags length exceeds limit {}", ValidationUtils.TAG_LIST_MAX_LENGTH);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH));
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH);
+ componentsUtils.auditComponentAdmin(responseFormat, user, component, action, componentType);
+ throw new ComponentException(ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH);
}
- return Either.left(true);
+ } else {
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_TAGS);
+ componentsUtils.auditComponentAdmin(responseFormat, user, component, action, componentType);
+ throw new ComponentException(ActionStatus.COMPONENT_MISSING_TAGS);
}
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_TAGS));
}
protected boolean validateTagPattern(String tag) {
@@ -421,14 +396,18 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
if (!ValidationUtils.validateStringNotEmpty(projectCode)) {
log.info("projectCode is missing.");
ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_PROJECT_CODE);
- componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, component.getComponentType(), ResourceAuditData.newBuilder().build());
+ componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, component.getComponentType(),
+ ResourceVersionInfo.newBuilder()
+ .build());
return Either.right(errorResponse);
}
Either<Boolean, ResponseFormat> validateProjectCodeResponse = validateProjectCode(projectCode);
if (validateProjectCodeResponse.isRight()) {
ResponseFormat responseFormat = validateProjectCodeResponse.right().value();
- componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, component.getComponentType(), ResourceAuditData.newBuilder().build());
+ componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, component.getComponentType(),
+ ResourceVersionInfo.newBuilder()
+ .build());
}
return validateProjectCodeResponse;
@@ -480,50 +459,27 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
}
}
- protected Either<Boolean, ResponseFormat> validateComponentFieldsBeforeCreate(User user, Component component, AuditingActionEnum actionEnum) {
+ protected void validateComponentFieldsBeforeCreate(User user, Component component, AuditingActionEnum actionEnum) {
// validate component name uniqueness
log.debug("validate component name ");
- Either<Boolean, ResponseFormat> componentNameValidation = validateComponentName(user, component, actionEnum);
- if (componentNameValidation.isRight()) {
- return componentNameValidation;
- }
-
+ validateComponentName(user, component, actionEnum);
// validate description
log.debug("validate description");
- Either<Boolean, ResponseFormat> descValidation = validateDescriptionAndCleanup(user, component, actionEnum);
- if (descValidation.isRight()) {
- return descValidation;
- }
-
+ validateDescriptionAndCleanup(user, component, actionEnum);
// validate tags
log.debug("validate tags");
- Either<Boolean, ResponseFormat> tagsValidation = validateTagsListAndRemoveDuplicates(user, component, actionEnum);
- if (tagsValidation.isRight()) {
- return tagsValidation;
- }
-
+ validateTagsListAndRemoveDuplicates(user, component, actionEnum);
// validate contact info
log.debug("validate contact info");
- Either<Boolean, ResponseFormat> contactIdValidation = validateContactId(user, component, actionEnum);
- if (contactIdValidation.isRight()) {
- return contactIdValidation;
- }
-
+ validateContactId(user, component, actionEnum);
// validate icon
log.debug("validate icon");
- Either<Boolean, ResponseFormat> iconValidation = validateIcon(user, component, actionEnum);
- if (iconValidation.isRight()) {
- return iconValidation;
- }
- return Either.left(true);
+ validateIcon(user, component, actionEnum);
}
public Either<CapReqDef, ResponseFormat> getRequirementsAndCapabilities(String componentId, ComponentTypeEnum componentTypeEnum, String userId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "create Component Instance", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "create Component Instance", false);
Either<CapReqDef, ResponseFormat> eitherRet = null;
ComponentParametersView filter = new ComponentParametersView(true);
filter.setIgnoreCapabilities(false);
@@ -539,38 +495,29 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
return eitherRet;
}
- public Either<List<Component>, ResponseFormat> getLatestVersionNotAbstractComponents(boolean isAbstractAbstract, HighestFilterEnum highestFilter, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids,
- String userId) {
- ResponseFormat responseFormat = null;
+ public Either<List<Component>, ResponseFormat> getLatestVersionNotAbstractComponents(boolean isAbstractAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids,
+ String userId) {
try{
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Latest Version Not Abstract Components", false);
-
- if (resp.isLeft()) {
- List<Component> result = new ArrayList<>();
- List<String> componentsUidToFetch = new ArrayList<>();
- componentsUidToFetch.addAll(componentUids);
-
- if (!componentsUidToFetch.isEmpty()) {
- log.debug("Number of Components to fetch from graph is {}", componentsUidToFetch.size());
- Boolean isHighest = isHighest(highestFilter);
- Either<List<Component>, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade.getLatestVersionNotAbstractComponents(isAbstractAbstract, isHighest, componentTypeEnum, internalComponentType, componentsUidToFetch);
-
- if (nonCheckoutCompResponse.isLeft()) {
- log.debug("Retrived Resource successfully.");
- result.addAll(nonCheckoutCompResponse.left().value());
- } else {
- responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value()));
- }
+ validateUserExists(userId, "get Latest Version Not Abstract Components", false);
+ List<Component> result = new ArrayList<>();
+ List<String> componentsUidToFetch = new ArrayList<>();
+ componentsUidToFetch.addAll(componentUids);
+ if (!componentsUidToFetch.isEmpty()) {
+ log.debug("Number of Components to fetch from graph is {}", componentsUidToFetch.size());
+ Either<List<Component>, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade.getLatestVersionNotAbstractComponents(isAbstractAbstract, componentTypeEnum, internalComponentType, componentsUidToFetch);
+
+ if (nonCheckoutCompResponse.isLeft()) {
+ log.debug("Retrived Resource successfully.");
+ result.addAll(nonCheckoutCompResponse.left().value());
+ } else {
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value())));
}
- return Either.left(result);
- } else {
- responseFormat = resp.right().value();
}
+ return Either.left(result);
}
finally{
titanDao.commit();
}
- return Either.right(responseFormat);
}
private Boolean isHighest(HighestFilterEnum highestFilter) {
@@ -594,20 +541,15 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
ResponseFormat responseFormat = null;
try{
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Latest Version Not Abstract Components", false);
- if (resp.isLeft()) {
-
- Boolean isHighest = isHighest(highestFilter);
- Either<List<Component>, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade.getLatestVersionNotAbstractMetadataOnly(isAbstractAbstract, isHighest, componentTypeEnum, internalComponentType);
+ validateUserExists(userId, "get Latest Version Not Abstract Components", false);
+ Boolean isHighest = isHighest(highestFilter);
+ Either<List<Component>, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade.getLatestVersionNotAbstractMetadataOnly(isAbstractAbstract, componentTypeEnum, internalComponentType);
- if (nonCheckoutCompResponse.isLeft()) {
- log.debug("Retrived Resource successfully.");
- return Either.left(nonCheckoutCompResponse.left().value());
- }
- responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value()));
- } else {
- responseFormat = resp.right().value();
+ if (nonCheckoutCompResponse.isLeft()) {
+ log.debug("Retrived Resource successfully.");
+ return Either.left(nonCheckoutCompResponse.left().value());
}
+ responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value()));
} finally {
titanDao.commit();
}
@@ -686,7 +628,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
return artifactsBusinessLogic.generateAndSaveToscaArtifact(artifactDefinition, component, user, isInCertificationRequest, shouldLock, inTransaction, fetchTemplatesFromDB);
}
- public Either<ImmutablePair<String, byte[]>, ResponseFormat> getToscaModelByComponentUuid(ComponentTypeEnum componentType, String uuid, EnumMap<AuditingFieldsKeysEnum, Object> additionalParam) {
+ public Either<ImmutablePair<String, byte[]>, ResponseFormat> getToscaModelByComponentUuid(ComponentTypeEnum componentType, String uuid, ResourceCommonInfo resourceCommonInfo) {
Either<List<Component>, StorageOperationStatus> latestVersionEither = toscaOperationFacade.getComponentListByUuid(uuid, null);
@@ -706,7 +648,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
ResponseFormat response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, componentType));
return Either.right(response);
}
- additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
+ resourceCommonInfo.setResourceName(component.getName());
// TODO remove after migration - handle artifact not found(no
// placeholder)
if (null == component.getToscaArtifacts() || component.getToscaArtifacts().isEmpty()) {
@@ -741,11 +683,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
String descriptionUpdated = updatedComponent.getDescription();
String descriptionCurrent = currentComponent.getDescription();
if (descriptionUpdated != null && !descriptionCurrent.equals(descriptionUpdated)) {
- Either<Boolean, ResponseFormat> validateDescriptionResponse = validateDescriptionAndCleanup(user, updatedComponent, auditingAction);
- if (validateDescriptionResponse.isRight()) {
- ResponseFormat errorRespons = validateDescriptionResponse.right().value();
- return Either.right(errorRespons);
- }
+ validateDescriptionAndCleanup(user, updatedComponent, auditingAction);
currentComponent.setDescription(updatedComponent.getDescription());
}
return Either.left(true);
@@ -770,11 +708,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
String iconCurrent = currentComponent.getIcon();
if (iconUpdated != null && !iconCurrent.equals(iconUpdated)) {
if (!hasBeenCertified) {
- Either<Boolean, ResponseFormat> validatIconResponse = validateIcon(user, updatedComponent, null);
- if (validatIconResponse.isRight()) {
- ResponseFormat errorRespons = validatIconResponse.right().value();
- return Either.right(errorRespons);
- }
+ validateIcon(user, updatedComponent, null);
currentComponent.setIcon(updatedComponent.getIcon());
} else {
log.info("icon {} cannot be updated once the component has been certified once.", iconUpdated);
@@ -790,12 +724,14 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
log.trace("start deleteMarkedComponents");
Either<List<String>, StorageOperationStatus> deleteMarkedElements = toscaOperationFacade.deleteMarkedElements(componentType);
- titanDao.commit();
+
if ( deleteMarkedElements.isRight()){
+ titanDao.rollback();
ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteMarkedElements.right().value(), componentType));
return Either.right(responseFormat);
}
log.trace("end deleteMarkedComponents");
+ titanDao.commit();
return Either.left(deleteMarkedElements.left().value());
}
@@ -824,10 +760,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
public Either<UiComponentDataTransfer, ResponseFormat> getComponentDataFilteredByParams(String componentId, User user, List<String> dataParamsToReturn) {
if (user != null) {
- Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Get Component by filtered by ui params", false);
- if (eitherCreator.isRight()) {
- return Either.right(eitherCreator.right().value());
- }
+ validateUserExists(user, "Get Component by filtered by ui params", false);
}
UiComponentDataTransfer result = new UiComponentDataTransfer();
@@ -872,15 +805,15 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
return componentNonGenericInputs;
}
- protected <T extends Component> Either<Resource, ResponseFormat> fetchAndSetDerivedFromGenericType(T component){
+ protected <T extends Component> Resource fetchAndSetDerivedFromGenericType(T component){
Either<Resource, ResponseFormat> genericTypeEither = this.genericTypeBusinessLogic.fetchDerivedFromGenericType(component);
if(genericTypeEither.isRight()){
log.debug("Failed to fetch latest generic type for component {} of type", component.getName(), component.assetType());
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERIC_TYPE_NOT_FOUND, component.assetType()));
+ throw new ComponentException(ActionStatus.GENERIC_TYPE_NOT_FOUND, component.assetType());
}
Resource genericTypeResource = genericTypeEither.left().value();
component.setDerivedFromGenericInfo(genericTypeResource);
- return Either.left(genericTypeResource);
+ return genericTypeResource;
}
public Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> getFilteredComponentInstanceProperties(String componentId, Map<FilterKeyEnum, List<String>> filters, String userId) {
@@ -891,10 +824,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
response = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
if (userId != null && response == null) {
- Either<User, ResponseFormat> validateUserRes = validateUserExists(userId, "Get filtered component instance properties", false);
- if (validateUserRes.isRight()) {
- response = Either.right(validateUserRes.right().value());
- }
+ validateUserExists(userId, "Get filtered component instance properties", false);
}
if(response == null){
getResourceRes = toscaOperationFacade.getToscaElement(componentId);
@@ -1033,10 +963,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
Boolean shouldUpgrade = false;
String currentGenericType = clonedComponent.getDerivedFromGenericType();
String currentGenericVersion = clonedComponent.getDerivedFromGenericVersion();
- Either<Resource, ResponseFormat> fetchAndSetLatestGeneric = fetchAndSetDerivedFromGenericType(clonedComponent);
- if(fetchAndSetLatestGeneric.isRight())
- return Either.right(fetchAndSetLatestGeneric.right().value());
- Resource genericTypeResource = fetchAndSetLatestGeneric.left().value();
+ Resource genericTypeResource = fetchAndSetDerivedFromGenericType(clonedComponent);
if(null == currentGenericType || !currentGenericType.equals(genericTypeResource.getToscaResourceName()) || !currentGenericVersion.equals(genericTypeResource.getVersion())){
shouldUpgrade = upgradeToLatestGeneric(clonedComponent, genericTypeResource);
if(!shouldUpgrade) {
@@ -1101,7 +1028,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
log.debug("input {} cannot be overriden, check out performed without upgrading to latest generic", eitherMerged.right().value());
return false;
}
- componentToCheckOut.setInputs(new ArrayList<InputDefinition>(eitherMerged.left().value().values()));
+ componentToCheckOut.setInputs(new ArrayList<>(eitherMerged.left().value().values()));
return true;
}
@@ -1132,7 +1059,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
return isMatchingType;
}
- protected String cleanUpText(String text){
+ String cleanUpText(String text){
text = ValidationUtils.removeNoneUtf8Chars(text);
text = ValidationUtils.normaliseWhitespace(text);
text = ValidationUtils.stripOctets(text);
@@ -1145,6 +1072,9 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
return Either.right(ActionStatus.GENERAL_ERROR);
}
+ public List<GroupDefinition> throwComponentException(ResponseFormat responseFormat) {
+ throw new ComponentException(responseFormat);
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogicProvider.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogicProvider.java
new file mode 100644
index 0000000000..3025084239
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogicProvider.java
@@ -0,0 +1,37 @@
+package org.openecomp.sdc.be.components.impl;
+
+import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.springframework.stereotype.Component;
+
+@Component
+public class ComponentBusinessLogicProvider {
+
+ private final ResourceBusinessLogic resourceBusinessLogic;
+ private final ServiceBusinessLogic serviceBusinessLogic;
+ private final ProductBusinessLogic productBusinessLogic;
+
+ public ComponentBusinessLogicProvider(ResourceBusinessLogic resourceBusinessLogic, ServiceBusinessLogic serviceBusinessLogic, ProductBusinessLogic productBusinessLogic) {
+ this.resourceBusinessLogic = resourceBusinessLogic;
+ this.serviceBusinessLogic = serviceBusinessLogic;
+ this.productBusinessLogic = productBusinessLogic;
+ }
+
+ public ComponentBusinessLogic getInstance(ComponentTypeEnum componentTypeEnum) {
+ switch (componentTypeEnum) {
+ case SERVICE:
+ return serviceBusinessLogic;
+ case PRODUCT:
+ return productBusinessLogic;
+ case RESOURCE:
+ case RESOURCE_INSTANCE:
+ return resourceBusinessLogic;
+ default:
+ BeEcompErrorManager.getInstance().logBeSystemError("getComponentBL");
+ throw new ComponentException(ActionStatus.INVALID_CONTENT_PARAM, componentTypeEnum.getValue());
+ }
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java
index 0ff00913e0..35493f715c 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java
@@ -26,7 +26,7 @@ import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.openecomp.sdc.be.components.impl.version.PostChangeVersionOperationOrchestrator;
+import org.openecomp.sdc.be.components.impl.instance.ComponentInstanceChangeOperationOrchestrator;
import org.openecomp.sdc.be.components.merge.instance.ComponentInstanceMergeDataBusinessLogic;
import org.openecomp.sdc.be.components.merge.instance.DataForMergeHolder;
import org.openecomp.sdc.be.components.validation.ComponentValidations;
@@ -67,6 +67,7 @@ import org.openecomp.sdc.be.model.RequirementDefinition;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.jsontitan.operations.ForwardingPathOperation;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation;
@@ -81,10 +82,9 @@ import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.datastructure.Wrapper;
import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
+import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
@@ -107,7 +107,15 @@ import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputV
@org.springframework.stereotype.Component
public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
- private static final Logger log = LoggerFactory.getLogger(ComponentInstanceBusinessLogic.class);
+ private static final Logger log = Logger.getLogger(ComponentInstanceBusinessLogic.class.getName());
+ private static final String VF_MODULE = "org.openecomp.groups.VfModule";
+ public static final String TRY_TO_CREATE_ENTRY_ON_GRAPH = "Try to create entry on graph";
+ public static final String FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE = "Failed to create entry on graph for component instance {}";
+ public static final String ENTITY_ON_GRAPH_IS_CREATED = "Entity on graph is created.";
+ public static final String INVALID_COMPONENT_TYPE = "invalid component type";
+ public static final String FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID = "Failed to retrieve component, component id {}";
+ public static final String FAILED_TO_LOCK_SERVICE = "Failed to lock service {}";
+ public static final String CREATE_OR_UPDATE_PROPERTY_VALUE = "CreateOrUpdatePropertyValue";
@Autowired
private IComponentInstanceOperation componentInstanceOperation;
@@ -119,9 +127,11 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
private ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL;
@Autowired
- private PostChangeVersionOperationOrchestrator postChangeVersionOperationOrchestrator;
+ private ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator;
+
+ @Autowired
+ private ForwardingPathOperation forwardingPathOperation;
- public static final String VF_MODULE = "org.openecomp.groups.VfModule";
public ComponentInstanceBusinessLogic() {
}
@@ -207,12 +217,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
ComponentTypeEnum containerComponentType;
try {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "create Component Instance", inTransaction);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- } else {
- user = resp.left().value();
- }
+ user = validateUserExists(userId, "create Component Instance", inTransaction);
Either<Boolean, ResponseFormat> validateValidJson = validateJsonBody(resourceInstance, ComponentInstance.class);
if (validateValidJson.isRight()) {
@@ -329,12 +334,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
ComponentInstance resourceInstance = createAndAssotiateInfo.getNode();
RequirementCapabilityRelDef associationInfo = createAndAssotiateInfo.getAssociate();
- Either<User, ResponseFormat> resp = validateUserExists(userId, "create And Associate RI To RI", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ User user = validateUserExists(userId, "create And Associate RI To RI", false);
- User user = resp.left().value();
Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
if (validateComponentType.isRight()) {
return Either.right(validateComponentType.right().value());
@@ -585,10 +586,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance, boolean inTransaction,
boolean needLock, boolean createNewTransaction) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "update Component Instance", inTransaction);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "update Component Instance", inTransaction);
Either<ComponentInstance, ResponseFormat> resultOp = null;
@@ -648,16 +646,12 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
// New Multiple Instance Update API
- public Either<List<ComponentInstance>, ResponseFormat> updateComponentInstance(String containerComponentParam, String containerComponentId, String userId, List<ComponentInstance> componentInstanceList, boolean needLock,
- boolean createNewTransaction) {
+ public Either<List<ComponentInstance>, ResponseFormat> updateComponentInstance(String containerComponentParam, String containerComponentId, String userId, List<ComponentInstance> componentInstanceList, boolean needLock) {
Either<List<ComponentInstance>, ResponseFormat> resultOp = null;
org.openecomp.sdc.be.model.Component containerComponent = null;
try {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "update Component Instance", true);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "update Component Instance", true);
Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
if (validateComponentType.isRight()) {
@@ -857,10 +851,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
public Either<ComponentInstance, ResponseFormat> deleteComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Component Instance", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "delete Component Instance", false);
Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
if (validateComponentType.isRight()) {
@@ -992,7 +983,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getInputs())) {
List<InputDefinition> inputsToDelete = containerComponent.getInputs().stream().filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
if (CollectionUtils.isNotEmpty(inputsToDelete)) {
- StorageOperationStatus deleteInputsRes = toscaOperationFacade.deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, containerComponent.getComponentType(), inputsToDelete);
+ StorageOperationStatus deleteInputsRes = toscaOperationFacade.deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, inputsToDelete);
if (deleteInputsRes != StorageOperationStatus.OK) {
log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId);
resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType), componentInstanceId));
@@ -1032,10 +1023,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction, boolean needLock,
boolean createNewTransaction) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "associate Ri To RI", inTransaction);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "associate Ri To RI", inTransaction);
Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
@@ -1106,10 +1094,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
public Either<RequirementCapabilityRelDef, ResponseFormat> dissociateRIFromRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "dissociate RI From RI", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "dissociate RI From RI", false);
Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
@@ -1177,10 +1162,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = null;
RequirementCapabilityRelDef foundRelation = null;
- Either<User, ResponseFormat> validateUserRes = validateUserExists(userId, "get relation by Id", false);
- if (validateUserRes.isRight()) {
- resultOp = Either.right(validateUserRes.right().value());
- }
+ validateUserExists(userId, "get relation by Id", false);
+
if(resultOp == null){
validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
if (validateComponentExists.isRight()) {
@@ -1366,7 +1349,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
Either<ComponentInstanceProperty, ResponseFormat> result = null;
Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
- validateUserExist(userId, "create Or Update Attribute Value", errorWrapper);
+ validateUserExist(userId, "create Or Update Attribute Value");
if (errorWrapper.isEmpty()) {
validateComponentTypeEnum(componentTypeEnum, "CreateOrUpdateAttributeValue", errorWrapper);
}
@@ -1440,10 +1423,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
/*-------------------------------Validations---------------------------------*/
- Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Properties Values", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "create Or Update Properties Values", false);
if (componentTypeEnum == null) {
BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertiesValues", "invalid component type", ErrorSeverity.INFO);
@@ -1642,10 +1622,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
Either<List<ComponentInstanceInput>, ResponseFormat> resultOp = null;
- Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Property Value", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "create Or Update Property Value", false);
if (componentTypeEnum == null) {
BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
@@ -1715,10 +1692,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
- Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Property Value", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "create Or Update Property Value", false);
if (componentTypeEnum == null) {
BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
@@ -1812,10 +1786,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
Either<ComponentInstanceInput, ResponseFormat> resultOp = null;
- Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Input Value", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "create Or Update Input Value", false);
if (componentTypeEnum == null) {
BeEcompErrorManager.getInstance().logInvalidInputError("createOrUpdateInputValue", "invalid component type", ErrorSeverity.INFO);
@@ -1902,10 +1873,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
public Either<ComponentInstanceProperty, ResponseFormat> deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId, String resourceInstanceId, String propertyValueId, String userId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Property Value", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "delete Property Value", false);
Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
@@ -2066,12 +2034,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
public Either<ComponentInstance, ResponseFormat> changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance newComponentInstance) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "change Component Instance Version", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ User user = validateUserExists(userId, "change Component Instance Version", false);
- User user = resp.left().value();
Either<ComponentInstance, ResponseFormat> resultOp = null;
Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
@@ -2101,7 +2065,17 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value();
+ return changeInstanceVersion(containerComponent, currentResourceInstance, newComponentInstance, user, containerComponentType );
+ }
+
+ public Either<ComponentInstance, ResponseFormat> changeInstanceVersion(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance currentResourceInstance,
+ ComponentInstance newComponentInstance, User user, final ComponentTypeEnum containerComponentType ) {
+ Either<ComponentInstance, ResponseFormat> resultOp = null;
+ Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus;
+
Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "changeComponentInstanceVersion");
+ String containerComponentId = containerComponent.getUniqueId();
+ String componentInstanceId = currentResourceInstance.getUniqueId();
if (lockComponent.isRight()) {
return Either.right(lockComponent.right().value());
}
@@ -2198,7 +2172,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return Either.right(mergeStatusEither.right().value());
}
- ActionStatus postChangeVersionResult = postChangeVersionOperationOrchestrator.doPostChangeVersionOperations(containerComponent, currentResourceInstance, newComponentInstance);
+ ActionStatus postChangeVersionResult = onChangeInstanceOperationOrchestrator.doPostChangeVersionOperations(containerComponent, currentResourceInstance, newComponentInstance);
if (postChangeVersionResult != ActionStatus.OK) {
return Either.right(componentsUtils.getResponseFormat(postChangeVersionResult));
}
@@ -2233,11 +2207,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
try {
- Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, ECOMP_ERROR_CONTEXT, false);
- if (validateUserExists.isRight()) {
- resultOp = Either.right(validateUserExists.right().value());
- return resultOp;
- }
+ validateUserExists(userId, ECOMP_ERROR_CONTEXT, false);
Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentTypeParam);
if (validateComponentType.isRight()) {
@@ -2305,19 +2275,19 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return result;
}
- public Either<ComponentInstance, ResponseFormat> deleteServiceProxy(String containerComponentType, String containerComponentId, String serviceProxyId, String userId) {
+ public Either<ComponentInstance, ResponseFormat> deleteServiceProxy() {
// TODO Add implementation
Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
return result;
}
- public Either<ComponentInstance, ResponseFormat> createServiceProxy(String containerComponentType, String containerComponentId, String userId, ComponentInstance componentInstance) {
+ public Either<ComponentInstance, ResponseFormat> createServiceProxy() {
// TODO Add implementation
Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
return result;
}
- public Either<ComponentInstance, ResponseFormat> changeServiceProxyVersion(String containerComponentType, String containerComponentId, String serviceProxyId, String userId) {
+ public Either<ComponentInstance, ResponseFormat> changeServiceProxyVersion() {
// TODO Add implementation
Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
return result;
@@ -2411,10 +2381,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
try {
- Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, "Get Component Instance Properties By Id", false);
- if (validateUserExists.isRight()) {
- resultOp = Either.right(validateUserExists.right().value());
- }
+ validateUserExists(userId, "Get Component Instance Properties By Id", false);
if(resultOp == null){
Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentType);
if (validateComponentType.isRight()) {
@@ -2517,10 +2484,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
List<ComponentInstanceProperty> properties, String userId) {
Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
- Either<User, ResponseFormat> resp = validateUserExists(userId, "update instance capability property", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "update instance capability property", false);
if (componentTypeEnum == null) {
BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", "invalid component type", ErrorSeverity.INFO);
@@ -2589,10 +2553,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
List<ComponentInstanceProperty> properties, String userId) {
Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
- Either<User, ResponseFormat> resp = validateUserExists(userId, "update instance capability property", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "update instance capability property", false);
if (componentTypeEnum == null) {
BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", "invalid component type", ErrorSeverity.INFO);
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentLocker.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentLocker.java
new file mode 100644
index 0000000000..8328098980
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentLocker.java
@@ -0,0 +1,55 @@
+package org.openecomp.sdc.be.components.impl;
+
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.operations.StorageException;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation;
+import org.openecomp.sdc.common.log.wrappers.Logger;
+
+
+@org.springframework.stereotype.Component
+public class ComponentLocker {
+
+ private static final Logger log = Logger.getLogger(ComponentLocker.class.getName());
+ private final GraphLockOperation graphLockOperation;
+
+ public ComponentLocker(GraphLockOperation graphLockOperation) {
+ this.graphLockOperation = graphLockOperation;
+ }
+
+ public void lock(String id, ComponentTypeEnum componentType) {
+ lock(id, componentType.getNodeType());
+ }
+
+ public void lock(Component component) {
+ doLockComponent(component.getUniqueId(), component.getComponentType().getNodeType());
+ }
+
+ public void lock(String id, NodeTypeEnum nodeTypeEnum) {
+ doLockComponent(id, nodeTypeEnum);
+ }
+
+ private void doLockComponent(String id, NodeTypeEnum nodeTypeEnum) {
+ log.debug("#doLockComponent - locking component {} of type {}", id, nodeTypeEnum);
+ StorageOperationStatus storageOperationStatus = graphLockOperation.lockComponent(id, nodeTypeEnum);
+ if (storageOperationStatus != StorageOperationStatus.OK) {
+ log.debug("#doLockComponent - failed to lock component {} with status {}", id, storageOperationStatus);
+ throw new StorageException(storageOperationStatus);
+ }
+ }
+
+ public void unlock(String id, ComponentTypeEnum componentType) {
+ unlock(id, componentType.getNodeType());
+ }
+
+ public void unlock(String id, NodeTypeEnum nodeTypeEnum) {
+ log.debug("#unlock - unlocking component {} of type {}", id, nodeTypeEnum);
+ StorageOperationStatus storageOperationStatus = graphLockOperation.unlockComponent(id, nodeTypeEnum);
+ if (storageOperationStatus != StorageOperationStatus.OK) {
+ log.debug("#unlock - failed to unlock component {} with status {}", id, storageOperationStatus);
+ throw new StorageException(storageOperationStatus, id);
+ }
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java
index b591c9e1b9..fa39cf0dca 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java
@@ -20,16 +20,8 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Optional;
-import java.util.Set;
-import java.util.stream.Collectors;
-
import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
import org.openecomp.sdc.be.model.ComponentInstance;
@@ -39,7 +31,10 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-import fj.data.Either;
+import java.util.*;
+import java.util.Collection;
+import java.util.Map.Entry;
+import java.util.stream.Collectors;
/**
* This class holds the logic of arranging resource instance on the canvas for imported VF
@@ -63,25 +58,24 @@ public class CompositionBusinessLogic {
LEFT, RIGHT, UP, DOWN
};
- protected Either<List<ComponentInstance>, ResponseFormat> setPositionsForComponentInstances(Resource resource, String userId) {
- Either<List<ComponentInstance>, ResponseFormat> result = Either.left(resource.getComponentInstances());
-
+ protected void setPositionsForComponentInstances(Resource resource, String userId) {
boolean isNotAllPositionsCalculated = resource.getComponentInstances() == null
- || resource.getComponentInstances().stream().filter(p -> (p.getPosX() == null || p.getPosX().isEmpty()) || (p.getPosY() == null || p.getPosY().isEmpty())).findAny().isPresent();
-
+ || resource.getComponentInstances().stream().anyMatch(p -> (p.getPosX() == null || p.getPosX().isEmpty()) || (p.getPosY() == null || p.getPosY().isEmpty()));
if (isNotAllPositionsCalculated && resource.getComponentInstances() != null) {
// Arrange Icons In Spiral Pattern
Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations = buildSpiralPatternPositioningForComponentInstances(resource);
-
// Set Relative Locations According to Canvas Size
- componentInstanceLocations.entrySet().stream().forEach(e -> setRelativePosition(e));
-
+ componentInstanceLocations.entrySet().forEach(this::setRelativePosition);
// Update in DB
- result = componentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME, resource.getUniqueId(), userId, resource.getComponentInstances(), false, false);
-
+ componentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME,resource.getUniqueId(),
+ userId, resource.getComponentInstances(), false)
+ .left()
+ .on(this::throwComponentException);
}
- return result;
+ }
+ private List<ComponentInstance> throwComponentException(ResponseFormat responseFormat) {
+ throw new ComponentException(responseFormat);
}
private void setRelativePosition(Entry<ImmutablePair<Double, Double>, ComponentInstance> entry) {
@@ -128,7 +122,7 @@ public class CompositionBusinessLogic {
componentInstances.addAll(resource.getComponentInstances());
Map<ComponentInstance, List<ComponentInstance>> connectededCps = getCpsConnectedToVFC(componentInstances, resource);
// Remove all cp that are connected from the list
- componentInstances.removeAll(connectededCps.values().stream().flatMap(e -> e.stream()).collect(Collectors.toList()));
+ componentInstances.removeAll(connectededCps.values().stream().flatMap(Collection::stream).collect(Collectors.toList()));
buildSpiralPatternForMajorComponents(componentInstanceLocations, componentInstances);
buildCirclePatternForCps(componentInstanceLocations, connectededCps);
@@ -154,7 +148,7 @@ public class CompositionBusinessLogic {
for (ComponentInstance currCp : cpsGroup) {
double cpXposition = xCenter + CompositionBusinessLogic.CP_RADIUS_FACTOR * Math.cos(currentAngle);
double cpYposition = yCenter + CompositionBusinessLogic.CP_RADIUS_FACTOR * Math.sin(currentAngle);
- componentInstLocations.put(new ImmutablePair<Double, Double>(cpXposition, cpYposition), currCp);
+ componentInstLocations.put(new ImmutablePair<>(cpXposition, cpYposition), currCp);
currentAngle += angleBetweenCps;
}
@@ -168,9 +162,9 @@ public class CompositionBusinessLogic {
for (ComponentInstance curr : componentInstances) {
elementsCounter++;
if (elementsCounter == 1) {
- currPlacement = new ImmutablePair<Double, Double>(0D, 0D);
+ currPlacement = new ImmutablePair<>(0D, 0D);
} else if (elementsCounter == 2) {
- currPlacement = new ImmutablePair<Double, Double>(-1D, 0D);
+ currPlacement = new ImmutablePair<>(-1D, 0D);
relationToPrevElement = RelativePosition.LEFT;
} else {
relationToPrevElement = getRelativePositionForCurrentElement(componentInstanceLocations, relationToPrevElement, prevPlacement);
@@ -263,19 +257,19 @@ public class CompositionBusinessLogic {
switch (relativeLocation) {
case LEFT: {
- relativeElementPosition = new ImmutablePair<Double, Double>(currElement.getLeft() - 1, currElement.getRight());
+ relativeElementPosition = new ImmutablePair<>(currElement.getLeft() - 1, currElement.getRight());
break;
}
case RIGHT: {
- relativeElementPosition = new ImmutablePair<Double, Double>(currElement.getLeft() + 1, currElement.getRight());
+ relativeElementPosition = new ImmutablePair<>(currElement.getLeft() + 1, currElement.getRight());
break;
}
case UP: {
- relativeElementPosition = new ImmutablePair<Double, Double>(currElement.getLeft(), currElement.getRight() + 1);
+ relativeElementPosition = new ImmutablePair<>(currElement.getLeft(), currElement.getRight() + 1);
break;
}
case DOWN: {
- relativeElementPosition = new ImmutablePair<Double, Double>(currElement.getLeft(), currElement.getRight() - 1);
+ relativeElementPosition = new ImmutablePair<>(currElement.getLeft(), currElement.getRight() - 1);
break;
}
default: {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java
index 8ab124c994..213c4b67db 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java
@@ -20,28 +20,23 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.Date;
-
+import fj.data.Either;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.ConsumerDefinition;
import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.ConsumerOperation;
import org.openecomp.sdc.be.resources.data.ConsumerData;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.be.user.IUserBusinessLogic;
import org.openecomp.sdc.be.user.Role;
+import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
-import fj.data.Either;
+import java.util.Date;
@Component("ConsumerBusinessLogic")
public class ConsumerBusinessLogic extends BaseBusinessLogic {
@@ -49,20 +44,12 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
private static final String CONSUMER_NAME = "Consumer name";
private static final String CONSUMER_SALT = "Consumer salt";
private static final String CONSUMER_PW = "Consumer password";
-
- @javax.annotation.Resource
- private IUserBusinessLogic userAdmin;
-
- @javax.annotation.Resource
- private ComponentsUtils componentsUtils;
+ public static final String AUDIT_BEFORE_SENDING_RESPONSE = "audit before sending response";
@javax.annotation.Resource
private ConsumerOperation consumerOperation;
- @javax.annotation.Resource
- private IGraphLockOperation graphLockOperation;
-
- private static final Logger log = LoggerFactory.getLogger(ConsumerBusinessLogic.class);
+ private static final Logger log = Logger.getLogger(ConsumerBusinessLogic.class.getName());
public Either<ConsumerDefinition, ResponseFormat> createConsumer(User user, ConsumerDefinition consumer) {
@@ -75,7 +62,7 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
user = userValidation.left().value();
consumer.setLastModfierAtuid(user.getUserId());
- Either<ConsumerDefinition, ResponseFormat> consumerValidationResponse = validateConsumer(consumer, user, AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS);
+ Either<ConsumerDefinition, ResponseFormat> consumerValidationResponse = validateConsumer(consumer);
if (consumerValidationResponse.isRight()) {
ResponseFormat responseFormat = consumerValidationResponse.right().value();
componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user);
@@ -94,7 +81,7 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
try {
Either<ConsumerData, StorageOperationStatus> getResponse = consumerOperation.getCredentials(consumerName);
if (getResponse.isLeft() && getResponse.left().value() != null) {
- return updateConsumer(consumer, user, true);
+ return updateConsumer(consumer);
}
Date date = new Date();
@@ -123,7 +110,7 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
if (user.getUserId() == null || user.getUserId().trim().isEmpty()) {
log.debug("createEcompUser method - user is missing. userId= {}", user.getUserId());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
- log.debug("audit before sending response");
+ log.debug(AUDIT_BEFORE_SENDING_RESPONSE);
componentsUtils.auditConsumerCredentialsEvent(auditAction, consumer, responseFormat, user);
return Either.right(responseFormat);
}
@@ -132,7 +119,7 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
if (eitherCreator.isRight() || eitherCreator.left().value() == null) {
log.debug("createEcompUser method - user is not listed. userId= {}", user.getUserId());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_ACCESS);
- log.debug("audit before sending response");
+ log.debug(AUDIT_BEFORE_SENDING_RESPONSE);
componentsUtils.auditConsumerCredentialsEvent(auditAction, consumer, responseFormat, user);
return Either.right(responseFormat);
}
@@ -143,14 +130,14 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
if (!user.getRole().equals(Role.ADMIN.name())) {
log.info("role {} is not allowed to perform this action", user.getRole());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
- log.debug("audit before sending response");
+ log.debug(AUDIT_BEFORE_SENDING_RESPONSE);
componentsUtils.auditConsumerCredentialsEvent(auditAction, consumer, responseFormat, user);
return Either.right(responseFormat);
}
return Either.left(user);
}
- private Either<ConsumerDefinition, ResponseFormat> validateConsumer(ConsumerDefinition consumer, User user, AuditingActionEnum audatingAction) {
+ private Either<ConsumerDefinition, ResponseFormat> validateConsumer(ConsumerDefinition consumer) {
Either<ConsumerDefinition, ResponseFormat> validateConsumerName = validateConsumerName(consumer);
if (validateConsumerName.isRight()) {
return Either.right(validateConsumerName.right().value());
@@ -286,7 +273,7 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
return Either.left(consumer);
}
- public Either<ConsumerDefinition, ResponseFormat> updateConsumer(ConsumerDefinition consumer, User modifier, boolean isCreateRequest) {
+ public Either<ConsumerDefinition, ResponseFormat> updateConsumer(ConsumerDefinition consumer) {
Either<ConsumerData, StorageOperationStatus> updateResult = consumerOperation.updateCredentials(new ConsumerData(consumer));
if (updateResult.isRight()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForConsumer(updateResult.right().value()));
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java
index 2609dfcbff..b008e516cb 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java
@@ -20,59 +20,53 @@
package org.openecomp.sdc.be.components.impl;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.StringReader;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.Properties;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
-
+import fj.data.Either;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.tosca.CsarUtils;
+import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.GeneralUtility;
import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import fj.data.Either;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.StringReader;
+import java.util.*;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
public class CsarValidationUtils {
- private static final Logger log = LoggerFactory.getLogger(CsarValidationUtils.class);
+ private static final Logger log = Logger.getLogger(CsarValidationUtils.class.getName());
private static final String TOSCA_META_FILE_VERSION = "TOSCA-Meta-File-Version";
-
private static final String CSAR_VERSION = "CSAR-Version";
-
private static final String CREATED_BY = "Created-By";
-
private static final String NEW_LINE_DELM = "\n";
-
- public final static String TOSCA_METADATA = "TOSCA-Metadata";
- public final static String TOSCA_FILE = "TOSCA.meta";
- public final static String DEL_PATTERN = "([/\\\\]+)";
+ public static final String TOSCA_METADATA = "TOSCA-Metadata";
+ public static final String TOSCA_FILE = "TOSCA.meta";
+ public static final String DEL_PATTERN = "([/\\\\]+)";
public static final String TOSCA_METADATA_PATH_PATTERN = TOSCA_METADATA +
// Artifact Group (i.e Deployment/Informational)
DEL_PATTERN + TOSCA_FILE;
public static final String TOSCA_META_ENTRY_DEFINITIONS = "Entry-Definitions";
-
private static final String[] TOSCA_METADATA_FIELDS = { TOSCA_META_FILE_VERSION, CSAR_VERSION, CREATED_BY, TOSCA_META_ENTRY_DEFINITIONS };
-
- public final static String ARTIFACTS_METADATA_FILE = "HEAT.meta";
-
+ public static final String ARTIFACTS_METADATA_FILE = "HEAT.meta";
public static final String TOSCA_CSAR_EXTENSION = ".csar";
-/**
+ public static final String TOSCA_METADATA_TOSCA_META_FILE_IS_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_CSAR_ID = "TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}";
+ public static final String TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID = "TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id ";
+ public static final String CSAR_INTERNALS_ARE_INVALID = "CSAR internals are invalid";
+ public static final String ENTRY_DEFINITIONS_ENTRY_NOT_FOUND_IN_TOSCA_METADATA_TOSCA_META_FILE_CSAR_ID = "Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file, csar ID {}";
+ public static final String FILE_NOT_FOUND_IN_CSAR_WITH_ID = " file not found in CSAR with id ";
+ public static final String CSAR_STRUCTURE_IS_INVALID = "CSAR structure is invalid";
+ public static final String ENTRY_DEFINITIONS = "Entry-Definitions ";
+
+ /**
* Validates Csar
* @param csar
* @param csarUUID
@@ -103,7 +97,7 @@ public class CsarValidationUtils {
for(int i = 0; i < numberOfArtifacts; ++i ){
collectNonUniqueArtifact(paths, i, numberOfArtifacts, nonUniqueArtifactsToRemove);
}
- nonUniqueArtifactsToRemove.stream().forEach(path->csar.remove(path));
+ nonUniqueArtifactsToRemove.stream().forEach(csar::remove);
}
private static void collectNonUniqueArtifact( String[] paths, int currInd, int numberOfArtifacts, List<String> nonUniqueArtifactsToRemove) {
@@ -145,8 +139,8 @@ public class CsarValidationUtils {
Pattern pattern = Pattern.compile(TOSCA_METADATA_PATH_PATTERN);
Optional<String> keyOp = csar.keySet().stream().filter(k -> pattern.matcher(k).matches()).findAny();
if(!keyOp.isPresent()){
- log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
+ log.debug(TOSCA_METADATA_TOSCA_META_FILE_IS_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_CSAR_ID, csarUUID);
+ BeEcompErrorManager.getInstance().logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
}
byte[] toscaMetaBytes = csar.get(keyOp.get());
@@ -155,8 +149,8 @@ public class CsarValidationUtils {
String propStr = new String(toscaMetaBytes);
props.load(new StringReader(propStr.replace("\\","\\\\")));
} catch (IOException e) {
- log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID, e);
- BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
+ log.debug(TOSCA_METADATA_TOSCA_META_FILE_IS_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_CSAR_ID, csarUUID, e);
+ BeEcompErrorManager.getInstance().logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
}
@@ -166,8 +160,8 @@ public class CsarValidationUtils {
String result = list.stream().map(x -> x).collect(Collectors.joining(DEL_PATTERN));
keyOp = csar.keySet().stream().filter(k -> Pattern.compile(result).matcher(k).matches()).findAny();
if(!keyOp.isPresent()){
- log.debug("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file, csar ID {}", csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
+ log.debug(ENTRY_DEFINITIONS_ENTRY_NOT_FOUND_IN_TOSCA_METADATA_TOSCA_META_FILE_CSAR_ID, csarUUID);
+ BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file in CSAR with id " + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, yamlFileName));
}
@@ -175,20 +169,20 @@ public class CsarValidationUtils {
byte[] yamlFileBytes = csar.get(yamlFileName);
if (yamlFileBytes == null) {
log.debug("Entry-Definitions {} file not found in csar, csar ID {}", yamlFileName, csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + yamlFileName + " file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance().logInternalDataError(ENTRY_DEFINITIONS + yamlFileName + FILE_NOT_FOUND_IN_CSAR_WITH_ID + csarUUID, CSAR_STRUCTURE_IS_INVALID, ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, yamlFileName));
}
String yamlFileContents = new String(yamlFileBytes);
- return Either.left(new ImmutablePair<String, String>(yamlFileName, yamlFileContents));
+ return Either.left(new ImmutablePair<>(yamlFileName, yamlFileContents));
}
public static Either<ImmutablePair<String, String>, ResponseFormat> getArtifactsMeta(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
if( !csar.containsKey(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE) ) {
- log.debug("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file, csar ID {}", csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
+ log.debug(ENTRY_DEFINITIONS_ENTRY_NOT_FOUND_IN_TOSCA_METADATA_TOSCA_META_FILE_CSAR_ID, csarUUID);
+ BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file in CSAR with id " + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, ARTIFACTS_METADATA_FILE));
}
@@ -196,19 +190,19 @@ public class CsarValidationUtils {
byte[] artifactsMetaBytes = csar.get(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE);
if (artifactsMetaBytes == null) {
log.debug("Entry-Definitions {}{} file not found in csar, csar ID {}", CsarUtils.ARTIFACTS_PATH, ARTIFACTS_METADATA_FILE, csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE + " file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance().logInternalDataError(ENTRY_DEFINITIONS + CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE + FILE_NOT_FOUND_IN_CSAR_WITH_ID + csarUUID, CSAR_STRUCTURE_IS_INVALID, ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE));
}
String artifactsFileContents = new String(artifactsMetaBytes);
- return Either.left(new ImmutablePair<String, String>(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE, artifactsFileContents));
+ return Either.left(new ImmutablePair<>(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE, artifactsFileContents));
}
public static Either<ImmutablePair<String, byte[]>, ResponseFormat> getArtifactsContent(String csarUUID, Map<String, byte[]> csar, String artifactPath, String artifactName, ComponentsUtils componentsUtils) {
if (!csar.containsKey(artifactPath)) {
log.debug("Entry-Definitions entry not found in Artifacts/HEAT.meta file, csar ID {}", csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file in CSAR with id " + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, CsarUtils.ARTIFACTS_PATH + artifactName, csarUUID));
}
@@ -216,11 +210,11 @@ public class CsarValidationUtils {
byte[] artifactFileBytes = csar.get(artifactPath);
if (artifactFileBytes == null) {
log.debug("Entry-Definitions {}{} file not found in csar, csar ID {}", CsarUtils.ARTIFACTS_PATH, artifactName, csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + artifactPath + " file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance().logInternalDataError(ENTRY_DEFINITIONS + artifactPath + FILE_NOT_FOUND_IN_CSAR_WITH_ID + csarUUID, CSAR_STRUCTURE_IS_INVALID, ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, artifactPath, csarUUID));
}
- return Either.left(new ImmutablePair<String, byte[]>(artifactName, artifactFileBytes));
+ return Either.left(new ImmutablePair<>(artifactName, artifactFileBytes));
}
private static Either<Boolean, ResponseFormat> validateTOSCAMetadataFile(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
@@ -228,8 +222,8 @@ public class CsarValidationUtils {
Pattern pattern = Pattern.compile(TOSCA_METADATA_PATH_PATTERN);
Optional<String> keyOp = csar.keySet().stream().filter(k -> pattern.matcher(k).matches()).findAny();
if(!keyOp.isPresent()){
- log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
+ log.debug(TOSCA_METADATA_TOSCA_META_FILE_IS_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_CSAR_ID, csarUUID);
+ BeEcompErrorManager.getInstance().logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
}
@@ -237,8 +231,8 @@ public class CsarValidationUtils {
String toscaMetadata = new String(toscaMetaBytes);
String[] splited = toscaMetadata.split(NEW_LINE_DELM);
if (splited == null || splited.length < TOSCA_METADATA_FIELDS.length) {
- log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
+ log.debug(TOSCA_METADATA_TOSCA_META_FILE_IS_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_CSAR_ID, csarUUID);
+ BeEcompErrorManager.getInstance().logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
}
@@ -260,30 +254,29 @@ public class CsarValidationUtils {
try {
props.load(new ByteArrayInputStream(splited[index].getBytes()));
} catch (IOException e) {
- log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID, e);
- BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
+ log.debug(TOSCA_METADATA_TOSCA_META_FILE_IS_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_CSAR_ID, csarUUID, e);
+ BeEcompErrorManager.getInstance().logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
}
if (!props.containsKey(toscaField)) {
log.debug("TOSCA.meta file format is invalid: No new line after block_0 as expected in csar, csar ID {}", csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance().logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
}
String value = props.getProperty(toscaField);
if (value == null || value.isEmpty()) {
- log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
+ log.debug(TOSCA_METADATA_TOSCA_META_FILE_IS_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_CSAR_ID, csarUUID);
+ BeEcompErrorManager.getInstance().logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
}
// TOSCA-Meta-File-Version & CSAR-Version : digit.digit - format
// validation
- if (toscaField.equals(TOSCA_META_FILE_VERSION) || toscaField.equals(CSAR_VERSION)) {
- if (!validateTOSCAMetaProperty(value)) {
- log.debug("TOSCA-Metadata/TOSCA.meta file contains {} in wrong format (digit.digit), csar ID {}", toscaField, csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
- }
+ if ((toscaField.equals(TOSCA_META_FILE_VERSION) || toscaField.equals(CSAR_VERSION)) && !validateTOSCAMetaProperty(value)) {
+ log.debug("TOSCA-Metadata/TOSCA.meta file contains {} in wrong format (digit.digit), csar ID {}", toscaField, csarUUID);
+ BeEcompErrorManager.getInstance()
+ .logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
}
index++;
}
@@ -311,14 +304,14 @@ public class CsarValidationUtils {
if(!keyOp.isPresent()){
log.debug("TOSCA-Metadata/TOSCA.meta file not found in csar, csar ID {}", csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not found in CSAR with id " + csarUUID, CSAR_STRUCTURE_IS_INVALID, ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID));
}
byte[] toscaMetaBytes = csar.get(keyOp.get());
- // && exchanged for ||
+
if (toscaMetaBytes == null || toscaMetaBytes.length == 0) {
log.debug("TOSCA-Metadata/TOSCA.meta file not found in csar, csar ID {}", csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not found in CSAR with id " + csarUUID, CSAR_STRUCTURE_IS_INVALID, ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID));
}
@@ -339,9 +332,7 @@ public class CsarValidationUtils {
}
public static boolean isCsarPayloadName(String payloadName) {
- if (payloadName == null)
- return false;
- return payloadName.toLowerCase().endsWith(TOSCA_CSAR_EXTENSION);
+ return payloadName != null && payloadName.toLowerCase().endsWith(TOSCA_CSAR_EXTENSION);
}
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeImportManager.java
index e423e729de..a9502b14f4 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeImportManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeImportManager.java
@@ -20,53 +20,30 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.function.Consumer;
-import java.util.stream.Collectors;
-
-import javax.annotation.Resource;
-
+import fj.data.Either;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum;
-import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
+import org.openecomp.sdc.be.utils.TypeUtils;
+import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
-import fj.data.Either;
+import javax.annotation.Resource;
+import java.util.*;
+import java.util.stream.Collectors;
@Component("dataTypeImportManager")
public class DataTypeImportManager {
- public static void main(String[] args) {
-
- List<PropertyDefinition> properties = new ArrayList<>();
- PropertyDefinition propertyDefintion = new PropertyDefinition();
- propertyDefintion.setName("aaa");
- properties.add(propertyDefintion);
-
- List<String> allParentsProps = new ArrayList<>();
- allParentsProps.add("aaa");
- allParentsProps.add("bbb");
-
- Set<String> alreadyExistPropsCollection = properties.stream().filter(p -> allParentsProps.contains(p.getName())).map(p -> p.getName()).collect(Collectors.toSet());
- System.out.println(alreadyExistPropsCollection);
-
- }
-
- private static final Logger log = LoggerFactory.getLogger(DataTypeImportManager.class);
+ private static final Logger log = Logger.getLogger(DataTypeImportManager.class.getName());
@Resource
private PropertyOperation propertyOperation;
@Resource
@@ -75,18 +52,16 @@ public class DataTypeImportManager {
private CommonImportManager commonImportManager;
public Either<List<ImmutablePair<DataTypeDefinition, Boolean>>, ResponseFormat> createDataTypes(String dataTypeYml) {
- return commonImportManager.createElementTypes(dataTypeYml, elementTypeYml -> createDataTypesFromYml(elementTypeYml), elementTypesList -> createDataTypesByDao(elementTypesList), ElementTypeEnum.DataType);
+ return commonImportManager.createElementTypes(dataTypeYml, this::createDataTypesFromYml, this::createDataTypesByDao, ElementTypeEnum.DATA_TYPE);
}
private Either<List<DataTypeDefinition>, ActionStatus> createDataTypesFromYml(String dataTypesYml) {
-
- return commonImportManager.createElementTypesFromYml(dataTypesYml, (dataTypeName, dataTypeJsonData) -> createDataType(dataTypeName, dataTypeJsonData));
-
+ return commonImportManager.createElementTypesFromYml(dataTypesYml, this::createDataType);
}
private Either<List<ImmutablePair<DataTypeDefinition, Boolean>>, ResponseFormat> createDataTypesByDao(List<DataTypeDefinition> dataTypesToCreate) {
- return commonImportManager.createElementTypesByDao(dataTypesToCreate, dataType -> validateDataType(dataType), dataType -> new ImmutablePair<>(ElementTypeEnum.DataType, dataType.getName()),
+ return commonImportManager.createElementTypesByDao(dataTypesToCreate, this::validateDataType, dataType -> new ImmutablePair<>(ElementTypeEnum.DATA_TYPE, dataType.getName()),
dataTypeName -> propertyOperation.getDataTypeByNameWithoutDerived(dataTypeName), dataType -> propertyOperation.addDataType(dataType), (newDataType, oldDataType) -> propertyOperation.updateDataType(newDataType, oldDataType));
}
@@ -124,17 +99,15 @@ public class DataTypeImportManager {
}
// check no duplicates
- Set<String> collect = properties.stream().map(p -> p.getName()).collect(Collectors.toSet());
- if (collect != null) {
- if (properties.size() != collect.size()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_DUPLICATE_PROPERTY, dataType, null);
+ Set<String> collect = properties.stream().map(PropertyDataDefinition::getName).collect(Collectors.toSet());
+ if (collect != null && properties.size() != collect.size()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_DUPLICATE_PROPERTY, dataType, null);
- return Either.right(responseFormat);
- }
+ return Either.right(responseFormat);
}
- List<String> propertiesWithSameTypeAsDataType = properties.stream().filter(p -> p.getType().equals(dataType.getName())).map(p -> p.getName()).collect(Collectors.toList());
- if (propertiesWithSameTypeAsDataType != null && propertiesWithSameTypeAsDataType.isEmpty() == false) {
+ List<String> propertiesWithSameTypeAsDataType = properties.stream().filter(p -> p.getType().equals(dataType.getName())).map(PropertyDataDefinition::getName).collect(Collectors.toList());
+ if (propertiesWithSameTypeAsDataType != null && !propertiesWithSameTypeAsDataType.isEmpty()) {
log.debug("The data type {} contains properties with the type {}", dataType.getName(), dataType.getName());
ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE, dataType, propertiesWithSameTypeAsDataType);
@@ -160,9 +133,9 @@ public class DataTypeImportManager {
} else {
DataTypeDefinition derivedDataTypeDef = derivedDataTypeByName.left().value();
- if (properties != null && properties.isEmpty() == false) {
+ if (properties != null && !properties.isEmpty() && derivedDataTypeDef!=null) {
- if (true == isScalarType(derivedDataTypeDef)) {
+ if (isScalarType(derivedDataTypeDef)) {
ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_CANNOT_HAVE_PROPERTIES, dataType, null);
return Either.right(responseFormat);
@@ -181,8 +154,8 @@ public class DataTypeImportManager {
// Check that no property is already defined in one of the
// ancestors
- Set<String> alreadyExistPropsCollection = properties.stream().filter(p -> allParentsProps.contains(p.getName())).map(p -> p.getName()).collect(Collectors.toSet());
- if (alreadyExistPropsCollection != null && alreadyExistPropsCollection.isEmpty() == false) {
+ Set<String> alreadyExistPropsCollection = properties.stream().filter(p -> allParentsProps.contains(p.getName())).map(PropertyDataDefinition::getName).collect(Collectors.toSet());
+ if (alreadyExistPropsCollection != null && !alreadyExistPropsCollection.isEmpty()) {
List<String> duplicateProps = new ArrayList<>();
duplicateProps.addAll(alreadyExistPropsCollection);
ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR, dataType, duplicateProps);
@@ -200,7 +173,7 @@ public class DataTypeImportManager {
ToscaPropertyType isPrimitiveToscaType = ToscaPropertyType.isValidType(dataTypeName);
- return isPrimitiveToscaType != null && isPrimitiveToscaType.isAbstract() == true;
+ return isPrimitiveToscaType != null && isPrimitiveToscaType.isAbstract();
}
@@ -230,22 +203,13 @@ public class DataTypeImportManager {
if (toscaJson != null) {
// Description
- final Consumer<String> descriptionSetter = description -> dataType.setDescription(description);
- commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DESCRIPTION.getElementName(), descriptionSetter);
+ commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName(), dataType::setDescription);
// Derived From
- final Consumer<String> derivedFromSetter = derivedFrom -> dataType.setDerivedFromName(derivedFrom);
- commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DERIVED_FROM.getElementName(), derivedFromSetter);
+ commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DERIVED_FROM.getElementName(), dataType::setDerivedFromName);
// Properties
- commonImportManager.setProperties(toscaJson, (values) -> dataType.setProperties(values));
-
- setConstraints(toscaJson, dataType);
+ CommonImportManager.setProperties(toscaJson, dataType::setProperties);
}
return dataType;
}
- private void setConstraints(Map<String, Object> toscaJson, DataTypeDefinition dataType) {
- // TODO Auto-generated method stub
-
- }
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypesService.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypesService.java
new file mode 100644
index 0000000000..3ddfe4bfc4
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypesService.java
@@ -0,0 +1,39 @@
+package org.openecomp.sdc.be.components.impl;
+
+import fj.data.Either;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
+import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
+import org.openecomp.sdc.exception.ResponseFormat;
+import org.springframework.stereotype.Component;
+
+import java.util.Map;
+
+@Component
+public class DataTypesService {
+
+ private final ComponentsUtils componentsUtils;
+
+ public DataTypesService(ComponentsUtils componentsUtils) {
+ this.componentsUtils = componentsUtils;
+ }
+
+ public Either<Map<String, DataTypeDefinition>, ResponseFormat> getAllDataTypes(ApplicationDataTypeCache applicationDataTypeCache) {
+ Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = applicationDataTypeCache.getAll();
+ if (allDataTypes.isRight()) {
+ TitanOperationStatus operationStatus = allDataTypes.right().value();
+ if (operationStatus == TitanOperationStatus.NOT_FOUND) {
+ BeEcompErrorManager.getInstance().logInternalDataError("FetchDataTypes", "Data types are not loaded", BeEcompErrorManager.ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.DATA_TYPE_CANNOT_BE_EMPTY));
+ } else {
+ BeEcompErrorManager.getInstance().logInternalFlowError("FetchDataTypes", "Failed to fetch data types", BeEcompErrorManager.ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+ return Either.left(allDataTypes.left().value());
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogic.java
index af5c03b4b8..4cf7c44e85 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogic.java
@@ -20,33 +20,25 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
+import fj.data.Either;
import org.apache.http.HttpStatus;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.info.DistributionStatusInfo;
import org.openecomp.sdc.be.info.DistributionStatusListResponse;
import org.openecomp.sdc.be.info.DistributionStatusOfServiceInfo;
import org.openecomp.sdc.be.info.DistributionStatusOfServiceListResponce;
-import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
import org.openecomp.sdc.be.resources.data.auditing.DistributionStatusEvent;
-import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKey;
import org.openecomp.sdc.common.datastructure.ESTimeBasedEvent;
+import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-import fj.data.Either;
+import java.util.*;
@Component("distributionMonitoringBusinessLogic")
public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic {
@@ -58,24 +50,18 @@ public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic {
private static final String IN_PROGRESS = "In Progress";
- private static final Logger log = LoggerFactory.getLogger(ArtifactsBusinessLogic.class);
+ private static final Logger log = Logger.getLogger(ArtifactsBusinessLogic.class.getName());
@Autowired
private AuditCassandraDao cassandraDao;
- @javax.annotation.Resource
- private ComponentsUtils componentsUtils;
-
public DistributionMonitoringBusinessLogic() {
}
public Either<DistributionStatusListResponse, ResponseFormat> getListOfDistributionStatus(String did, String userId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get List Of Distribution Status", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "get List Of Distribution Status", false);
log.trace("getListOfDistributionStatus for did {}", did);
Either<List<DistributionStatusEvent>, ActionStatus> distributionStatus = cassandraDao.getListOfDistributionStatuses(did);
@@ -83,7 +69,7 @@ public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic {
log.debug("not found distribution statuses for did {} status is {} ", did, distributionStatus.right().value());
return Either.right(componentsUtils.getResponseFormat(distributionStatus.right().value(), did));
}
- List<DistributionStatusInfo> distribStatusInfoList = new ArrayList<DistributionStatusInfo>();
+ List<DistributionStatusInfo> distribStatusInfoList = new ArrayList<>();
List<DistributionStatusEvent> distributionStatusEventList = distributionStatus.left().value();
if (distributionStatusEventList != null) {
for (ESTimeBasedEvent distributionStatusEvent : distributionStatusEventList) {
@@ -98,10 +84,7 @@ public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic {
}
public Either<DistributionStatusOfServiceListResponce, ResponseFormat> getListOfDistributionServiceStatus(String serviceUuid, String userId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get List Of Distribution Service Status", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "get List Of Distribution Service Status", false);
log.trace("getListOfDistributionServiceStatus for serviceUUID {}", serviceUuid);
Either<List<? extends AuditingGenericEvent>, ActionStatus> status = cassandraDao.getServiceDistributionStatusesList(serviceUuid);
@@ -109,7 +92,7 @@ public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic {
log.debug("failed to find service distribution statuses. error: {}", status);
return Either.right(componentsUtils.getResponseFormat(status.right().value(), serviceUuid));
}
- List<DistributionStatusOfServiceInfo> distribStatusInfoList = new ArrayList<DistributionStatusOfServiceInfo>();
+ List<DistributionStatusOfServiceInfo> distribStatusInfoList;
List<? extends AuditingGenericEvent> distributionStatusEventList = status.left().value();
distribStatusInfoList = handleAuditingDaoResponse(distributionStatusEventList);
DistributionStatusOfServiceListResponce distributionStatusListResponse = new DistributionStatusOfServiceListResponce();
@@ -118,7 +101,7 @@ public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic {
}
private List<DistributionStatusOfServiceInfo> handleAuditingDaoResponse(List<? extends AuditingGenericEvent> distribStatusInfoList) {
- List<DistributionStatusOfServiceInfo> reslist = new ArrayList<DistributionStatusOfServiceInfo>();
+ List<DistributionStatusOfServiceInfo> reslist = new ArrayList<>();
Map<String, List<AuditingGenericEvent>> serviceDidMap = createServiceDidMap(distribStatusInfoList);
Set<String> didSet = serviceDidMap.keySet();
for (String did : didSet) {
@@ -132,8 +115,8 @@ public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic {
for (AuditingGenericEvent auditingGenericEvent : auditingGenericEventList) {
auditingGenericEvent.fillFields();
- String action = (String) auditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName());
- Object modifierUserId = auditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID.getDisplayName());
+ String action = (String) auditingGenericEvent.getFields().get(AuditingFieldsKey.AUDIT_ACTION.getDisplayName());
+ Object modifierUserId = auditingGenericEvent.getFields().get(AuditingFieldsKey.AUDIT_MODIFIER_UID.getDisplayName());
if (modifierUserId != null) {
distributionStatusOfServiceInfo.setUserId((String) modifierUserId);
}
@@ -152,7 +135,7 @@ public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic {
resAuditingGenericEvent = auditingGenericEvent;
}
- distributionStatusOfServiceInfo.setTimestamp((String) resAuditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName()));
+ distributionStatusOfServiceInfo.setTimestamp((String) resAuditingGenericEvent.getFields().get(AuditingFieldsKey.AUDIT_TIMESTAMP.getDisplayName()));
if (!isResult) {
if (dReguestStatus.equals(String.valueOf(HttpStatus.SC_OK))) {
@@ -177,7 +160,7 @@ public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic {
private String getStatusFromAuditEvent(ESTimeBasedEvent auditingGenericEvent) {
String status = "";
- Object requestStatus = auditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName());
+ Object requestStatus = auditingGenericEvent.getFields().get(AuditingFieldsKey.AUDIT_STATUS.getDisplayName());
if (requestStatus instanceof String) {
status = (String) requestStatus;
}
@@ -186,13 +169,13 @@ public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic {
private Map<String, List<AuditingGenericEvent>> createServiceDidMap(List<? extends AuditingGenericEvent> distribStatusInfoList) {
- Map<String, List<AuditingGenericEvent>> serviceDidMap = new HashMap<String, List<AuditingGenericEvent>>();
+ Map<String, List<AuditingGenericEvent>> serviceDidMap = new HashMap<>();
for (AuditingGenericEvent auditingGenericEvent : distribStatusInfoList) {
List<AuditingGenericEvent> auditingGenericEventList = null;
String did = "";
auditingGenericEvent.fillFields();
- Object didValue = auditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID.getDisplayName());
+ Object didValue = auditingGenericEvent.getFields().get(AuditingFieldsKey.AUDIT_DISTRIBUTION_ID.getDisplayName());
if (didValue != null) {
did = (String) didValue;
}
@@ -202,7 +185,7 @@ public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic {
auditingGenericEventList = serviceDidMap.get(did);
}
if (auditingGenericEventList == null) {
- auditingGenericEventList = new ArrayList();
+ auditingGenericEventList = new ArrayList<>();
}
auditingGenericEventList.add(auditingGenericEvent);
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java
index 998ef6274f..630332fd32 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java
@@ -20,23 +20,11 @@
package org.openecomp.sdc.be.components.impl;
-import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.Set;
-import java.util.function.Predicate;
-import java.util.stream.Collectors;
-
+import fj.data.Either;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
+import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
@@ -48,25 +36,8 @@ import org.openecomp.sdc.be.datamodel.api.CategoryTypeEnum;
import org.openecomp.sdc.be.datamodel.utils.NodeTypeConvertUtils;
import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
-import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
-import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.ArtifactType;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentParametersView;
-import org.openecomp.sdc.be.model.DistributionStatusEnum;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.Product;
-import org.openecomp.sdc.be.model.PropertyScope;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.Tag;
-import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.datatypes.enums.*;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.catalog.CatalogComponent;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.category.GroupingDefinition;
@@ -85,25 +56,31 @@ import org.openecomp.sdc.be.ui.model.UiCategories;
import org.openecomp.sdc.be.user.Role;
import org.openecomp.sdc.be.user.UserBusinessLogic;
import org.openecomp.sdc.common.datastructure.Wrapper;
+import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import fj.data.Either;
+import java.nio.charset.StandardCharsets;
+import java.util.*;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
+
+import static org.apache.commons.lang.BooleanUtils.isTrue;
@org.springframework.stereotype.Component("elementsBusinessLogic")
public class ElementBusinessLogic extends BaseBusinessLogic {
- private static final Logger log = LoggerFactory.getLogger(ElementBusinessLogic.class);
+ private static final Logger log = Logger.getLogger(ElementBusinessLogic.class);
+ private static final String SERVICES = "services";
+ private static final String RESOURCES = "resources";
+ private static final String VALIDATION_OF_USER_FAILED_USER_ID = "Validation of user failed, userId {}";
+ private static final String COMPONENT_TYPE_IS_INVALID = "Component type {} is invalid";
+ private static final String VALIDATION_OF_USER_ROLE_FAILED_USER_ID = "Validation of user role failed, userId {}";
@javax.annotation.Resource
private IElementOperation elementOperation;
@javax.annotation.Resource
- private ComponentsUtils componentsUtils;
-
- @javax.annotation.Resource
private UserBusinessLogic userAdminManager;
/**
@@ -127,22 +104,22 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
case TESTER:
userId = user.getUserId();
- response = handleTester(userId);
+ response = handleTester();
break;
case GOVERNOR:
userId = user.getUserId();
- response = handleGovernor(userId);
+ response = handleGovernor();
break;
case OPS:
userId = user.getUserId();
- response = handleOps(userId);
+ response = handleOps();
break;
case PRODUCT_STRATEGIST:
userId = user.getUserId();
- response = handleProductStrategist(userId);
+ response = handleProductStrategist();
break;
case PRODUCT_MANAGER:
@@ -178,16 +155,16 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleAdmin() {
Either<Map<String, Set<? extends Component>>, ResponseFormat> response;
// userId should stay null
- Set<LifecycleStateEnum> lifecycleStates = new HashSet<LifecycleStateEnum>();
- Set<LifecycleStateEnum> lastStateStates = new HashSet<LifecycleStateEnum>();
+ Set<LifecycleStateEnum> lifecycleStates = new HashSet<>();
+ Set<LifecycleStateEnum> lastStateStates = new HashSet<>();
lifecycleStates.add(LifecycleStateEnum.CERTIFIED);
response = getFollowedResourcesAndServices(null, lifecycleStates, lastStateStates);
return response;
}
private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleDesigner(String userId) {
- Set<LifecycleStateEnum> lifecycleStates = new HashSet<LifecycleStateEnum>();
- Set<LifecycleStateEnum> lastStateStates = new HashSet<LifecycleStateEnum>();
+ Set<LifecycleStateEnum> lifecycleStates = new HashSet<>();
+ Set<LifecycleStateEnum> lastStateStates = new HashSet<>();
Either<Map<String, Set<? extends Component>>, ResponseFormat> response;
lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
@@ -200,21 +177,20 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
return response;
}
- private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleGovernor(String userId) {
- Either<Map<String, Set<? extends Component>>, ResponseFormat> result = handleFollowedCertifiedServices(null);
- return result;
+ private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleGovernor() {
+ return handleFollowedCertifiedServices(null);
}
- private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleProductStrategist(String userId) {
+ private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleProductStrategist() {
// Should be empty list according to Ella, 13/03/16
- Map<String, Set<? extends Component>> result = new HashMap<String, Set<? extends Component>>();
+ Map<String, Set<? extends Component>> result = new HashMap<>();
result.put("products", new HashSet<>());
return Either.left(result);
}
private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleProductManager(String userId) {
- Set<LifecycleStateEnum> lifecycleStates = new HashSet<LifecycleStateEnum>();
- Set<LifecycleStateEnum> lastStateStates = new HashSet<LifecycleStateEnum>();
+ Set<LifecycleStateEnum> lifecycleStates = new HashSet<>();
+ Set<LifecycleStateEnum> lastStateStates = new HashSet<>();
Either<Map<String, Set<? extends Component>>, ResponseFormat> response;
lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
@@ -227,13 +203,12 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
return response;
}
- private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleOps(String userId) {
- Set<DistributionStatusEnum> distStatus = new HashSet<DistributionStatusEnum>();
+ private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleOps() {
+ Set<DistributionStatusEnum> distStatus = new HashSet<>();
distStatus.add(DistributionStatusEnum.DISTRIBUTION_APPROVED);
distStatus.add(DistributionStatusEnum.DISTRIBUTED);
- Either<Map<String, Set<? extends Component>>, ResponseFormat> result = handleFollowedCertifiedServices(distStatus);
- return result;
+ return handleFollowedCertifiedServices(distStatus);
}
private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleFollowedCertifiedServices(Set<DistributionStatusEnum> distStatus) {
@@ -243,20 +218,19 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
Map<String, Set<? extends Component>> result = new HashMap<>();
Set<Service> set = new HashSet<>();
set.addAll(services.left().value());
- result.put("services", set);
+ result.put(SERVICES, set);
return Either.left(result);
} else {
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(services.right().value())));
}
}
- private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleTester(String userId) {
- Set<LifecycleStateEnum> lifecycleStates = new HashSet<LifecycleStateEnum>();
+ private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleTester() {
+ Set<LifecycleStateEnum> lifecycleStates = new HashSet<>();
lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
lifecycleStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION);
- Either<Map<String, Set<? extends Component>>, ResponseFormat> result = getFollowedResourcesAndServices(null, lifecycleStates, null);
- return result;
+ return getFollowedResourcesAndServices(null, lifecycleStates, null);
}
private Either<Map<String, Set<? extends Component>>, ResponseFormat> getFollowedResourcesAndServices(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates) {
@@ -267,9 +241,9 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
if (resources.isLeft()) {
Either<Set<Service>, StorageOperationStatus> services = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.SERVICE);
if (services.isLeft()) {
- Map<String, Set<? extends Component>> result = new HashMap<String, Set<? extends Component>>();
- result.put("services", services.left().value());
- result.put("resources", resources.left().value());
+ Map<String, Set<? extends Component>> result = new HashMap<>();
+ result.put(SERVICES, services.left().value());
+ result.put(RESOURCES, resources.left().value());
return Either.left(result);
} else {
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(services.right().value())));
@@ -311,10 +285,10 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
String componentType = componentTypeEnum == null ? componentTypeParamName : componentTypeEnum.getValue();
CategoryTypeEnum categoryType = CategoryTypeEnum.CATEGORY;
- User user = new User();
+ User user;
Either<User, ResponseFormat> validateUser = validateUser(userId);
if (validateUser.isRight()) {
- log.debug("Validation of user failed, userId {}", userId);
+ log.debug(VALIDATION_OF_USER_FAILED_USER_ID, userId);
ResponseFormat responseFormat = validateUser.right().value();
user = new User();
user.setUserId(userId);
@@ -336,7 +310,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
// For auditing of failures we need the original non-normalized name
String origCategoryName = categoryName;
if (componentTypeEnum == null) {
- log.debug("Component type {} is invalid", componentTypeParamName);
+ log.debug(COMPONENT_TYPE_IS_INVALID, componentTypeParamName);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType);
return Either.right(responseFormat);
@@ -344,7 +318,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, componentTypeEnum);
if (validateUserRole.isRight()) {
- log.debug("Validation of user role failed, userId {}", userId);
+ log.debug(VALIDATION_OF_USER_ROLE_FAILED_USER_ID, userId);
ResponseFormat responseFormat = validateUserRole.right().value();
handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType);
return Either.right(responseFormat);
@@ -422,22 +396,20 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
String subCategoryName = subCategory.getName();
// For auditing of failures we need the original non-normalized name
String origSubCategoryName = subCategoryName;
-
- User user = new User();
- Either<User, ResponseFormat> validateUser = validateUserExists(userId, "createSubCategory", false);
- if (validateUser.isRight()) {
- log.debug("Validation of user failed, userId {}", userId);
- ResponseFormat responseFormat = validateUser.right().value();
+ User user;
+ try{
+ user = validateUserExists(userId, "createSubCategory", false);
+ } catch(ComponentException e){
+ log.debug(VALIDATION_OF_USER_FAILED_USER_ID, userId);
+ ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat() :
+ componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
user = new User();
user.setUserId(userId);
handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
- return Either.right(responseFormat);
+ throw e;
}
-
- user = validateUser.left().value();
-
if (componentTypeEnum == null) {
- log.debug("Component type {} is invalid", componentTypeParamName);
+ log.debug(COMPONENT_TYPE_IS_INVALID, componentTypeParamName);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
return Either.right(responseFormat);
@@ -453,7 +425,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, componentTypeEnum);
if (validateUserRole.isRight()) {
- log.debug("Validation of user role failed, userId {}", userId);
+ log.debug(VALIDATION_OF_USER_ROLE_FAILED_USER_ID, userId);
ResponseFormat responseFormat = validateUserRole.right().value();
handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
return Either.right(responseFormat);
@@ -557,19 +529,19 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
String parentSubCategoryName = parentSubCategoryId;
User user;
- Either<User, ResponseFormat> validateUser = validateUserExists(userId, "create Grouping", false);
- if (validateUser.isRight()) {
- log.debug("Validation of user failed, userId {}", userId);
- ResponseFormat responseFormat = validateUser.right().value();
+ try{
+ user = validateUserExists(userId, "create Grouping", false);
+ } catch(ComponentException e){
+ log.debug(VALIDATION_OF_USER_FAILED_USER_ID, userId);
+ ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat() :
+ componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
user = new User();
user.setUserId(userId);
String groupingNameForAudit = grouping == null ? null : grouping.getName();
handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, groupingNameForAudit, auditingAction, componentType);
- return Either.right(responseFormat);
+ throw e;
}
- user = validateUser.left().value();
-
if (grouping == null) {
log.debug("Grouping json is invalid");
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
@@ -582,7 +554,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
String origGroupingName = groupingName;
if (componentTypeEnum == null) {
- log.debug("Component type {} is invalid", componentTypeParamName);
+ log.debug(COMPONENT_TYPE_IS_INVALID, componentTypeParamName);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
return Either.right(responseFormat);
@@ -598,7 +570,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, componentTypeEnum);
if (validateUserRole.isRight()) {
- log.debug("Validation of user role failed, userId {}", userId);
+ log.debug(VALIDATION_OF_USER_ROLE_FAILED_USER_ID, userId);
ResponseFormat responseFormat = validateUserRole.right().value();
handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
return Either.right(responseFormat);
@@ -707,31 +679,30 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
}
public Either<List<CategoryDefinition>, ResponseFormat> getAllCategories(String componentType, String userId) {
- AuditingActionEnum auditingAction = AuditingActionEnum.GET_CATEGORY_HIERARCHY;
ResponseFormat responseFormat;
User user = new User();
if (userId == null) {
user.setUserId("UNKNOWN");
responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
- componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat);
+ componentsUtils.auditGetCategoryHierarchy(user, componentType, responseFormat);
return Either.right(responseFormat);
}
-
- Either<User, ResponseFormat> validateUser = validateUserExists(userId, "get All Categories", false);
- if (validateUser.isRight()) {
+ try {
+ user = validateUserExists(userId, "get All Categories", false);
+ } catch (ComponentException e){
+ user = new User();
user.setUserId(userId);
- log.debug("Validation of user failed, userId {}", userId);
- responseFormat = validateUser.right().value();
- componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat);
- return Either.right(responseFormat);
+ log.debug(VALIDATION_OF_USER_FAILED_USER_ID, userId);
+ responseFormat = e.getResponseFormat() != null ? e.getResponseFormat():
+ componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
+ componentsUtils.auditGetCategoryHierarchy(user, componentType, responseFormat);
+ throw e;
}
- user = validateUser.left().value();
-
ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
if (componentTypeEnum == null) {
log.debug("Cannot create category for component type {}", componentType);
responseFormat = componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, "component type");
- componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat);
+ componentsUtils.auditGetCategoryHierarchy(user, componentType, responseFormat);
return Either.right(responseFormat);
}
@@ -739,32 +710,26 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
Either<List<CategoryDefinition>, ActionStatus> getAllCategoriesByType = elementOperation.getAllCategories(nodeTypeEnum, false);
if (getAllCategoriesByType.isRight()) {
responseFormat = componentsUtils.getResponseFormat(getAllCategoriesByType.right().value());
- componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat);
+ componentsUtils.auditGetCategoryHierarchy(user, componentType, responseFormat);
return Either.right(responseFormat);
}
List<CategoryDefinition> categories = getAllCategoriesByType.left().value();
responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
- componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat);
+ componentsUtils.auditGetCategoryHierarchy(user, componentType, responseFormat);
return Either.left(categories);
}
public Either<UiCategories, ResponseFormat> getAllCategories(String userId) {
- AuditingActionEnum auditingAction = AuditingActionEnum.GET_CATEGORY_HIERARCHY;
ResponseFormat responseFormat;
UiCategories categories = new UiCategories();
- Either<User, ResponseFormat> userResponse = validateUserExists(userId, "get all categories", false);
-
- if (userResponse.isRight()) {
- return Either.right(userResponse.right().value());
- }
- User user = userResponse.left().value();
+ User user = validateUserExists(userId, "get all categories", false);
// GET resource categories
Either<List<CategoryDefinition>, ActionStatus> getResourceCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ResourceNewCategory, false);
if (getResourceCategoriesByType.isRight()) {
responseFormat = componentsUtils.getResponseFormat(getResourceCategoriesByType.right().value());
- componentsUtils.auditGetCategoryHierarchy(auditingAction, user, ComponentTypeEnum.RESOURCE.getValue(), responseFormat);
+ componentsUtils.auditGetCategoryHierarchy(user, ComponentTypeEnum.RESOURCE.getValue(), responseFormat);
return Either.right(responseFormat);
}
categories.setResourceCategories(getResourceCategoriesByType.left().value());
@@ -773,7 +738,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
Either<List<CategoryDefinition>, ActionStatus> getServiceCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ServiceNewCategory, false);
if (getServiceCategoriesByType.isRight()) {
responseFormat = componentsUtils.getResponseFormat(getServiceCategoriesByType.right().value());
- componentsUtils.auditGetCategoryHierarchy(auditingAction, user, ComponentTypeEnum.SERVICE.getValue(), responseFormat);
+ componentsUtils.auditGetCategoryHierarchy(user, ComponentTypeEnum.SERVICE.getValue(), responseFormat);
return Either.right(responseFormat);
}
categories.setServiceCategories(getServiceCategoriesByType.left().value());
@@ -782,7 +747,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
Either<List<CategoryDefinition>, ActionStatus> getProductCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ProductCategory, false);
if (getProductCategoriesByType.isRight()) {
responseFormat = componentsUtils.getResponseFormat(getProductCategoriesByType.right().value());
- componentsUtils.auditGetCategoryHierarchy(auditingAction, user, ComponentTypeEnum.PRODUCT.getValue(), responseFormat);
+ componentsUtils.auditGetCategoryHierarchy(user, ComponentTypeEnum.PRODUCT.getValue(), responseFormat);
return Either.right(responseFormat);
}
@@ -793,10 +758,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
public Either<CategoryDefinition, ResponseFormat> deleteCategory(String categoryId, String componentTypeParamName, String userId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Category", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "delete Category", false);
ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName);
if (componentTypeEnum == null) {
@@ -816,12 +778,9 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
return Either.left(category);
}
- public Either<SubCategoryDefinition, ResponseFormat> deleteSubCategory(String grandParentCategoryId, String parentSubCategoryId, String componentTypeParamName, String userId) {
+ public Either<SubCategoryDefinition, ResponseFormat> deleteSubCategory(String parentSubCategoryId, String componentTypeParamName, String userId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Sub Category", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "delete Sub Category", false);
ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName);
if (componentTypeEnum == null) {
@@ -841,12 +800,9 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
return Either.left(subCategory);
}
- public Either<GroupingDefinition, ResponseFormat> deleteGrouping(String grandParentCategoryId, String parentSubCategoryId, String groupingId, String componentTypeParamName, String userId) {
+ public Either<GroupingDefinition, ResponseFormat> deleteGrouping(String groupingId, String componentTypeParamName, String userId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Grouping", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "delete Grouping", false);
ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName);
if (componentTypeEnum == null) {
@@ -1001,13 +957,12 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
return elementOperation.getDefaultHeatTimeout();
}
- public Either<Map<String, List<CatalogComponent>>, ResponseFormat> getCatalogComponents(String userId) {
+ public Either<Map<String, List<CatalogComponent>>, ResponseFormat> getCatalogComponents(String userId, List<OriginTypeEnum> excludeTypes) {
try {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Catalog Components", true);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
- return toscaOperationFacade.getCatalogComponents().bimap(this::groupByComponentType, err -> componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(err)));
+ validateUserExists(userId, "get Catalog Components", true);
+ return toscaOperationFacade.getCatalogOrArchiveComponents(true, excludeTypes)
+ .bimap(this::groupByComponentType,
+ err -> componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(err)));
} finally {
titanDao.commit();
}
@@ -1020,11 +975,11 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
if (map == null) {
map = new HashMap<>();
}
- if (map.get("resources") == null) {
- map.put("resources", new ArrayList());
+ if (map.get(RESOURCES) == null) {
+ map.put(RESOURCES, new ArrayList());
}
- if (map.get("services") == null) {
- map.put("services", new ArrayList());
+ if (map.get(SERVICES) == null) {
+ map.put(SERVICES, new ArrayList());
}
return map;
}
@@ -1032,9 +987,9 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
private String cmptTypeToString(ComponentTypeEnum componentTypeEnum) {
switch (componentTypeEnum) {
case RESOURCE:
- return "resources";
+ return RESOURCES;
case SERVICE:
- return "services";
+ return SERVICES;
default:
throw new IllegalStateException("resources or services only");
}
@@ -1099,7 +1054,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
}
if (categoryName != null) { // primary filter
- components = fetchByCategoryOrSubCategoryName(categoryName, NodeTypeEnum.ServiceNewCategory, GraphEdgeLabels.CATEGORY.getProperty(), NodeTypeEnum.Service, inTransaction, ServiceMetadataData.class, null);
+ components = fetchByCategoryOrSubCategoryName(categoryName, NodeTypeEnum.ServiceNewCategory, NodeTypeEnum.Service, inTransaction, ServiceMetadataData.class, null);
if (components.isLeft() && distEnum != null) {// secondary filter
Predicate<T> statusFilter = p -> ((Service) p).getDistributionStatus().equals(distEnum);
return Either.left(components.left().value().stream().filter(statusFilter).collect(Collectors.toList()));
@@ -1186,7 +1141,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
}
private List<String> getErrorResponseParams(Map<FilterKeyEnum, String> filters, ComponentTypeEnum assetType) {
- List<String> params = new ArrayList<String>();
+ List<String> params = new ArrayList<>();
if (1 == filters.size()) {
params.add(assetType.getValue().toLowerCase());
params.add(filters.keySet().iterator().next().getName());
@@ -1220,11 +1175,11 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
if (!subCategoryData.isPresent()) {
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
- return fetchByCategoryOrSubCategoryUid((String) subCategoryData.get().getLeft().getUniqueId(), NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, inTransaction,
+ return fetchByCategoryOrSubCategoryUid((String) subCategoryData.get().getLeft().getUniqueId(), NodeTypeEnum.ResourceSubcategory, NodeTypeEnum.Resource, inTransaction,
ResourceMetadataData.class, resourceType);
}
- return fetchByCategoryOrSubCategoryName(subCategoryName, NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, inTransaction, ResourceMetadataData.class, resourceType);
+ return fetchByCategoryOrSubCategoryName(subCategoryName, NodeTypeEnum.ResourceSubcategory, NodeTypeEnum.Resource, inTransaction, ResourceMetadataData.class, resourceType);
}
if (subcategories != null) {
return fetchByMainCategory(subcategories.left().value(), inTransaction, resourceType);
@@ -1252,23 +1207,23 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
return childNodes.stream().filter(matchName).findAny();
}
- protected <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryUid(String categoryUid, NodeTypeEnum categoryType, String categoryLabel, NodeTypeEnum neededType, boolean inTransaction,
- Class<S> clazz, ResourceTypeEnum resourceType) {
+ protected <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryUid(String categoryUid, NodeTypeEnum categoryType, NodeTypeEnum neededType, boolean inTransaction,
+ Class<S> clazz, ResourceTypeEnum resourceType) {
try {
return collectComponents(neededType, categoryUid, categoryType, clazz, resourceType);
} finally {
- if (false == inTransaction) {
+ if (!inTransaction) {
titanDao.commit();
}
}
}
- protected <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryName(String categoryName, NodeTypeEnum categoryType, String categoryLabel, NodeTypeEnum neededType, boolean inTransaction,
- Class<S> clazz, ResourceTypeEnum resourceType) {
+ protected <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryName(String categoryName, NodeTypeEnum categoryType, NodeTypeEnum neededType, boolean inTransaction,
+ Class<S> clazz, ResourceTypeEnum resourceType) {
List<T> components = new ArrayList<>();
try {
Class categoryClazz = categoryType == NodeTypeEnum.ServiceNewCategory ? CategoryData.class : SubCategoryData.class;
- Map<String, Object> props = new HashMap<String, Object>();
+ Map<String, Object> props = new HashMap<>();
props.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), ValidationUtils.normalizeCategoryName4Uniqueness(categoryName));
Either<List<GraphNode>, TitanOperationStatus> getCategory = titanGenericDao.getByCriteria(categoryType, props, categoryClazz);
if (getCategory.isRight()) {
@@ -1284,12 +1239,13 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
return Either.left(components);
} finally {
- if (false == inTransaction) {
+ if (!inTransaction) {
titanDao.commit();
}
}
}
+
private <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> collectComponents(NodeTypeEnum neededType, String categoryUid, NodeTypeEnum categoryType, Class<S> clazz, ResourceTypeEnum resourceType) {
List<T> components = new ArrayList<>();
Either<List<ImmutablePair<S, GraphEdge>>, TitanOperationStatus> parentNodes = titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(categoryType), categoryUid, GraphEdgeLabels.CATEGORY, neededType, clazz);
@@ -1298,9 +1254,10 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
ComponentMetadataDataDefinition componentData = component.getLeft().getMetadataDataDefinition();
Boolean isHighest = componentData.isHighestVersion();
boolean isMatchingResourceType = isMatchingByResourceType(neededType, resourceType, componentData);
- boolean isDeleted = componentData.isDeleted() != null && componentData.isDeleted();
+ boolean isDeleted = isTrue(componentData.isDeleted());
+ boolean isArchived = isTrue(componentData.isArchived());
- if (isHighest && isMatchingResourceType && !isDeleted) {
+ if (isHighest && isMatchingResourceType && !isDeleted && !isArchived) {
Either<T, StorageOperationStatus> result = (Either<T, StorageOperationStatus>) toscaOperationFacade.getToscaElement(componentData.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
if (result.isRight()) {
return Either.right(result.right().value());
@@ -1331,7 +1288,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
List<T> components = new ArrayList<>();
for (ImmutablePair<SubCategoryData, GraphEdge> subCategory : subcategories) {
- Either<List<T>, StorageOperationStatus> fetched = fetchByCategoryOrSubCategoryUid((String) subCategory.getLeft().getUniqueId(), NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource,
+ Either<List<T>, StorageOperationStatus> fetched = fetchByCategoryOrSubCategoryUid((String) subCategory.getLeft().getUniqueId(), NodeTypeEnum.ResourceSubcategory, NodeTypeEnum.Resource,
inTransaction, ResourceMetadataData.class, resourceType);
if (fetched.isRight()) {
continue;
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ExternalRefsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ExternalRefsBusinessLogic.java
index d8626ff591..0b53da0018 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ExternalRefsBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ExternalRefsBusinessLogic.java
@@ -1,24 +1,21 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
+import fj.data.Either;
+import org.openecomp.sdc.be.components.validation.AccessValidations;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.dto.ExternalRefDTO;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.jsontitan.operations.ExternalReferencesOperation;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import org.openecomp.sdc.common.log.wrappers.Logger;
-import fj.data.Either;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
/**
* Created by yavivi on 04/02/2018.
@@ -26,16 +23,18 @@ import fj.data.Either;
@org.springframework.stereotype.Component
public class ExternalRefsBusinessLogic {
- private static final Logger log = LoggerFactory.getLogger(ExternalRefsBusinessLogic.class);
+ private static final Logger log = Logger.getLogger(ExternalRefsBusinessLogic.class);
- private ExternalReferencesOperation externalReferencesOperation;
- private ToscaOperationFacade toscaOperationFacade;
- private GraphLockOperation graphLockOperation;
+ private final ExternalReferencesOperation externalReferencesOperation;
+ private final ToscaOperationFacade toscaOperationFacade;
+ private final AccessValidations accessValidations;
+ private final ComponentLocker componentLocker;
- public ExternalRefsBusinessLogic(ExternalReferencesOperation externalReferencesOperation, ToscaOperationFacade toscaOperationFacade, GraphLockOperation graphLockOperation){
+ public ExternalRefsBusinessLogic(ExternalReferencesOperation externalReferencesOperation, ToscaOperationFacade toscaOperationFacade, AccessValidations accessValidations, ComponentLocker componentLocker) {
this.externalReferencesOperation = externalReferencesOperation;
this.toscaOperationFacade = toscaOperationFacade;
- this.graphLockOperation = graphLockOperation;
+ this.accessValidations = accessValidations;
+ this.componentLocker = componentLocker;
}
public Either<List<String>, ActionStatus> getExternalReferences(String assetUuid, String version, String componentInstanceName, String objectType){
@@ -63,21 +62,20 @@ public class ExternalRefsBusinessLogic {
}
}
- public Either<String, ActionStatus> addExternalReference(String uuid, String componentInstanceName, String objectType, ExternalRefDTO ref) {
- return this.doAction("POST", uuid, componentInstanceName, objectType, ref.getReferenceUUID(), "");
+ public Either<String, ActionStatus> addExternalReference(ComponentTypeEnum componentType, String userId, String uuid, String componentInstanceName, String objectType, ExternalRefDTO ref) {
+ return this.doAction(componentType, userId, "POST", uuid, componentInstanceName, objectType, ref.getReferenceUUID(), "");
}
-
- public Either<String, ActionStatus> deleteExternalReference(String uuid, String componentInstanceName, String objectType, String reference) {
- return this.doAction("DELETE", uuid, componentInstanceName, objectType, reference, "");
+ public Either<String, ActionStatus> deleteExternalReference(ComponentTypeEnum componentType, String userId, String uuid, String componentInstanceName, String objectType, String reference) {
+ return this.doAction(componentType, userId, "DELETE", uuid, componentInstanceName, objectType, reference, "");
}
- public Either<String, ActionStatus> updateExternalReference(String uuid, String componentInstanceName, String objectType, String oldRefValue, String newRefValue) {
- return this.doAction("PUT", uuid, componentInstanceName, objectType, oldRefValue, newRefValue);
+ public Either<String, ActionStatus> updateExternalReference(ComponentTypeEnum componentType, String userId, String uuid, String componentInstanceName, String objectType, String oldRefValue, String newRefValue) {
+ return this.doAction(componentType, userId, "PUT", uuid, componentInstanceName, objectType, oldRefValue, newRefValue);
}
- private Either<String, ActionStatus> doAction(String action, String uuid, String componentInstanceName, String objectType, String ref1, String ref2){
- Either<Component, StorageOperationStatus> latestServiceByUuid = toscaOperationFacade.getLatestComponentByUuid(uuid, createPropsToMatch());
+ private Either<String, ActionStatus> doAction(ComponentTypeEnum componentType, String userId, String action, String uuid, String componentInstanceName, String objectType, String ref1, String ref2){
+ Either<Component, StorageOperationStatus> latestServiceByUuid = toscaOperationFacade.getLatestComponentByUuid(uuid, createPropsToMatch(componentType));
if (latestServiceByUuid == null || latestServiceByUuid.isRight()){
return Either.right(ActionStatus.RESOURCE_NOT_FOUND);
}
@@ -87,10 +85,8 @@ public class ExternalRefsBusinessLogic {
String uniqueId = component.getUniqueId();
//Lock Asset
- StorageOperationStatus lockStatus = this.graphLockOperation.lockComponent(uniqueId, NodeTypeEnum.Service);
- if (lockStatus != StorageOperationStatus.OK){
- return Either.right(ActionStatus.GENERAL_ERROR);
- }
+ this.componentLocker.lock(component);
+ this.accessValidations.validateUserCanWorkOnComponent(component, userId, action + " EXTERNAL REF");
Either<String, ActionStatus> opResult = Either.right(ActionStatus.GENERAL_ERROR);
try {
@@ -113,14 +109,14 @@ public class ExternalRefsBusinessLogic {
log.error("Cause is:" , e);
} finally {
//Unlock Asset
- this.graphLockOperation.unlockComponent(uniqueId, NodeTypeEnum.Service);
+ this.componentLocker.unlock(uniqueId, componentType);
}
return opResult;
}
- private Map<GraphPropertyEnum, Object> createPropsToMatch() {
+ private Map<GraphPropertyEnum, Object> createPropsToMatch(ComponentTypeEnum componentType) {
Map<GraphPropertyEnum, Object> propertiesToMatch = new HashMap<>();
- propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
+ propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
return propertiesToMatch;
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java
index 313a117add..f2d0d94418 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,22 +20,7 @@
package org.openecomp.sdc.be.components.impl;
-import static java.util.stream.Collectors.toList;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-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.Set;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
-
+import fj.data.Either;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.FilenameUtils;
@@ -43,6 +28,8 @@ import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
+import org.openecomp.sdc.be.components.impl.lock.LockingTransactional;
+import org.openecomp.sdc.be.components.impl.policy.PolicyTargetsUpdateHandler;
import org.openecomp.sdc.be.components.utils.Utils;
import org.openecomp.sdc.be.components.validation.AccessValidations;
import org.openecomp.sdc.be.components.validation.ComponentValidations;
@@ -51,74 +38,65 @@ import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.CreatedFrom;
import org.openecomp.sdc.be.info.ArtifactDefinitionInfo;
import org.openecomp.sdc.be.info.ArtifactTemplateInfo;
import org.openecomp.sdc.be.info.GroupDefinitionInfo;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.ComponentParametersView;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.GroupDefinition;
-import org.openecomp.sdc.be.model.GroupInstance;
-import org.openecomp.sdc.be.model.GroupInstanceProperty;
-import org.openecomp.sdc.be.model.GroupProperty;
-import org.openecomp.sdc.be.model.GroupTypeDefinition;
-import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.PropertyDefinition.GroupInstancePropertyValueUpdateBehavior;
import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
-import org.openecomp.sdc.be.model.jsontitan.operations.ArtifactsOperations;
import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation;
import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
-import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation;
import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import fj.data.Either;
+import java.util.*;
+import java.util.Map.Entry;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+
+import static java.util.stream.Collectors.toList;
+import static org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter.extractCapabilitiesFromGroups;
+import static org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter.extractCapabilityPropertiesFromGroups;
@org.springframework.stereotype.Component("groupBusinessLogic")
public class GroupBusinessLogic extends BaseBusinessLogic {
+
public static final String GROUP_DELIMITER_REGEX = "\\.\\.";
- private static String ADDING_GROUP = "AddingGroup";
public static final String INITIAL_VERSION = "1";
+ private static final String ADDING_GROUP = "AddingGroup";
+
private static final String CREATE_GROUP = "CreateGroup";
private static final String UPDATE_GROUP = "UpdateGroup";
private static final String GET_GROUP = "GetGroup";
- private static final String DELETE_GROUP = "GetGroup";
+ private static final String DELETE_GROUP = "DeleteGroup";
- private static final Logger log = LoggerFactory.getLogger(GroupBusinessLogic.class);
-
- @javax.annotation.Resource
+ private static final Logger log = Logger.getLogger(GroupBusinessLogic.class);
+ @Autowired
private AccessValidations accessValidations;
@javax.annotation.Resource
- private GroupTypeOperation groupTypeOperation;
-
- @Autowired
- private ArtifactsOperations artifactsOperation;
-
@Autowired
private GroupsOperation groupsOperation;
+
@Autowired
- private ApplicationDataTypeCache dataTypeCache;
+ PolicyTargetsUpdateHandler policyTargetsUpdateHandler;
private String getComponentTypeForResponse(org.openecomp.sdc.be.model.Component component) {
String componentTypeForResponse = "SERVICE";
@@ -147,7 +125,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
- List<String> currentArtifacts = deploymentArtifacts.values().stream().map(p -> p.getUniqueId()).collect(toList());
+ List<String> currentArtifacts = deploymentArtifacts.values().stream().map(ArtifactDefinition::getUniqueId).collect(toList());
log.debug("The deployment artifacts of component {} are {}", component.getNormalizedName(), deploymentArtifacts);
if (!currentArtifacts.containsAll(artifacts)) {
BeEcompErrorManager.getInstance().logInvalidInputError(context, "Not all artifacts belongs to component " + component.getNormalizedName(), ErrorSeverity.INFO);
@@ -178,7 +156,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
List<ComponentInstance> componentInstances = component.getComponentInstances();
if (CollectionUtils.isNotEmpty(componentInstances)) {
- Map<String, ComponentInstance> compInstUidToCompInstMap = componentInstances.stream().collect(Collectors.toMap(p -> p.getUniqueId(), p -> p));
+ Map<String, ComponentInstance> compInstUidToCompInstMap = componentInstances.stream().collect(Collectors.toMap(ComponentInstance::getUniqueId, p -> p));
Set<String> allCompInstances = compInstUidToCompInstMap.keySet();
@@ -218,11 +196,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
Either<GroupDefinition, ResponseFormat> result = null;
try {
// Validate user exist
- Either<User, ResponseFormat> validateUserExists = validateUserExists(user.getUserId(), UPDATE_GROUP, inTransaction);
- if (validateUserExists.isRight()) {
- result = Either.right(validateUserExists.right().value());
- return result;
- }
+ validateUserExists(user.getUserId(), UPDATE_GROUP, inTransaction);
// Validate component exist
Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, null);
if (validateComponent.isRight()) {
@@ -268,7 +242,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
return result;
} finally {
- if (result.isLeft()) {
+ if (result != null && result.isLeft()) {
titanDao.commit();
} else {
titanDao.rollback();
@@ -320,239 +294,6 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
/**
- * Validate and Update Group Property
- *
- * @param componentId
- * @param groupUniqueId
- * @param user
- * @param componentType
- * @param groupPropertiesToUpdate
- * @param inTransaction
- * @return
- */
- public Either<List<GroupProperty>, ResponseFormat> validateAndUpdateGroupProperties(String componentId, String groupUniqueId, User user, ComponentTypeEnum componentType, List<GroupProperty> groupPropertiesToUpdate, boolean inTransaction) {
-
- Either<List<GroupProperty>, ResponseFormat> result = Either.left(groupPropertiesToUpdate);
- try {
- Optional<GroupDefinition> optionalGroupConnectedToVf = null;
- GroupDefinition currentGroup = null;
- StorageOperationStatus lockResult = graphLockOperation.lockComponent(componentId, componentType.getNodeType());
- if (lockResult != StorageOperationStatus.OK) {
- result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult, componentType), componentId));
- }
- if (result.isLeft()) {
- // VF exist because lock succedded
- Resource vf = (Resource) toscaOperationFacade.getToscaElement(componentId).left().value();
- optionalGroupConnectedToVf =
- // All groups on resource
- vf.getGroups().stream().
- // Filter in group sent is part of VF groups
- filter(e -> e.getUniqueId().equals(groupUniqueId)).
- // Collect
- findAny();
- if (!optionalGroupConnectedToVf.isPresent()) {
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, groupUniqueId, vf.getName(), ComponentTypeEnum.RESOURCE.getValue()));
- }
- }
-
- if (result.isLeft()) {
- currentGroup = optionalGroupConnectedToVf.get();
- result = validateGroupPropertyAndResetEmptyValue(currentGroup, groupPropertiesToUpdate);
- }
- if (result.isLeft()) {
- result = updateGroupPropertiesValue(componentId, currentGroup, groupPropertiesToUpdate, inTransaction);
- if (result.isRight()) {
- BeEcompErrorManager.getInstance().logBeSystemError("Update GroupProperties");
- log.debug("failed to update Vf {}", componentId);
- }
- }
-
- } catch (Exception e) {
- log.debug("Error in validateAndUpdateGroupProperty {}", e);
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- } finally {
- graphLockOperation.unlockComponent(componentId, componentType.getNodeType());
- }
- return result;
- }
-
- private void resetEmptyValueWithDefaults(List<GroupProperty> groupPropertiesToUpdate, GroupDefinition originalGroup) {
- Map<String, GroupProperty> originalProperties =
- // Stream of original properties from group
- originalGroup.convertToGroupProperties().stream().
- // Collecting to map with name as key
- collect(Collectors.toMap(e -> e.getName(), e -> e));
- for (GroupProperty gp : groupPropertiesToUpdate) {
- if (StringUtils.isEmpty(gp.getValue())) {
- gp.setValue(originalProperties.get(gp.getName()).getDefaultValue());
- }
- }
-
- }
-
- private Either<List<GroupProperty>, ResponseFormat> validateGroupPropertyAndResetEmptyValue(GroupDefinition originalGroup, List<GroupProperty> groupPropertiesToUpdate) {
-
- Either<List<GroupProperty>, ResponseFormat> ret = validateOnlyValueChanged(groupPropertiesToUpdate, originalGroup);
- if (ret.isLeft()) {
- resetEmptyValueWithDefaults(groupPropertiesToUpdate, originalGroup);
- }
- if (ret.isLeft()) {
- // Validate Type Match Value
- Optional<StorageOperationStatus> optionalError =
- // Stream of group properties
- groupPropertiesToUpdate.stream().
- // Validate each and map to returned Strorage status value
- map(e -> groupOperation.validateAndUpdatePropertyValue(e)).
- // Keep only failed result if there is such
- filter(e -> e != StorageOperationStatus.OK).
- // collect
- findFirst();
- if (optionalError.isPresent()) {
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(optionalError.get());
- ret = Either.right(componentsUtils.getResponseFormat(actionStatus));
- }
-
- }
- if (ret.isLeft()) {
- // Validate min max ect...
- ret = validatePropertyBusinessLogic(groupPropertiesToUpdate, originalGroup);
- }
-
- return ret;
- }
-
- private Either<List<GroupProperty>, ResponseFormat> validatePropertyBusinessLogic(List<GroupProperty> groupPropertiesToUpdate, GroupDefinition originalGroup) {
-
- Either<List<GroupProperty>, ResponseFormat> ret = Either.left(groupPropertiesToUpdate);
-
- Map<PropertyNames, String> nameValueMap = new HashMap<>();
- for (GroupProperty gp : groupPropertiesToUpdate) {
- // Filter out non special properties which does not have Enum
- final PropertyNames gpEnum = PropertyNames.findName(gp.getName());
- if (gpEnum != null) {
- nameValueMap.put(gpEnum, gp.getValue());
- }
- }
-
- if (!MapUtils.isEmpty(nameValueMap)) {
-
- if (nameValueMap.containsKey(PropertyNames.INITIAL_COUNT) || nameValueMap.containsKey(PropertyNames.MAX_INSTANCES) || nameValueMap.containsKey(PropertyNames.MIN_INSTANCES)) {
-
- Map<PropertyNames, String> oldValueMap = prepareMapWithOriginalProperties(originalGroup);
-
- Either<Boolean, ResponseFormat> eitherValid = validateMinMaxAndInitialCountPropertyLogicVF(nameValueMap, oldValueMap);
- if (eitherValid.isRight()) {
- ret = Either.right(eitherValid.right().value());
- }
- }
- if (ret.isLeft() && (nameValueMap.containsKey(PropertyNames.VF_MODULE_DESCRIPTION) || nameValueMap.containsKey(PropertyNames.VF_MODULE_LABEL))) {
-
- Optional<ResponseFormat> optionalError =
- // Stream of group Properties
- groupPropertiesToUpdate.stream().
- // Filter in only properties that needs text validation
- filter(e -> enumHasValueFilter(e.getName(), enumName -> PropertyNames.findName(enumName), PropertyNames.VF_MODULE_DESCRIPTION, PropertyNames.VF_MODULE_LABEL)).
- // validate text properties
- map(e -> validateFreeText(e)).
- // filter in only errors if exist
- filter(e -> e.isRight()).
- // map the Either value to the Error
- map(e -> e.right().value())
- // collect
- .findFirst();
- if (optionalError.isPresent()) {
- ret = Either.right(optionalError.get());
- }
-
- }
- }
-
- return ret;
- }
-
- private Map<PropertyNames, String> prepareMapWithOriginalProperties(GroupDefinition originalGroup) {
- Map<PropertyNames, String> oldValueMap = new HashMap<>();
- PropertyNames[] propertiesToCheck = new PropertyNames[] { PropertyNames.INITIAL_COUNT, PropertyNames.MAX_INSTANCES, PropertyNames.MIN_INSTANCES };
-
- for (GroupProperty gp : originalGroup.convertToGroupProperties()) {
- if (enumHasValueFilter(gp.getName(), PropertyNames::findName, propertiesToCheck)) {
- oldValueMap.put(PropertyNames.findName(gp.getName()), gp.getValue());
- }
- }
- if (StringUtils.isEmpty(oldValueMap.get(PropertyNames.MAX_INSTANCES))) {
- oldValueMap.put(PropertyNames.MAX_INSTANCES, String.valueOf(Integer.MAX_VALUE));
- }
- return oldValueMap;
- }
-
- private Either<List<GroupProperty>, ResponseFormat> validateOnlyValueChanged(List<GroupProperty> groupPropertiesToUpdate, GroupDefinition originalGroup) {
-
- Either<List<GroupProperty>, ResponseFormat> ret = Either.left(groupPropertiesToUpdate);
- if (CollectionUtils.isEmpty(groupPropertiesToUpdate)) {
- ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, StringUtils.EMPTY));
- } else if (CollectionUtils.isEmpty(originalGroup.getProperties())) {
- ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, groupPropertiesToUpdate.get(NumberUtils.INTEGER_ZERO).getName()));
- } else {
- Map<String, GroupProperty> namePropertyMap =
- // Original Group Properties Stream
- originalGroup.convertToGroupProperties().stream().
- // Collect to map with name as key
- collect(Collectors.toMap(e -> e.getName(), e -> e));
-
- Optional<GroupProperty> optionalMissingProperty =
- // Group Properties to be updated Stream
- groupPropertiesToUpdate.stream().
- // Filter in property that is not contained in original if there is such
- filter(e -> !namePropertyMap.containsKey(e.getName())).
- // collect
- findFirst();
-
- if (optionalMissingProperty.isPresent()) {
- ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, optionalMissingProperty.get().getName()));
- } else {
- Optional<GroupProperty> optionalNonValueChange =
- // groups to be updated stream
- groupPropertiesToUpdate.stream().
- // filter in only properties with non-value (illegal) change
- filter(e -> !isOnlyGroupPropertyValueChanged(e, namePropertyMap.get(e.getName()))).
- // Collect
- findFirst();
- if (optionalNonValueChange.isPresent()) {
- ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY, optionalNonValueChange.get().getName()));
-
- }
- }
-
- }
- return ret;
- }
-
- /**
- * if groupProperty are the same or if only value is different returns true, otherwise returns false.
- *
- * @param groupProperty
- * @param groupProperty2
- * @return
- */
- private boolean isOnlyGroupPropertyValueChanged(GroupProperty groupProperty, GroupProperty groupProperty2) {
- // Create 2 duplicates for groupPropery and reset their values
- try {
- GroupProperty groupPropertyDuplicate = new GroupProperty(groupProperty);
- groupPropertyDuplicate.setValue(null);
- groupPropertyDuplicate.setSchema(null);
- groupPropertyDuplicate.setParentUniqueId(null);
- GroupProperty groupProperty2Duplicate = new GroupProperty(groupProperty2);
- groupProperty2Duplicate.setValue(null);
- groupProperty2Duplicate.setSchema(null);
- groupProperty2Duplicate.setParentUniqueId(null);
- return groupPropertyDuplicate.equals(groupProperty2Duplicate) && StringUtils.equals(groupPropertyDuplicate.getValueUniqueUid(), groupProperty2Duplicate.getValueUniqueUid());
- } catch (Exception e) {
- log.debug("Failed validate group properties. ", e);
- return false;
- }
- }
-
- /**
* Validate and update GroupDefinition metadata
*
* @param currentGroup
@@ -659,16 +400,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
Either<GroupDefinitionInfo, ResponseFormat> result = null;
// Validate user exist
- Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, GET_GROUP, true);
-
- if (validateUserExists.isRight()) {
- result = Either.right(validateUserExists.right().value());
- return result;
- }
-
+ validateUserExists(userId, GET_GROUP, true);
// Validate component exist
org.openecomp.sdc.be.model.Component component = null;
- String realComponentId = componentId;
try {
ComponentParametersView componentParametersView = new ComponentParametersView();
@@ -677,7 +411,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
componentParametersView.setIgnoreArtifacts(false);
componentParametersView.setIgnoreUsers(false);
- Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView);
+ Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, componentParametersView);
if (validateComponent.isRight()) {
result = Either.right(validateComponent.right().value());
return result;
@@ -714,12 +448,12 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
Map<String, ArtifactDefinition> deploymentArtifacts = null;
if (MapUtils.isNotEmpty(component.getDeploymentArtifacts())) {
- deploymentArtifacts = component.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(a -> a.getUniqueId(), a -> a));
+ deploymentArtifacts = component.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, a -> a));
}
if (artifactsIds != null && !artifactsIds.isEmpty()) {
for (String id : artifactsIds) {
- if (MapUtils.isEmpty(deploymentArtifacts) || !deploymentArtifacts.containsKey(id)) {
+ if (deploymentArtifacts == null || !deploymentArtifacts.containsKey(id)) {
log.debug("Failed to get artifact {} . Status is {} ", id, StorageOperationStatus.NOT_FOUND);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND));
result = Either.right(responseFormat);
@@ -777,36 +511,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
return result;
}
- public String getAsString(List<String> list) {
-
- if (list == null || list.isEmpty()) {
- return "";
- }
- StringBuilder builder = new StringBuilder();
- list.forEach(p -> builder.append(p + ","));
-
- String result = builder.toString();
- return result.substring(0, result.length());
-
- }
-
-
- private Either<List<GroupProperty>, ResponseFormat> updateGroupPropertiesValue(String componentId, GroupDefinition currentGroup, List<GroupProperty> groupPropertyToUpdate, boolean inTransaction) {
- Either<List<GroupProperty>, ResponseFormat> result;
-
- Either<List<GroupProperty>, StorageOperationStatus> eitherUpdate = groupsOperation.updateGroupPropertiesOnComponent(componentId, currentGroup, groupPropertyToUpdate);
- if (eitherUpdate.isRight()) {
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(eitherUpdate.right().value());
- result = Either.right(componentsUtils.getResponseFormat(actionStatus));
- } else {
- result = Either.left(eitherUpdate.left().value());
- }
- return result;
- }
-
public Either<Boolean, ResponseFormat> validateGenerateVfModuleGroupNames(List<ArtifactTemplateInfo> allGroups, String resourceSystemName, int startGroupCounter) {
Either<Boolean, ResponseFormat> validateGenerateGroupNamesRes = Either.left(true);
- Collections.sort(allGroups, (art1, art2) -> ArtifactTemplateInfo.compareByGroupName(art1, art2));
+ Collections.sort(allGroups, ArtifactTemplateInfo::compareByGroupName);
for (ArtifactTemplateInfo group : allGroups) {
Either<String, ResponseFormat> validateGenerateGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, group.getDescription(), startGroupCounter++);
if (validateGenerateGroupNameRes.isRight()) {
@@ -837,7 +544,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
return validateGenerateGroupNameRes;
}
- public Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNames(Map<String, GroupDefinition> groups, String resourceSystemName) {
+ Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNames(Map<String, GroupDefinition> groups, String resourceSystemName) {
Map<String, GroupDefinition> updatedNamesGroups = new HashMap<>();
Either<Map<String, GroupDefinition>, ResponseFormat> result = Either.left(updatedNamesGroups);
@@ -884,12 +591,12 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
if (groups != null && !groups.isEmpty()) {
List<Integer> counters = groups.stream().filter(group -> Pattern.compile(Constants.MODULE_NEW_NAME_PATTERN).matcher(group.getName()).matches() || Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(group.getName()).matches())
.map(group -> Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1])).collect(toList());
- counter = (counters == null || counters.isEmpty()) ? 0 : counters.stream().max((a, b) -> Integer.compare(a, b)).get() + 1;
+ counter = (counters == null || counters.isEmpty()) ? 0 : counters.stream().max(Integer::compare).get() + 1;
}
return counter;
}
- public Either<List<GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesOnGraph(List<GroupDefinition> groups, Component component, boolean inTransaction) {
+ public Either<List<GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesOnGraph(List<GroupDefinition> groups, Component component) {
List<GroupDefinition> updatedGroups = new ArrayList<>();
Either<List<GroupDefinition>, ResponseFormat> result = Either.left(updatedGroups);
@@ -924,16 +631,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
Either<GroupDefinitionInfo, ResponseFormat> result = null;
// Validate user exist
- Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, UPDATE_GROUP, true);
-
- if (validateUserExists.isRight()) {
- result = Either.right(validateUserExists.right().value());
- return result;
- }
-
+ validateUserExists(userId, UPDATE_GROUP, true);
// Validate component exist
org.openecomp.sdc.be.model.Component component = null;
- String realComponentId = componentId;
try {
ComponentParametersView componentParametersView = new ComponentParametersView();
@@ -942,7 +642,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
componentParametersView.setIgnoreComponentInstances(false);
componentParametersView.setIgnoreArtifacts(false);
- Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView);
+ Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, componentParametersView);
if (validateComponent.isRight()) {
result = Either.right(validateComponent.right().value());
return result;
@@ -1044,42 +744,6 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
return result;
}
- private int getLatestIntProperty(Map<PropertyNames, String> newValues, Map<PropertyNames, String> parentValues, PropertyNames propertyKey) {
- String value;
- if (newValues.containsKey(propertyKey)) {
- value = newValues.get(propertyKey);
- } else {
- value = parentValues.get(propertyKey);
- }
- return Integer.valueOf(value);
- }
-
- private boolean isPropertyChanged(Map<PropertyNames, String> newValues, Map<PropertyNames, String> parentValues, final PropertyNames minInstances) {
- return newValues.containsKey(minInstances) && !newValues.get(minInstances).equals(parentValues.get(minInstances));
- }
-
- private Either<Boolean, ResponseFormat> validateMinMaxAndInitialCountPropertyLogicVF(Map<PropertyNames, String> newValues, Map<PropertyNames, String> parentValues) {
-
- int latestMaxInstances = getLatestIntProperty(newValues, parentValues, PropertyNames.MAX_INSTANCES);
- int latestInitialCount = getLatestIntProperty(newValues, parentValues, PropertyNames.INITIAL_COUNT);
- int latestMinInstances = getLatestIntProperty(newValues, parentValues, PropertyNames.MIN_INSTANCES);
- Either<Boolean, ResponseFormat> result = Either.left(true);
-
- if (isPropertyChanged(newValues, parentValues, PropertyNames.INITIAL_COUNT) && result.isLeft()
- && (latestInitialCount > latestMaxInstances || latestInitialCount < latestMinInstances)) {
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_INITIAL_COUNT_PROPERTY_VALUE, PropertyNames.INITIAL_COUNT.getPropertyName(), String.valueOf(latestMinInstances), String.valueOf(latestMaxInstances)));
- }
- if (isPropertyChanged(newValues, parentValues, PropertyNames.MAX_INSTANCES) && result.isLeft() &&
- latestMaxInstances < latestInitialCount) {
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER, PropertyNames.MAX_INSTANCES.getPropertyName(), "higher", String.valueOf(latestInitialCount)));
- }
- if (isPropertyChanged(newValues, parentValues, PropertyNames.MIN_INSTANCES) &&
- result.isLeft() && latestMinInstances > latestInitialCount) {
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER, PropertyNames.MIN_INSTANCES.getPropertyName(), "lower", String.valueOf(latestInitialCount)));
- }
- return result;
- }
-
private Either<Boolean, ResponseFormat> validateMinMaxAndInitialCountPropertyLogic(Map<PropertyNames, String> newValues, Map<PropertyNames, String> currValues, Map<PropertyNames, String> parentValues) {
Either<Boolean, ResponseFormat> result;
@@ -1088,24 +752,24 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
if (currPropertyName == PropertyNames.MIN_INSTANCES) {
String minValue = parentValues.get(PropertyNames.MIN_INSTANCES);
String maxValue = newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MAX_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT);
- result = validateValueInRange(new ImmutablePair<PropertyNames, String>(currPropertyName, entry.getValue()), new ImmutablePair<PropertyNames, String>(PropertyNames.MIN_INSTANCES, minValue),
- new ImmutablePair<PropertyNames, String>(PropertyNames.MAX_INSTANCES, maxValue));
+ result = validateValueInRange(new ImmutablePair<>(currPropertyName, entry.getValue()), new ImmutablePair<>(PropertyNames.MIN_INSTANCES, minValue),
+ new ImmutablePair<>(PropertyNames.MAX_INSTANCES, maxValue));
if (result.isRight()) {
return result;
}
} else if (currPropertyName == PropertyNames.INITIAL_COUNT) {
String minValue = newValues.containsKey(PropertyNames.MIN_INSTANCES) ? newValues.get(PropertyNames.MIN_INSTANCES) : currValues.get(PropertyNames.MIN_INSTANCES);
String maxValue = newValues.containsKey(PropertyNames.MAX_INSTANCES) ? newValues.get(PropertyNames.MAX_INSTANCES) : currValues.get(PropertyNames.MAX_INSTANCES);
- result = validateValueInRange(new ImmutablePair<PropertyNames, String>(currPropertyName, entry.getValue()), new ImmutablePair<PropertyNames, String>(PropertyNames.MIN_INSTANCES, minValue),
- new ImmutablePair<PropertyNames, String>(PropertyNames.MAX_INSTANCES, maxValue));
+ result = validateValueInRange(new ImmutablePair<>(currPropertyName, entry.getValue()), new ImmutablePair<>(PropertyNames.MIN_INSTANCES, minValue),
+ new ImmutablePair<>(PropertyNames.MAX_INSTANCES, maxValue));
if (result.isRight()) {
return result;
}
} else if (currPropertyName == PropertyNames.MAX_INSTANCES) {
String minValue = newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MIN_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT);
String maxValue = parentValues.get(PropertyNames.MAX_INSTANCES);
- result = validateValueInRange(new ImmutablePair<PropertyNames, String>(currPropertyName, entry.getValue()), new ImmutablePair<PropertyNames, String>(PropertyNames.MIN_INSTANCES, minValue),
- new ImmutablePair<PropertyNames, String>(PropertyNames.MAX_INSTANCES, maxValue));
+ result = validateValueInRange(new ImmutablePair<>(currPropertyName, entry.getValue()), new ImmutablePair<>(PropertyNames.MIN_INSTANCES, minValue),
+ new ImmutablePair<>(PropertyNames.MAX_INSTANCES, maxValue));
if (result.isRight()) {
return result;
}
@@ -1149,10 +813,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
*
* @param oldGroupInstance
* @param newProperties
- * @param inTransaction
* @return
*/
- public Either<GroupInstance, ResponseFormat> validateAndUpdateGroupInstancePropertyValues(String componentId, String instanceId, GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties, boolean inTransaction) {
+ public Either<GroupInstance, ResponseFormat> validateAndUpdateGroupInstancePropertyValues(String componentId, String instanceId, GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties) {
Either<GroupInstance, ResponseFormat> actionResult = null;
Either<GroupInstance, StorageOperationStatus> updateGroupInstanceResult = null;
@@ -1179,7 +842,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
Either<Boolean, ResponseFormat> validationRes = null;
Either<List<GroupInstanceProperty>, ResponseFormat> actionResult;
- Map<String, GroupInstanceProperty> existingProperties = oldGroupInstance.convertToGroupInstancesProperties().stream().collect(Collectors.toMap(p -> p.getName(), p -> p));
+ Map<String, GroupInstanceProperty> existingProperties = oldGroupInstance.convertToGroupInstancesProperties().stream().collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p));
Map<PropertyNames, String> newPropertyValues = new EnumMap<>(PropertyNames.class);
List<GroupInstanceProperty> reducedProperties = new ArrayList<>();
String currPropertyName;
@@ -1312,52 +975,54 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
}
- public GroupDefinition createGroup(String groupType, ComponentTypeEnum componentTypeEnum, String componentId,
+ @LockingTransactional
+ public GroupDefinition createGroup(String componentId, ComponentTypeEnum componentTypeEnum, String groupType,
String userId) {
- try {
- Component component = accessValidations.validateUserCanWorkOnComponentAndLockIt(componentTypeEnum, componentId, userId, CREATE_GROUP);
+ Component component = accessValidations.validateUserCanWorkOnComponent(componentId, componentTypeEnum, userId, CREATE_GROUP);
- validateGroupTypePerComponent(groupType, component);
+ validateGroupTypePerComponent(groupType, component);
- GroupTypeDefinition groupTypeDefinition = groupTypeOperation.getLatestGroupTypeByType(groupType, false)
- .left()
- .on(se -> onGroupTypeNotFound(component));
+ GroupTypeDefinition groupTypeDefinition = groupTypeOperation.getLatestGroupTypeByType(groupType, false)
+ .left()
+ .on(se -> onGroupTypeNotFound(component));
- boolean isFirstGroup = component.getGroups() == null;
- GroupDefinition groupDefinition = new GroupDefinition();
- groupDefinition.setType(groupType);
+ boolean hasExistingGroups = CollectionUtils.isNotEmpty(component.getGroups());
+ GroupDefinition groupDefinition = new GroupDefinition();
+ groupDefinition.setType(groupType);
- //find next valid counter
- int nextCounter = 0;
- if (!isFirstGroup) {
- nextCounter = getNewGroupCounter(component);
- }
- String name = TopologyTemplateOperation.buildSubComponentName(component.getName(), groupType, nextCounter);
- groupDefinition.setName(name);
-
- //Add default type properties
- List<PropertyDefinition> groupTypeProperties = groupTypeDefinition.getProperties();
- List<GroupProperty> properties = groupTypeProperties.stream()
- .map(GroupProperty::new)
- .collect(toList());
- groupDefinition.convertFromGroupProperties(properties);
-
- List<GroupDefinition> gdList;
- if (isFirstGroup) {
- gdList = createGroups(component, Arrays.asList(groupDefinition))
- .left()
- .on(this::onFailedGroupDBOperation);
- } else {
- gdList = addGroups(component, Arrays.asList(groupDefinition))
- .left()
- .on(this::onFailedGroupDBOperation);
- }
- return gdList.get(0);
- } finally {
- titanDao.commit();
- graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
+ //find next valid counter
+ int nextCounter = 0;
+ if (hasExistingGroups) {
+ nextCounter = getNewGroupCounter(component);
+ }
+ String name = TopologyTemplateOperation.buildSubComponentName(component.getName(), groupType, nextCounter);
+ groupDefinition.setName(name);
+ groupDefinition.setDescription(groupTypeDefinition.getDescription());
+ groupDefinition.setInvariantName(name);
+ groupDefinition.setCreatedFrom(CreatedFrom.UI);
+
+ //Add default type properties
+ List<PropertyDefinition> groupTypeProperties = groupTypeDefinition.getProperties();
+ List<GroupProperty> properties = groupTypeProperties.stream()
+ .map(GroupProperty::new)
+ .collect(toList());
+ groupDefinition.convertFromGroupProperties(properties);
+
+ groupDefinition.convertCapabilityDefinitions(groupTypeDefinition.getCapabilities());
+
+ List<GroupDefinition> gdList;
+ if (toscaOperationFacade.canAddGroups(componentId)) {
+ gdList = addGroups(component, Arrays.asList(groupDefinition), false)
+ .left()
+ .on(this::onFailedGroupDBOperation);
+ } else {
+ //createGroups also creates an edge and vertex to store group data
+ gdList = createGroups(component, Arrays.asList(groupDefinition), false)
+ .left()
+ .on(this::onFailedGroupDBOperation);
}
+ return gdList.get(0);
}
private void validateGroupTypePerComponent(String groupType, Component component) {
@@ -1391,28 +1056,23 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
return Utils.getNextCounter(existingIds);
}
- public GroupDefinition updateGroup(ComponentTypeEnum componentTypeEnum, String componentId, String groupId,
+ @LockingTransactional
+ public GroupDefinition updateGroup(String componentId, ComponentTypeEnum componentTypeEnum, String groupId,
String userId, GroupDefinition updatedGroup) {
- try {
- Component component = accessValidations.validateUserCanWorkOnComponentAndLockIt(componentTypeEnum, componentId, userId, UPDATE_GROUP);
-
- GroupDefinition existingGroup = findGroupOnComponent(component, groupId)
- .left()
- .on(se -> onGroupNotFoundInComponentError(component, groupId));
+ Component component = accessValidations.validateUserCanWorkOnComponent(componentId, componentTypeEnum, userId, UPDATE_GROUP);
- String existingGroupName = existingGroup.getName();
- String updatedGroupName = updatedGroup.getName();
- assertNewNameIsValidAndUnique(existingGroupName, updatedGroupName, component);
- existingGroup.setName(updatedGroupName);
+ GroupDefinition existingGroup = findGroupOnComponent(component, groupId)
+ .left()
+ .on(se -> onGroupNotFoundInComponentError(component, groupId));
- return updateGroup(component, existingGroup, existingGroupName)
- .left()
- .on(this::onFailedUpdateGroupDBOperation);
- } finally {
- titanDao.commit();
- graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
- }
+ String existingGroupName = existingGroup.getName();
+ String updatedGroupName = updatedGroup.getName();
+ assertNewNameIsValidAndUnique(existingGroupName, updatedGroupName, component);
+ existingGroup.setName(updatedGroupName);
+ return updateGroup(component, existingGroup, existingGroupName)
+ .left()
+ .on(this::onFailedUpdateGroupDBOperation);
}
private void assertNewNameIsValidAndUnique(String currentGroupName, String updatedGroupName, Component component) {
@@ -1427,23 +1087,21 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
}
- public GroupDefinition deleteGroup(ComponentTypeEnum componentTypeEnum, String componentId, String groupId,
- String userId) {
- try {
- Component component = accessValidations.validateUserCanWorkOnComponentAndLockIt(componentTypeEnum, componentId, userId, DELETE_GROUP);
+ @LockingTransactional
+ public GroupDefinition deleteGroup(String componentId, ComponentTypeEnum componentTypeEnum, String groupId,
+ String userId) {
+ Component component = accessValidations.validateUserCanWorkOnComponent(componentId, componentTypeEnum, userId, DELETE_GROUP);
- GroupDefinition groupDefinition = findGroupOnComponent(component, groupId)
- .left()
- .on(se -> onGroupNotFoundInComponentError(component, groupId));
+ GroupDefinition groupDefinition = findGroupOnComponent(component, groupId)
+ .left()
+ .on(se -> onGroupNotFoundInComponentError(component, groupId));
- List<GroupDefinition> gdList = deleteGroups(component, java.util.Arrays.asList(groupDefinition))
- .left()
- .on(this::onFailedGroupDBOperation);
- return gdList.get(0);
- } finally {
- titanDao.commit();
- graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
- }
+ List<GroupDefinition> gdList = deleteGroups(component, java.util.Arrays.asList(groupDefinition))
+ .left()
+ .on(this::onFailedGroupDBOperation);
+
+ updatePolicyTargetReferencingDeletedGroup(groupId, component);
+ return gdList.get(0);
}
private List<GroupDefinition> onFailedGroupDBOperation(ResponseFormat responseFormat) {
@@ -1466,7 +1124,17 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
component.getComponentType().toString());
}
- public Either<List<GroupDefinition>, ResponseFormat> createGroups(Component component, final List<GroupDefinition> groupDefinitions) {
+ private void updatePolicyTargetReferencingDeletedGroup(String groupId, Component component) {
+ log.debug("#updatePolicyTargetReferencingDeletedGroup - removing all component {} policy targets referencing group {}", component.getUniqueId(), groupId);
+ ActionStatus actionStatus = policyTargetsUpdateHandler.removePoliciesTargets(component, groupId, PolicyTargetType.GROUPS);
+ if (ActionStatus.OK != actionStatus) {
+ titanDao.rollback();
+ throw new ComponentException(actionStatus, groupId);
+ }
+ }
+
+
+ public Either<List<GroupDefinition>, ResponseFormat> createGroups(Component component, final List<GroupDefinition> groupDefinitions, boolean fromCsar) {
Map<String, GroupDataDefinition> groups = new HashMap<>();
Either<List<GroupDefinition>, ResponseFormat> result = null;
@@ -1499,12 +1167,43 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
}
if (result == null) {
- result = Either.left(createGroupsResult.left().value());
+ addCalculatedCapabilitiesWithPropertiesToComponent(component, groupDefinitions, fromCsar);
+ }
+ if (result == null) {
+ result = Either.left(groupDefinitions);
}
return result;
}
- public Either<List<GroupDefinition>, ResponseFormat> addGroups(Component component, final List<GroupDefinition> groupDefinitions) {
+ private void updateCalculatedCapabilitiesWithPropertiesOnComponent(Component component, final List<GroupDefinition> groupDefinitions, boolean fromCsar) {
+ groupDefinitions.forEach(GroupDefinition::updateEmptyCapabilitiesOwnerFields);
+ StorageOperationStatus status = groupsOperation.updateCalculatedCapabilitiesWithProperties(component.getUniqueId(),
+ extractCapabilitiesFromGroups(groupDefinitions), extractCapabilityPropertiesFromGroups(groupDefinitions, fromCsar));
+ if(status != StorageOperationStatus.OK){
+ log.error("#updateCalculatedCapabilitiesWithPropertiesOnComponent - failed to update the groups' calculated capabilities with the properties on the component {}. ", component.getUniqueId());
+ rollbackWithException(componentsUtils.convertFromStorageResponse(status));
+ }
+ }
+
+ private void addCalculatedCapabilitiesWithPropertiesToComponent(Component component, final List<GroupDefinition> groupDefinitions, boolean fromCsar) {
+ groupDefinitions.forEach(GroupDefinition::updateEmptyCapabilitiesOwnerFields);
+ StorageOperationStatus status = groupsOperation.addCalculatedCapabilitiesWithProperties(component.getUniqueId(),
+ extractCapabilitiesFromGroups(groupDefinitions), extractCapabilityPropertiesFromGroups(groupDefinitions, fromCsar));
+ if(status != StorageOperationStatus.OK){
+ log.error("#addCalculatedCapabilitiesWithPropertiesToComponent - failed to add the groups' calculated capabilities with the properties to the component {}. ", component.getUniqueId());
+ rollbackWithException(componentsUtils.convertFromStorageResponse(status));
+ }
+ }
+
+ private void deleteCalculatedCapabilitiesWithPropertiesFromComponent(Component component, final List<GroupDefinition> groupDefinitions) {
+ StorageOperationStatus status = groupsOperation.deleteCalculatedCapabilitiesWithProperties(component.getUniqueId(), groupDefinitions);
+ if(status != StorageOperationStatus.OK){
+ log.error("#deleteCalculatedCapabilitiesWithPropertiesFromComponent - failed to remove the groups' calculated capabilities with the properties from the component {}. ", component.getUniqueId());
+ rollbackWithException(componentsUtils.convertFromStorageResponse(status));
+ }
+ }
+
+ public Either<List<GroupDefinition>, ResponseFormat> addGroups(Component component, final List<GroupDefinition> groupDefinitions, boolean fromCsar) {
Either<List<GroupDefinition>, ResponseFormat> result = null;
Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult = null;
@@ -1537,7 +1236,10 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
}
}
if (result == null) {
- result = Either.left(createGroupsResult.left().value());
+ addCalculatedCapabilitiesWithPropertiesToComponent(component, groupDefinitions, fromCsar);
+ }
+ if (result == null) {
+ result = Either.left(groupDefinitions);
}
return result;
}
@@ -1546,34 +1248,39 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
Either<List<GroupDefinition>, StorageOperationStatus> deleteGroupsResult;
- deleteGroupsResult = groupsOperation.deleteGroups(component, groupDefinitions.stream().map(x -> new GroupDataDefinition(x)).collect(toList()));
+ deleteGroupsResult = groupsOperation.deleteGroups(component, groupDefinitions.stream().map(GroupDataDefinition::new).collect(toList()));
if (deleteGroupsResult.isRight()) {
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteGroupsResult.right().value())));
+ } else {
+ deleteCalculatedCapabilitiesWithPropertiesFromComponent(component, groupDefinitions);
}
return Either.left(deleteGroupsResult.left().value());
}
/**
* Update specific group version
+ * @param fromCsar TODO
*
*/
- public Either<List<GroupDefinition>, ResponseFormat> updateGroups(Component component, List<GroupDefinition> groupDefinitions) {
+ public Either<List<GroupDefinition>, ResponseFormat> updateGroups(Component component, List<GroupDefinition> groupDefinitions, boolean fromCsar) {
Either<List<GroupDefinition>, ResponseFormat> result = null;
Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult;
- createGroupsResult = groupsOperation.updateGroups(component, groupDefinitions.stream().map(GroupDataDefinition::new).collect(toList()));
+ createGroupsResult = groupsOperation.updateGroups(component, groupDefinitions.stream().map(GroupDataDefinition::new).collect(toList()), true);
if (createGroupsResult.isRight()) {
result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value())));
}
-
if (result == null) {
- result = Either.left(createGroupsResult.left().value());
+ updateCalculatedCapabilitiesWithPropertiesOnComponent(component, groupDefinitions, fromCsar);
+ }
+ if (result == null) {
+ result = Either.left(groupDefinitions);
}
return result;
}
- public Either<GroupDefinition, ResponseFormat> handleGroup(Component component, GroupDefinition groupDefinition, Map<String, DataTypeDefinition> allDAtaTypes) {
+ private Either<GroupDefinition, ResponseFormat> handleGroup(Component component, GroupDefinition groupDefinition, Map<String, DataTypeDefinition> allDAtaTypes) {
log.trace("Going to create group {}", groupDefinition);
// 3. verify group not already exist
@@ -1623,7 +1330,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.MATCH_NOT_FOUND))));
}
- Map<String, PropertyDefinition> groupTypePropertiesMap = groupTypeProperties.stream().collect(Collectors.toMap(p -> p.getName(), p -> p));
+ Map<String, PropertyDefinition> groupTypePropertiesMap = groupTypeProperties.stream().collect(Collectors.toMap(PropertyDefinition::getName, p -> p));
Either<GroupProperty, TitanOperationStatus> addPropertyResult;
int i = 1;
@@ -1638,6 +1345,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
i++;
}
}
+
if (groupDefinition.getUniqueId() == null) {
String uid = UniqueIdBuilder.buildGroupingUid(component.getUniqueId(), groupDefinitionName);
groupDefinition.setUniqueId(uid);
@@ -1666,11 +1374,10 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
}
- PropertyDataDefinition propDataDef = prop;
- String propertyType = propDataDef.getType();
+ String propertyType = prop.getType();
String value = groupProperty.getValue();
- Either<String, TitanOperationStatus> checkInnerType = propertyOperation.checkInnerType(propDataDef);
+ Either<String, TitanOperationStatus> checkInnerType = propertyOperation.checkInnerType(prop);
if (checkInnerType.isRight()) {
TitanOperationStatus status = checkInnerType.right().value();
return Either.right(status);
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogicNew.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogicNew.java
new file mode 100644
index 0000000000..855e55c415
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogicNew.java
@@ -0,0 +1,231 @@
+package org.openecomp.sdc.be.components.impl;
+
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.collections.MapUtils;
+import org.apache.commons.lang.StringUtils;
+import org.apache.commons.lang3.math.NumberUtils;
+import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
+import org.openecomp.sdc.be.components.impl.lock.LockingTransactional;
+import org.openecomp.sdc.be.components.validation.AccessValidations;
+import org.openecomp.sdc.be.components.validation.ComponentValidations;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.model.*;
+import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation;
+import org.openecomp.sdc.be.model.operations.StorageException;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.GroupOperation;
+import org.openecomp.sdc.common.util.ValidationUtils;
+import org.springframework.transaction.annotation.Transactional;
+
+import java.util.*;
+import java.util.stream.Collectors;
+
+import static org.openecomp.sdc.be.components.impl.BaseBusinessLogic.enumHasValueFilter;
+
+@org.springframework.stereotype.Component
+public class GroupBusinessLogicNew {
+
+ private final AccessValidations accessValidations;
+ private final ComponentValidations componentValidations;
+ private final GroupsOperation groupsOperation;
+ private final GroupOperation groupOperation;
+
+ public GroupBusinessLogicNew(AccessValidations accessValidations, ComponentValidations componentValidations, GroupsOperation groupsOperation, GroupOperation groupOperation) {
+ this.accessValidations = accessValidations;
+ this.componentValidations = componentValidations;
+ this.groupsOperation = groupsOperation;
+ this.groupOperation = groupOperation;
+ }
+
+ @LockingTransactional
+ public List<String> updateMembers(String componentId, ComponentTypeEnum componentType, String userId, String groupUniqueId, List<String> members) {
+ Component component = accessValidations.validateUserCanWorkOnComponent(componentId, componentType, userId, "UPDATE GROUP MEMBERS");
+ GroupDefinition groupDefinition = getGroup(component, groupUniqueId);
+ groupDefinition.setMembers(buildMembersMap(component, members));
+ groupsOperation.updateGroupOnComponent(componentId, groupDefinition);
+ return new ArrayList<>(groupDefinition.getMembers().values());
+ }
+
+ @LockingTransactional
+ public List<GroupProperty> updateProperties(String componentId, ComponentTypeEnum componentType, String userId, String groupUniqueId, List<GroupProperty> newProperties) {
+ Component component = accessValidations.validateUserCanWorkOnComponent(componentId, componentType, userId, "UPDATE GROUP PROPERTIES");
+ GroupDefinition currentGroup = getGroup(component, groupUniqueId);
+ validateUpdatedPropertiesAndSetEmptyValues(currentGroup, newProperties);
+ return groupsOperation.updateGroupPropertiesOnComponent(componentId, currentGroup, newProperties)
+ .left()
+ .on(this::onUpdatePropertyError);
+ }
+
+ @Transactional
+ public List<PropertyDataDefinition> getProperties(String componentType, String userId, String componentId, String groupUniqueId) {
+ Component component = accessValidations.validateUserCanRetrieveComponentData(componentId, componentType, userId, "GET GROUP PROPERTIES");
+ GroupDefinition currentGroup = getGroup(component, groupUniqueId);
+ return currentGroup.getProperties();
+ }
+
+ private List<GroupProperty> onUpdatePropertyError(StorageOperationStatus storageOperationStatus) {
+ throw new StorageException(storageOperationStatus);
+ }
+
+ private Map<String, String> buildMembersMap(Component component, List<String> newMemberUniqueIds) {
+ Map<String, String> nameToUniqueId = new HashMap<>();
+ for (String memberUniqueId : newMemberUniqueIds) {
+ ComponentInstance componentInstance = getComponentInstance(component, memberUniqueId);
+ nameToUniqueId.put(componentInstance.getName(), componentInstance.getUniqueId());
+ }
+ return nameToUniqueId;
+ }
+
+ private ComponentInstance getComponentInstance(Component component, String memberUniqueId) {
+ return componentValidations.getComponentInstance(component, memberUniqueId)
+ .orElseThrow(() -> new ComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
+ memberUniqueId, "",
+ component.getActualComponentType(), component.getSystemName()));
+ }
+
+ private GroupDefinition getGroup(Component component, String groupUniqueId) {
+ return component.getGroupById(groupUniqueId)
+ .orElseThrow(() -> new ComponentException(ActionStatus.GROUP_IS_MISSING,
+ component.getSystemName(), component.getActualComponentType()));
+ }
+
+ private void validateUpdatedPropertiesAndSetEmptyValues(GroupDefinition originalGroup, List<GroupProperty> groupPropertiesToUpdate) {
+
+ if (CollectionUtils.isEmpty(groupPropertiesToUpdate)) {
+ throw new ComponentException(ActionStatus.PROPERTY_NOT_FOUND, StringUtils.EMPTY);
+ }
+ if (CollectionUtils.isEmpty(originalGroup.getProperties())) {
+ throw new ComponentException(ActionStatus.PROPERTY_NOT_FOUND, groupPropertiesToUpdate.get(NumberUtils.INTEGER_ZERO).getName());
+ }
+ Map<String, GroupProperty> originalProperties = originalGroup.convertToGroupProperties()
+ .stream()
+ .collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p));
+
+
+ for (GroupProperty gp : groupPropertiesToUpdate) {
+ String updatedPropertyName = gp.getName();
+ if (!originalProperties.containsKey(updatedPropertyName)) {
+ throw new ComponentException(ActionStatus.PROPERTY_NOT_FOUND, updatedPropertyName);
+ }
+ if (!isOnlyGroupPropertyValueChanged(gp, originalProperties.get(updatedPropertyName))) {
+ throw new ComponentException(ActionStatus.INVALID_PROPERTY, updatedPropertyName);
+ }
+ if (StringUtils.isEmpty(gp.getValue())) {
+ gp.setValue(originalProperties.get(updatedPropertyName).getDefaultValue());
+ }
+ StorageOperationStatus sos = groupOperation.validateAndUpdatePropertyValue(gp);
+ if (StorageOperationStatus.OK != sos) {
+ throw new StorageException(sos, updatedPropertyName);
+ }
+ }
+
+ validatePropertyBusinessLogic(groupPropertiesToUpdate, originalGroup);
+ }
+
+ private void validatePropertyBusinessLogic(List<GroupProperty> groupPropertiesToUpdate, GroupDefinition originalGroup) {
+
+ Map<PropertyDefinition.PropertyNames, String> enumValueMap = new EnumMap<>(PropertyDefinition.PropertyNames.class);
+ for (GroupProperty gp : groupPropertiesToUpdate) {
+ // Filter out non special properties which does not have Enum
+ final PropertyDefinition.PropertyNames gpEnum = PropertyDefinition.PropertyNames.findName(gp.getName());
+ if (gpEnum != null) {
+ enumValueMap.put(gpEnum, gp.getValue());
+ }
+ }
+ if (MapUtils.isEmpty(enumValueMap)) {
+ return;
+ }
+
+ validateVFInstancesLogic(enumValueMap, prepareMapWithOriginalProperties(originalGroup));
+
+ if (enumValueMap.containsKey(PropertyDefinition.PropertyNames.VF_MODULE_DESCRIPTION) || enumValueMap.containsKey(PropertyDefinition.PropertyNames.VF_MODULE_LABEL)) {
+ groupPropertiesToUpdate.stream()
+ .filter(e -> enumHasValueFilter(e.getName(), PropertyDefinition.PropertyNames::findName, PropertyDefinition.PropertyNames.VF_MODULE_DESCRIPTION, PropertyDefinition.PropertyNames.VF_MODULE_LABEL))
+ .forEach(this::validateFreeText);
+ }
+ }
+
+ private Map<PropertyDefinition.PropertyNames, String> prepareMapWithOriginalProperties(GroupDefinition originalGroup) {
+ Map<PropertyDefinition.PropertyNames, String> oldValueMap = new EnumMap<>(PropertyDefinition.PropertyNames.class);
+ PropertyDefinition.PropertyNames[] propertiesToCheck = new PropertyDefinition.PropertyNames[] { PropertyDefinition.PropertyNames.INITIAL_COUNT, PropertyDefinition.PropertyNames.MAX_INSTANCES, PropertyDefinition.PropertyNames.MIN_INSTANCES };
+
+ for (GroupProperty gp : originalGroup.convertToGroupProperties()) {
+ if (enumHasValueFilter(gp.getName(), PropertyDefinition.PropertyNames::findName, propertiesToCheck)) {
+ oldValueMap.put(PropertyDefinition.PropertyNames.findName(gp.getName()), gp.getValue());
+ }
+ }
+ if (StringUtils.isEmpty(oldValueMap.get(PropertyDefinition.PropertyNames.MAX_INSTANCES))) {
+ oldValueMap.put(PropertyDefinition.PropertyNames.MAX_INSTANCES, String.valueOf(Integer.MAX_VALUE));
+ }
+ return oldValueMap;
+ }
+
+ private void validateVFInstancesLogic(Map<PropertyDefinition.PropertyNames, String> newValues, Map<PropertyDefinition.PropertyNames, String> parentValues) {
+ if (!newValues.containsKey(PropertyDefinition.PropertyNames.INITIAL_COUNT)
+ && !newValues.containsKey(PropertyDefinition.PropertyNames.MAX_INSTANCES)
+ && !newValues.containsKey(PropertyDefinition.PropertyNames.MIN_INSTANCES)) {
+ return;
+ }
+ int latestMaxInstances = getLatestIntProperty(newValues, parentValues, PropertyDefinition.PropertyNames.MAX_INSTANCES);
+ int latestInitialCount = getLatestIntProperty(newValues, parentValues, PropertyDefinition.PropertyNames.INITIAL_COUNT);
+ int latestMinInstances = getLatestIntProperty(newValues, parentValues, PropertyDefinition.PropertyNames.MIN_INSTANCES);
+
+ if (isPropertyChanged(newValues, parentValues, PropertyDefinition.PropertyNames.INITIAL_COUNT)
+ && (latestInitialCount > latestMaxInstances || latestInitialCount < latestMinInstances)) {
+ throw new ComponentException(ActionStatus.INVALID_GROUP_INITIAL_COUNT_PROPERTY_VALUE, PropertyDefinition.PropertyNames.INITIAL_COUNT.getPropertyName(), String.valueOf(latestMinInstances), String.valueOf(latestMaxInstances));
+ }
+ if (isPropertyChanged(newValues, parentValues, PropertyDefinition.PropertyNames.MAX_INSTANCES) &&
+ latestMaxInstances < latestInitialCount) {
+ throw new ComponentException(ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER, PropertyDefinition.PropertyNames.MAX_INSTANCES.getPropertyName(), "higher", String.valueOf(latestInitialCount));
+ }
+ if (isPropertyChanged(newValues, parentValues, PropertyDefinition.PropertyNames.MIN_INSTANCES) &&
+ latestMinInstances > latestInitialCount) {
+ throw new ComponentException(ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER, PropertyDefinition.PropertyNames.MIN_INSTANCES.getPropertyName(), "lower", String.valueOf(latestInitialCount));
+ }
+ }
+
+ private boolean isPropertyChanged(Map<PropertyDefinition.PropertyNames, String> newValues, Map<PropertyDefinition.PropertyNames, String> parentValues, final PropertyDefinition.PropertyNames minInstances) {
+ return newValues.containsKey(minInstances) && !newValues.get(minInstances).equals(parentValues.get(minInstances));
+ }
+
+ private int getLatestIntProperty(Map<PropertyDefinition.PropertyNames, String> newValues, Map<PropertyDefinition.PropertyNames, String> parentValues, PropertyDefinition.PropertyNames propertyKey) {
+ String value;
+ if (newValues.containsKey(propertyKey)) {
+ value = newValues.get(propertyKey);
+ } else {
+ value = parentValues.get(propertyKey);
+ }
+ return Integer.valueOf(value);
+ }
+
+ private boolean isOnlyGroupPropertyValueChanged(GroupProperty groupProperty1, GroupProperty groupProperty2) {
+ GroupProperty groupProperty1Duplicate = new GroupProperty(groupProperty1);
+ groupProperty1Duplicate.setValue(null);
+ groupProperty1Duplicate.setSchema(null);
+ groupProperty1Duplicate.setParentUniqueId(null);
+ GroupProperty groupProperty2Duplicate = new GroupProperty(groupProperty2);
+ groupProperty2Duplicate.setValue(null);
+ groupProperty2Duplicate.setSchema(null);
+ groupProperty2Duplicate.setParentUniqueId(null);
+ return StringUtils.equals(groupProperty1Duplicate.getValueUniqueUid(), groupProperty2Duplicate.getValueUniqueUid())
+ && groupProperty1Duplicate.equals(groupProperty2Duplicate);
+ }
+
+ private void validateFreeText(GroupProperty groupPropertyToUpdate) {
+ final String groupTypeValue = groupPropertyToUpdate.getValue();
+ if (!org.apache.commons.lang3.StringUtils.isEmpty(groupTypeValue)) {
+ if (!ValidationUtils.validateDescriptionLength(groupTypeValue)) {
+ throw new ComponentException(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT,
+ NodeTypeEnum.Property.getName(),
+ String.valueOf(ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH));
+ } else if (!ValidationUtils.validateIsEnglish(groupTypeValue)) {
+ throw new ComponentException(ActionStatus.COMPONENT_INVALID_DESCRIPTION,
+ NodeTypeEnum.Property.getName());
+ }
+ }
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeBusinessLogic.java
index d852ac3c3c..99c4e9e181 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeBusinessLogic.java
@@ -1,46 +1,70 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.List;
-import java.util.Set;
-
+import org.apache.commons.lang3.StringUtils;
import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
import org.openecomp.sdc.be.components.validation.UserValidations;
import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.GroupTypeDefinition;
-import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation;
-import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.stereotype.Component;
-@Component
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import static java.util.Collections.emptySet;
+
+@Component("groupTypeBusinessLogic")
public class GroupTypeBusinessLogic {
private final GroupTypeOperation groupTypeOperation;
private final TitanDao titanDao;
private final UserValidations userValidations;
+ private final ComponentsUtils componentsUtils;
- public GroupTypeBusinessLogic(GroupTypeOperation groupTypeOperation, TitanDao titanDao, UserValidations userValidations) {
+ public GroupTypeBusinessLogic(GroupTypeOperation groupTypeOperation, TitanDao titanDao, UserValidations userValidations, ComponentsUtils componentsUtils) {
this.groupTypeOperation = groupTypeOperation;
this.titanDao = titanDao;
this.userValidations = userValidations;
+ this.componentsUtils = componentsUtils;
}
public List<GroupTypeDefinition> getAllGroupTypes(String userId, String internalComponentType) {
try {
- userValidations.validateUserExists(userId, "get group types", true)
- .left()
- .on(this::onUserError);
-
- Set<String> excludeGroupTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedGroupTypesMapping().get(internalComponentType);
+ userValidations.validateUserExists(userId, "get group types", true);
+ Set<String> excludeGroupTypes = getExcludedGroupTypes(internalComponentType);
return groupTypeOperation.getAllGroupTypes(excludeGroupTypes);
} finally {
titanDao.commit();
}
}
- private User onUserError(ResponseFormat responseFormat) {
- throw new ComponentException(responseFormat);
+ public GroupTypeDefinition getLatestGroupTypeByType(String groupTypeName) {
+ return groupTypeOperation.getLatestGroupTypeByType(groupTypeName, true)
+ .left()
+ .on(e -> failOnGetGroupType(e, groupTypeName));
+ }
+
+ public Set<String> getExcludedGroupTypes(String internalComponentType) {
+ if (StringUtils.isEmpty(internalComponentType)) {
+ return emptySet();
+ }
+ Map<String, Set<String>> excludedGroupTypesMapping = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedGroupTypesMapping();
+ Set<String> excludedTypes = excludedGroupTypesMapping.get(internalComponentType);
+ return excludedTypes == null ? emptySet() : excludedTypes;
+ }
+
+ private GroupTypeDefinition failOnGetGroupType(StorageOperationStatus status, String groupType) {
+ titanDao.rollback();
+ if (status == StorageOperationStatus.NOT_FOUND) {
+ throw new ComponentException(ActionStatus.GROUP_TYPE_IS_INVALID, groupType);
+ } else {
+ throw new ComponentException(ActionStatus.GENERAL_ERROR);
+ }
}
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java
index 0485e3a968..4a7b080fbc 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java
@@ -20,76 +20,73 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.stream.Collectors;
-
-import javax.annotation.Resource;
-
+import fj.data.Either;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum;
-import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
+import org.openecomp.sdc.be.components.impl.model.ToscaTypeImportData;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;
import org.openecomp.sdc.be.model.GroupTypeDefinition;
import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
-import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation;
+import org.openecomp.sdc.be.model.utils.TypeCompareUtils;
+import org.openecomp.sdc.be.utils.TypeUtils;
+import org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum;
+import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
-import fj.data.Either;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
@Component("groupTypeImportManager")
public class GroupTypeImportManager {
- public static void main(String[] args) {
-
- List<PropertyDefinition> properties = new ArrayList<>();
- PropertyDefinition propertyDefintion = new PropertyDefinition();
- propertyDefintion.setName("aaa");
- properties.add(propertyDefintion);
-
- List<String> allParentsProps = new ArrayList<>();
- allParentsProps.add("aaa");
- allParentsProps.add("bbb");
-
- Set<String> alreadyExistPropsCollection = properties.stream().filter(p -> allParentsProps.contains(p.getName())).map(p -> p.getName()).collect(Collectors.toSet());
- System.out.println(alreadyExistPropsCollection);
-
+ private static final Logger log = Logger.getLogger(GroupTypeImportManager.class);
+ private final GroupTypeOperation groupTypeOperation;
+ private final ComponentsUtils componentsUtils;
+ private final ToscaOperationFacade toscaOperationFacade;
+ private final CommonImportManager commonImportManager;
+
+ public GroupTypeImportManager(GroupTypeOperation groupTypeOperation, ComponentsUtils componentsUtils, ToscaOperationFacade toscaOperationFacade, CommonImportManager commonImportManager) {
+ this.groupTypeOperation = groupTypeOperation;
+ this.componentsUtils = componentsUtils;
+ this.toscaOperationFacade = toscaOperationFacade;
+ this.commonImportManager = commonImportManager;
}
- private static final Logger log = LoggerFactory.getLogger(GroupTypeImportManager.class);
- @Resource
- private IGroupTypeOperation groupTypeOperation;
- @Resource
- private ComponentsUtils componentsUtils;
- @Resource
- private ToscaOperationFacade toscaOperationFacade;
-
- @Resource
- private CommonImportManager commonImportManager;
-
- public Either<List<ImmutablePair<GroupTypeDefinition, Boolean>>, ResponseFormat> createGroupTypes(String groupTypesYml) {
- return commonImportManager.createElementTypes(groupTypesYml, elementTypeYml -> createGroupTypesFromYml(elementTypeYml), groupTypesList -> createGroupTypesByDao(groupTypesList), ElementTypeEnum.GroupType);
+ public Either<List<ImmutablePair<GroupTypeDefinition, Boolean>>, ResponseFormat> createGroupTypes(ToscaTypeImportData toscaTypeImportData) {
+ return commonImportManager.createElementTypes(toscaTypeImportData, this::createGroupTypesFromYml, this::upsertGroupTypesByDao);
}
private Either<List<GroupTypeDefinition>, ActionStatus> createGroupTypesFromYml(String groupTypesYml) {
+ return commonImportManager.createElementTypesFromYml(groupTypesYml, this::createGroupType);
+ }
- return commonImportManager.createElementTypesFromYml(groupTypesYml, (groupTypeName, groupTypeJsonData) -> createGroupType(groupTypeName, groupTypeJsonData));
+ private Either<List<ImmutablePair<GroupTypeDefinition, Boolean>>, ResponseFormat> upsertGroupTypesByDao(List<GroupTypeDefinition> groupTypesToCreate) {
+ return commonImportManager.createElementTypesByDao(groupTypesToCreate, this::validateGroupType, groupType -> new ImmutablePair<>(ElementTypeEnum.GROUP_TYPE, groupType.getType()),
+ groupTypeOperation::getLatestGroupTypeByType, groupTypeOperation::addGroupType, this::updateGroupType);
}
- private Either<List<ImmutablePair<GroupTypeDefinition, Boolean>>, ResponseFormat> createGroupTypesByDao(List<GroupTypeDefinition> groupTypesToCreate) {
- return commonImportManager.createElementTypesByDao(groupTypesToCreate, groupType -> validateGroupType(groupType), groupType -> new ImmutablePair<>(ElementTypeEnum.GroupType, groupType.getType()),
- groupTypeName -> groupTypeOperation.getLatestGroupTypeByType(groupTypeName), groupType -> groupTypeOperation.addGroupType(groupType), groupTypeOperation::upgradeGroupType);
+ private Either<GroupTypeDefinition, StorageOperationStatus> updateGroupType(GroupTypeDefinition newGroupType, GroupTypeDefinition oldGroupType) {
+ Either<GroupTypeDefinition, StorageOperationStatus> validationRes = groupTypeOperation.validateUpdateProperties(newGroupType);
+ if (validationRes.isRight()) {
+ log.error("#updateGroupType - One or all properties of group type {} not valid. status is {}", newGroupType, validationRes.right().value());
+ return validationRes;
+ }
+
+ if (TypeCompareUtils.isGroupTypesEquals(newGroupType, oldGroupType)) {
+ return TypeCompareUtils.typeAlreadyExists();
+ }
+
+ return groupTypeOperation.updateGroupType(newGroupType, oldGroupType);
}
private Either<ActionStatus, ResponseFormat> validateGroupType(GroupTypeDefinition groupType) {
@@ -123,24 +120,24 @@ public class GroupTypeImportManager {
if (toscaJson != null) {
// Description
- commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DESCRIPTION.getElementName(), groupType::setDescription);
+ commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName(), groupType::setDescription);
// Derived From
- commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DERIVED_FROM.getElementName(), groupType::setDerivedFrom);
+ commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DERIVED_FROM.getElementName(), groupType::setDerivedFrom);
// Properties
- commonImportManager.setProperties(toscaJson, groupType::setProperties);
+ CommonImportManager.setProperties(toscaJson, groupType::setProperties);
// Metadata
- commonImportManager.setField(toscaJson, ToscaTagNamesEnum.METADATA.getElementName(), groupType::setMetadata);
+ commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.METADATA.getElementName(), groupType::setMetadata);
// Capabilities
- List<CapabilityTypeDefinition> capabilityTypes = createGroupCapabilityTypes(toscaJson);
- groupType.setCapabilityTypes(capabilityTypes);
+ Map<String, CapabilityDefinition> capabilities = createCapabilities(toscaJson);
+ groupType.setCapabilities(capabilities);
// Members
- commonImportManager.setField(toscaJson, ToscaTagNamesEnum.MEMBERS.getElementName(), groupType::setMembers);
+ commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.MEMBERS.getElementName(), groupType::setMembers);
groupType.setType(groupTypeName);
groupType.setHighestVersion(true);
- groupType.setVersion(ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION);
+ groupType.setVersion(TypeUtils.FIRST_CERTIFIED_VERSION_VERSION);
}
return groupType;
}
@@ -149,17 +146,17 @@ public class GroupTypeImportManager {
* @param toscaJson
* @return
*/
- private List<CapabilityTypeDefinition> createGroupCapabilityTypes(Map<String, Object> toscaJson) {
+ private Map<String, CapabilityDefinition> createCapabilities(Map<String, Object> toscaJson) {
CapabilityTypeToscaJsonHolder capabilityTypeToscaJsonHolder = new CapabilityTypeToscaJsonHolder();
- commonImportManager.setField(toscaJson, ToscaTagNamesEnum.CAPABILITIES.getElementName(), capabilityTypeToscaJsonHolder::setCapabilityTypeToscaJson);
- List<CapabilityTypeDefinition> capabilityTypes;
+ commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.CAPABILITIES.getElementName(), capabilityTypeToscaJsonHolder::setCapabilityTypeToscaJson);
+ Map<String, CapabilityDefinition> capabilities;
if (capabilityTypeToscaJsonHolder.isEmpty()) {
- capabilityTypes = Collections.emptyList();
+ capabilities = Collections.emptyMap();
}
else {
- capabilityTypes = commonImportManager.createElementTypesFromToscaJsonMap(this::createGroupCapabilityType, capabilityTypeToscaJsonHolder.getCapabilityTypeToscaJson());
+ capabilities = commonImportManager.createElementTypesMapFromToscaJsonMap(this::createCapability, capabilityTypeToscaJsonHolder.getCapabilityTypeToscaJson());
}
- return capabilityTypes;
+ return capabilities;
}
private class CapabilityTypeToscaJsonHolder {
@@ -178,14 +175,25 @@ public class GroupTypeImportManager {
}
}
- private CapabilityTypeDefinition createGroupCapabilityType(String capabilityTypeName, Map<String, Object> toscaJson) {
- CapabilityTypeDefinition capabilityType = new CapabilityTypeDefinition();
+ private CapabilityDefinition createCapability(String capabilityName, Map<String, Object> toscaJson) {
+ CapabilityDefinition capability = new CapabilityDefinition();
- commonImportManager.setField(toscaJson, ToscaTagNamesEnum.TYPE.getElementName(), capabilityType::setType);
+ capability.setName(capabilityName);
+ commonImportManager.setField(toscaJson, ToscaTagNamesEnum.TYPE.getElementName(), capability::setType);
// Properties
- commonImportManager.setPropertiesMap(toscaJson, capabilityType::setProperties);
+ CommonImportManager.setProperties(toscaJson, pl -> capability.setProperties(map(pl)));
+
+ return capability;
+ }
- return capabilityType;
+ /**
+ * @param pl
+ * @return
+ */
+ private List<ComponentInstanceProperty> map(List<PropertyDefinition> pl) {
+ return pl.stream()
+ .map(ComponentInstanceProperty::new)
+ .collect(Collectors.toList());
}
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java
index 4b9203de42..8b69a4575c 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java
@@ -20,30 +20,28 @@
package org.openecomp.sdc.be.components.impl;
-import java.lang.reflect.Type;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.function.Consumer;
-import java.util.function.Function;
-
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.reflect.TypeToken;
+import fj.data.Either;
import org.apache.commons.lang3.StringEscapeUtils;
+import org.openecomp.sdc.be.components.impl.utils.ExceptionUtils;
+import org.openecomp.sdc.be.datatypes.elements.Annotation;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
-import org.openecomp.sdc.be.model.HeatParameterDefinition;
-import org.openecomp.sdc.be.model.InputDefinition;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.PropertyConstraint;
-import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.heat.HeatParameterType;
+import org.openecomp.sdc.be.model.operations.impl.AnnotationTypeOperations;
import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
+import org.openecomp.sdc.be.utils.TypeUtils;
+import org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum;
import org.openecomp.sdc.common.api.ArtifactTypeEnum;
+import org.openecomp.sdc.common.log.wrappers.Logger;
+import org.openecomp.sdc.exception.ResponseFormat;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.YamlProcessor;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
@@ -52,11 +50,16 @@ import org.yaml.snakeyaml.nodes.Tag;
import org.yaml.snakeyaml.representer.Representer;
import org.yaml.snakeyaml.resolver.Resolver;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.reflect.TypeToken;
+import java.lang.reflect.Type;
+import java.util.*;
+import java.util.Map.Entry;
+import java.util.function.Consumer;
+import java.util.function.Function;
+
+import static org.apache.commons.collections.CollectionUtils.isEmpty;
+import static org.openecomp.sdc.be.components.impl.ResourceImportManager.PROPERTY_NAME_PATTERN_IGNORE_LENGTH;
+import static org.openecomp.sdc.be.datatypes.elements.Annotation.setAnnotationsName;
-import fj.data.Either;
public final class ImportUtils {
private ImportUtils() {
@@ -64,7 +67,15 @@ public final class ImportUtils {
}
private static CustomResolver customResolver = new CustomResolver();
- private static Yaml STRICT_MAPPING_YAML_LOADER = new YamlLoader().getStrictYamlLoader();
+ private static Yaml strictYamlLoader = new YamlLoader().getStrictYamlLoader();
+
+ @Autowired
+ protected static ComponentsUtils componentsUtils;
+
+ @Autowired
+ private ExceptionUtils exceptionUtils;
+
+ private static final Logger log = Logger.getLogger(ImportUtils.class);
private static class CustomResolver extends Resolver {
@Override
@@ -106,7 +117,7 @@ public final class ImportUtils {
public static Map<String, Object> loadYamlAsStrictMap(String content){
Map<String, Object> result = new LinkedHashMap<>();
- Object map = STRICT_MAPPING_YAML_LOADER.load(content);
+ Object map = strictYamlLoader.load(content);
buildMap(result, (Map<String, Object>)map);
return result;
}
@@ -124,8 +135,6 @@ public final class ImportUtils {
}
public static class Constants {
-
- public static final String FIRST_CERTIFIED_VERSION_VERSION = "1.0";
public static final String FIRST_NON_CERTIFIED_VERSION = "0.1";
public static final String VENDOR_NAME = "ATT (Tosca)";
public static final String VENDOR_RELEASE = "1.0.0.wd03";
@@ -139,6 +148,8 @@ public final class ImportUtils {
public static final String USER_DEFINED_RESOURCE_NAMESPACE_PREFIX = "org.openecomp.resource.";
public static final String UI_JSON_PAYLOAD_NAME = "payloadName";
public static final String CVFC_DESCRIPTION = "Complex node type that is used as nested type in VF";
+
+ private Constants() {}
}
public enum ResultStatusEnum {
@@ -149,37 +160,6 @@ public final class ImportUtils {
BOOLEAN, STRING, MAP, LIST, ALL
}
- public enum ToscaTagNamesEnum {
- DERIVED_FROM("derived_from"), IS_PASSWORD("is_password"),
- // Properties
- PROPERTIES("properties"), TYPE("type"), STATUS("status"), ENTRY_SCHEMA("entry_schema"), REQUIRED("required"), DESCRIPTION("description"), DEFAULT_VALUE("default"), VALUE("value"), CONSTRAINTS("constraints"),
- // Group Types
- MEMBERS("members"), METADATA("metadata"),
- // Policy Types
- TARGETS("targets"),
- // Capabilities
- CAPABILITIES("capabilities"), VALID_SOURCE_TYPES("valid_source_types"),
- // Requirements
- REQUIREMENTS("requirements"), NODE("node"), RELATIONSHIP("relationship"), CAPABILITY("capability"), INTERFACES("interfaces"),
- // Heat env Validation
- PARAMETERS("parameters"),
- // Import Validations
- TOSCA_VERSION("tosca_definitions_version"), TOPOLOGY_TEMPLATE("topology_template"), NODE_TYPES("node_types"), OCCURRENCES("occurrences"), NODE_TEMPLATES("node_templates"), GROUPS("groups"), INPUTS("inputs"),
- SUBSTITUTION_MAPPINGS("substitution_mappings"), NODE_TYPE("node_type"),
- // Attributes
- ATTRIBUTES("attributes"), LABEL("label"), HIDDEN("hidden"), IMMUTABLE("immutable"), GET_INPUT("get_input");
-
- private String elementName;
-
- private ToscaTagNamesEnum(String elementName) {
- this.elementName = elementName;
- }
-
- public String getElementName() {
- return elementName;
- }
- }
-
@SuppressWarnings("unchecked")
private static void handleElementNameNotFound(String elementName, Object elementValue, ToscaElementTypeEnum elementType, List<Object> returnedList) {
if (elementValue instanceof Map) {
@@ -190,7 +170,7 @@ public final class ImportUtils {
}
@SuppressWarnings("unchecked")
- private static void handleElementNameFound(String elementName, ToscaElementTypeEnum elementType, List<Object> returnedList, Object elementValue) {
+ private static void addFoundElementAccordingToItsType(String elementName, ToscaElementTypeEnum elementType, List<Object> returnedList, Object elementValue) {
if (elementValue instanceof Boolean) {
if (elementType == ToscaElementTypeEnum.BOOLEAN || elementType == ToscaElementTypeEnum.ALL) {
@@ -216,10 +196,8 @@ public final class ImportUtils {
}
// For Integer, Double etc...
- else if (elementType == ToscaElementTypeEnum.ALL) {
- if (elementValue != null) {
- returnedList.add(String.valueOf(elementValue));
- }
+ else if (elementType == ToscaElementTypeEnum.ALL && elementValue != null) {
+ returnedList.add(String.valueOf(elementValue));
}
}
@@ -232,15 +210,13 @@ public final class ImportUtils {
}
- public static Either<Object, ResultStatusEnum> findToscaElement(Map<String, Object> toscaJson, ToscaTagNamesEnum elementName, ToscaElementTypeEnum elementType) {
+ public static Either<Object, ResultStatusEnum> findToscaElement(Map<String, Object> toscaJson, TypeUtils.ToscaTagNamesEnum elementName, ToscaElementTypeEnum elementType) {
List<Object> foundElements = new ArrayList<>();
- Either<Object, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
ImportUtils.findToscaElements(toscaJson, elementName.getElementName(), elementType, foundElements);
- if (foundElements.size() > 0) {
- returnedElement = Either.left(foundElements.get(0));
+ if (!isEmpty(foundElements)) {
+ return Either.left(foundElements.get(0));
}
- return returnedElement;
-
+ return Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
}
/**
@@ -250,16 +226,13 @@ public final class ImportUtils {
* Or ELEMENT_NOT_FOUND ActionStatus
*
* @param toscaJson
- * @param toscaTagName
* @return
*/
public static Either<List<Object>, ResultStatusEnum> findToscaElements(Map<String, Object> toscaJson, String elementName, ToscaElementTypeEnum elementType, List<Object> returnedList) {
Either<List<Object>, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
String skipKey = null;
if (toscaJson.containsKey(elementName)) {
- Object elementValue = toscaJson.get(elementName);
- handleElementNameFound(elementName, elementType, returnedList, elementValue);
- skipKey = elementName;
+ skipKey = handleFoundElement(toscaJson, elementName, elementType, returnedList);
}
Iterator<Entry<String, Object>> keyValItr = toscaJson.entrySet().iterator();
@@ -270,15 +243,22 @@ public final class ImportUtils {
}
}
- if (returnedList.size() > 0) {
+ if (!isEmpty(returnedList)) {
returnedElement = Either.left(returnedList);
}
return returnedElement;
}
+ private static String handleFoundElement(Map<String, Object> toscaJson, String elementName, ToscaElementTypeEnum elementType, List<Object> returnedList) {
+ Object elementValue = toscaJson.get(elementName);
+ addFoundElementAccordingToItsType(elementName, elementType, returnedList, elementValue);
+ return elementName;
+
+ }
+
@SuppressWarnings("unchecked")
- public static <T> Either<List<T>, ResultStatusEnum> findFirstToscaListElement(Map<String, Object> toscaJson, ToscaTagNamesEnum toscaTagName) {
+ public static <T> Either<List<T>, ResultStatusEnum> findFirstToscaListElement(Map<String, Object> toscaJson, TypeUtils.ToscaTagNamesEnum toscaTagName) {
Either<List<T>, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
Either<Object, ResultStatusEnum> findFirstToscaElement = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.LIST);
if (findFirstToscaElement.isLeft()) {
@@ -289,7 +269,7 @@ public final class ImportUtils {
}
@SuppressWarnings("unchecked")
- public static <T> Either<Map<String, T>, ResultStatusEnum> findFirstToscaMapElement(Map<String, Object> toscaJson, ToscaTagNamesEnum toscaTagName) {
+ public static <T> Either<Map<String, T>, ResultStatusEnum> findFirstToscaMapElement(Map<String, Object> toscaJson, TypeUtils.ToscaTagNamesEnum toscaTagName) {
Either<Map<String, T>, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
Either<Object, ResultStatusEnum> findFirstToscaElement = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.MAP);
if (findFirstToscaElement.isLeft()) {
@@ -299,7 +279,7 @@ public final class ImportUtils {
}
- public static Either<String, ResultStatusEnum> findFirstToscaStringElement(Map<String, Object> toscaJson, ToscaTagNamesEnum toscaTagName) {
+ public static Either<String, ResultStatusEnum> findFirstToscaStringElement(Map<String, Object> toscaJson, TypeUtils.ToscaTagNamesEnum toscaTagName) {
Either<String, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
Either<Object, ResultStatusEnum> findFirstToscaElements = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.STRING);
if (findFirstToscaElements.isLeft()) {
@@ -315,7 +295,7 @@ public final class ImportUtils {
* @param toscaTagName
* @return
*/
- public static Either<String, ResultStatusEnum> findFirstToscaBooleanElement(Map<String, Object> toscaJson, ToscaTagNamesEnum toscaTagName) {
+ public static Either<String, ResultStatusEnum> findFirstToscaBooleanElement(Map<String, Object> toscaJson, TypeUtils.ToscaTagNamesEnum toscaTagName) {
Either<String, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
Either<Object, ResultStatusEnum> findFirstToscaElements = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.BOOLEAN);
if (findFirstToscaElements.isLeft()) {
@@ -325,7 +305,7 @@ public final class ImportUtils {
}
private static void setPropertyConstraints(Map<String, Object> propertyValue, PropertyDefinition property) {
- Either<List<Object>, ResultStatusEnum> propertyFieldconstraints = findFirstToscaListElement(propertyValue, ToscaTagNamesEnum.CONSTRAINTS);
+ Either<List<Object>, ResultStatusEnum> propertyFieldconstraints = findFirstToscaListElement(propertyValue, TypeUtils.ToscaTagNamesEnum.CONSTRAINTS);
if (propertyFieldconstraints.isLeft()) {
List<Object> jsonConstraintList = propertyFieldconstraints.left().value();
@@ -345,78 +325,129 @@ public final class ImportUtils {
public static PropertyDefinition createModuleProperty(Map<String, Object> propertyValue) {
PropertyDefinition propertyDef = new PropertyDefinition();
- ImportUtils.setField(propertyValue, ToscaTagNamesEnum.TYPE, type -> propertyDef.setType(type));
- ImportUtils.setPropertyFieldRequired(propertyValue, propertyDef);
- ImportUtils.setField(propertyValue, ToscaTagNamesEnum.DESCRIPTION, desc -> propertyDef.setDescription(desc));
+ setField(propertyValue, TypeUtils.ToscaTagNamesEnum.TYPE, propertyDef::setType);
+ setPropertyFieldRequired(propertyValue, propertyDef);
+ setField(propertyValue, TypeUtils.ToscaTagNamesEnum.DESCRIPTION, propertyDef::setDescription);
- Either<Object, ResultStatusEnum> findToscaElement = ImportUtils.findToscaElement(propertyValue, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL);
- if (findToscaElement.isLeft()) {
- String propertyJsonStringValue = getPropertyJsonStringValue(findToscaElement.left().value(), propertyDef.getType());
- propertyDef.setDefaultValue(propertyJsonStringValue);
- }
- ImportUtils.setField(propertyValue, ToscaTagNamesEnum.IS_PASSWORD, pass -> propertyDef.setPassword(Boolean.parseBoolean(pass)));
- ImportUtils.setField(propertyValue, ToscaTagNamesEnum.STATUS, status -> propertyDef.setStatus(status));
- ImportUtils.setPropertyScheme(propertyValue, propertyDef);
- ImportUtils.setPropertyConstraints(propertyValue, propertyDef);
+ setJsonStringField(propertyValue, TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE, propertyDef.getType(), propertyDef::setDefaultValue);
+ setJsonStringField(propertyValue, TypeUtils.ToscaTagNamesEnum.VALUE, propertyDef.getType(), propertyDef::setValue);
+
+ setField(propertyValue, TypeUtils.ToscaTagNamesEnum.IS_PASSWORD, pass -> propertyDef.setPassword(Boolean.parseBoolean(pass)));
+ setField(propertyValue, TypeUtils.ToscaTagNamesEnum.STATUS, propertyDef::setStatus);
+ setScheme(propertyValue, propertyDef);
+ setPropertyConstraints(propertyValue, propertyDef);
return propertyDef;
}
- public static InputDefinition createModuleInput(Map<String, Object> inputValue) {
+
+ private static void setJsonStringField(Map<String, Object> propertyValue, ToscaTagNamesEnum elementName, String type, Consumer<String> setter) {
+ Either<Object, ResultStatusEnum> eitherValue = ImportUtils.findToscaElement(propertyValue, elementName, ToscaElementTypeEnum.ALL);
+ if (eitherValue.isLeft()) {
+ String propertyJsonStringValue = getPropertyJsonStringValue(eitherValue.left().value(), type);
+ setter.accept(propertyJsonStringValue);
+ }
+ }
+
+
+
+ public static Annotation createModuleAnnotation(Map<String, Object> annotationMap, AnnotationTypeOperations annotationTypeOperations) {
+ String parsedAnnotationType = findFirstToscaStringElement(annotationMap, TypeUtils.ToscaTagNamesEnum.TYPE).left().value();
+ AnnotationTypeDefinition annotationTypeObject = annotationTypeOperations.getLatestType(parsedAnnotationType);
+ if (annotationTypeObject != null) {
+ Annotation annotation = new Annotation();
+ ImportUtils.setField(annotationMap, TypeUtils.ToscaTagNamesEnum.TYPE, annotation::setType);
+ ImportUtils.setField(annotationMap, TypeUtils.ToscaTagNamesEnum.DESCRIPTION, annotation::setDescription);
+ Either<Map<String, PropertyDefinition>, ResultStatusEnum> properties = getProperties(annotationMap);
+ modifyPropertiesKeysToProperForm(properties, annotation);
+ return annotation;
+ }
+ return null;
+ }
+
+ private static Either<Boolean, ResponseFormat> modifyPropertiesKeysToProperForm(Either<Map<String, PropertyDefinition>, ResultStatusEnum> properties, Annotation annotation) {
+ Either<Boolean, ResponseFormat> result = Either.left(true);
+ if (properties.isLeft()) {
+ List<PropertyDataDefinition> 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, annotation.getName());
+ result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromResultStatusEnum(ResultStatusEnum.INVALID_PROPERTY_NAME, JsonPresentationFields.PROPERTY)));
+ }
+ PropertyDefinition propertyDefinition = entry.getValue();
+ propertyDefinition.setValue(propertyDefinition.getName());
+ propertyDefinition.setName(name);
+ propertiesList.add(propertyDefinition);
+ }
+ }
+ annotation.setProperties(propertiesList);
+ }
+ else if (properties.right().value() != ResultStatusEnum.ELEMENT_NOT_FOUND) {
+ result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromResultStatusEnum(properties
+ .right()
+ .value(), JsonPresentationFields.PROPERTY)));
+ }
+ return result;
+ }
+
+ public static InputDefinition createModuleInput(Map<String, Object> inputValue, AnnotationTypeOperations annotationTypeOperations) {
InputDefinition inputDef = new InputDefinition();
- ImportUtils.setField(inputValue, ToscaTagNamesEnum.TYPE, type -> inputDef.setType(type));
- ImportUtils.setField(inputValue, ToscaTagNamesEnum.REQUIRED, req -> inputDef.setRequired(Boolean.parseBoolean(req)));
- ImportUtils.setField(inputValue, ToscaTagNamesEnum.DESCRIPTION, desc -> inputDef.setDescription(desc));
-
- Either<Object, ResultStatusEnum> findToscaElement = ImportUtils.findToscaElement(inputValue, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL);
- if (findToscaElement.isLeft()) {
- String propertyJsonStringValue = getPropertyJsonStringValue(findToscaElement.left().value(), inputDef.getType());
- inputDef.setDefaultValue(propertyJsonStringValue);
- }
- ImportUtils.setField(inputValue, ToscaTagNamesEnum.IS_PASSWORD, pass -> inputDef.setPassword(Boolean.parseBoolean(pass)));
- ImportUtils.setField(inputValue, ToscaTagNamesEnum.STATUS, status -> inputDef.setStatus(status));
- ImportUtils.setField(inputValue, ToscaTagNamesEnum.LABEL, label -> inputDef.setLabel(label));
- ImportUtils.setField(inputValue, ToscaTagNamesEnum.HIDDEN, hidden -> inputDef.setHidden(Boolean.parseBoolean(hidden)));
- ImportUtils.setField(inputValue, ToscaTagNamesEnum.HIDDEN, immutable -> inputDef.setImmutable(Boolean.parseBoolean(immutable)));
- ImportUtils.setField(inputValue, ToscaTagNamesEnum.LABEL, label -> inputDef.setLabel(label));
- ImportUtils.setPropertyScheme(inputValue, inputDef);
+ ImportUtils.setField(inputValue, TypeUtils.ToscaTagNamesEnum.TYPE, inputDef::setType);
+ ImportUtils.setField(inputValue, TypeUtils.ToscaTagNamesEnum.REQUIRED, req -> inputDef.setRequired(Boolean.parseBoolean(req)));
+ ImportUtils.setField(inputValue, TypeUtils.ToscaTagNamesEnum.DESCRIPTION, inputDef::setDescription);
+
+ setJsonStringField(inputValue, TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE, inputDef.getType(), inputDef::setDefaultValue);
+
+ ImportUtils.setField(inputValue, TypeUtils.ToscaTagNamesEnum.IS_PASSWORD, pass -> inputDef.setPassword(Boolean.parseBoolean(pass)));
+ ImportUtils.setField(inputValue, TypeUtils.ToscaTagNamesEnum.STATUS, inputDef::setStatus);
+ ImportUtils.setField(inputValue, TypeUtils.ToscaTagNamesEnum.LABEL, inputDef::setLabel);
+ ImportUtils.setField(inputValue, TypeUtils.ToscaTagNamesEnum.HIDDEN, hidden -> inputDef.setHidden(Boolean.parseBoolean(hidden)));
+ ImportUtils.setField(inputValue, TypeUtils.ToscaTagNamesEnum.HIDDEN, immutable -> inputDef.setImmutable(Boolean.parseBoolean(immutable)));
+ ImportUtils.setField(inputValue, TypeUtils.ToscaTagNamesEnum.LABEL, inputDef::setLabel);
+
+ ImportUtils.setScheme(inputValue, inputDef);
ImportUtils.setPropertyConstraints(inputValue, inputDef);
+ return parseAnnotationsAndAddItToInput(inputDef, inputValue, annotationTypeOperations);
+
+ }
+
+
+ public static InputDefinition parseAnnotationsAndAddItToInput(InputDefinition inputDef, Map<String, Object> inputValue, AnnotationTypeOperations annotationTypeOperations){
+ Function<String, Annotation> elementGenByName = ImportUtils::createAnnotation;
+ Function<Map<String, Object>, Annotation> func = annotation -> createModuleAnnotation(annotation, annotationTypeOperations);
+ return getElements(inputValue, TypeUtils.ToscaTagNamesEnum.ANNOTATIONS, elementGenByName, func).
+ left().map( annotations -> modifyInputWithAnnotations(inputDef, annotations)).
+ left().on(err -> { log.error("Parsing annotations or adding them to the PropertyDataDefinition object failed");
+ return inputDef;});
+ }
+
+ private static InputDefinition modifyInputWithAnnotations(InputDefinition inputDef, Map<String, Annotation> annotationsMap) {
+ setAnnotationsName(annotationsMap);
+ inputDef.setAnnotationsToInput(annotationsMap.values());
return inputDef;
}
+
public static PropertyDefinition createModuleAttribute(Map<String, Object> attributeMap) {
PropertyDefinition attributeDef = new PropertyDefinition();
- ImportUtils.setField(attributeMap, ToscaTagNamesEnum.TYPE, type -> attributeDef.setType(type));
- ImportUtils.setField(attributeMap, ToscaTagNamesEnum.DESCRIPTION, desc -> attributeDef.setDescription(desc));
- ImportUtils.setField(attributeMap, ToscaTagNamesEnum.STATUS, status -> attributeDef.setStatus(status));
- Either<Object, ResultStatusEnum> eitherDefaultValue = ImportUtils.findToscaElement(attributeMap, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL);
- if (eitherDefaultValue.isLeft()) {
- String attributeDefaultValue = getPropertyJsonStringValue(eitherDefaultValue.left().value(), attributeDef.getType());
- attributeDef.setDefaultValue(attributeDefaultValue);
- }
- Either<Object, ResultStatusEnum> eitherValue = ImportUtils.findToscaElement(attributeMap, ToscaTagNamesEnum.VALUE, ToscaElementTypeEnum.ALL);
- if (eitherValue.isLeft()) {
- String attributeValue = getPropertyJsonStringValue(eitherValue.left().value(), attributeDef.getType());
- attributeDef.setValue(attributeValue);
- }
- ImportUtils.setAttributeScheme(attributeMap, attributeDef);
- return attributeDef;
- }
+ setField(attributeMap, TypeUtils.ToscaTagNamesEnum.TYPE, attributeDef::setType);
+ setField(attributeMap, TypeUtils.ToscaTagNamesEnum.DESCRIPTION, attributeDef::setDescription);
+ setField(attributeMap, TypeUtils.ToscaTagNamesEnum.STATUS, attributeDef::setStatus);
- private static void setPropertyScheme(Map<String, Object> propertyValue, PropertyDefinition propertyDefinition) {
- Either<SchemaDefinition, ResultStatusEnum> eitherSchema = getSchema(propertyValue);
- if (eitherSchema.isLeft()) {
- SchemaDefinition schemaDef = new SchemaDefinition();
- schemaDef.setProperty(eitherSchema.left().value().getProperty());
- propertyDefinition.setSchema(schemaDef);
- }
+ setJsonStringField(attributeMap, TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE, attributeDef.getType(), attributeDef::setDefaultValue);
+ setJsonStringField(attributeMap, TypeUtils.ToscaTagNamesEnum.VALUE, attributeDef.getType(), attributeDef::setValue);
+ setScheme(attributeMap, attributeDef);
+ return attributeDef;
}
- private static void setAttributeScheme(Map<String, Object> propertyValue, PropertyDefinition propertyDefinition) {
+ private static void setScheme(Map<String, Object> propertyValue, PropertyDefinition propertyDefinition) {
Either<SchemaDefinition, ResultStatusEnum> eitherSchema = getSchema(propertyValue);
if (eitherSchema.isLeft()) {
SchemaDefinition schemaDef = new SchemaDefinition();
@@ -428,7 +459,7 @@ public final class ImportUtils {
private static Either<SchemaDefinition, ResultStatusEnum> getSchema(Map<String, Object> propertyValue) {
Either<SchemaDefinition, ResultStatusEnum> result = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
- Either<Object, ResultStatusEnum> propertyFieldEntryScheme = findToscaElement(propertyValue, ToscaTagNamesEnum.ENTRY_SCHEMA, ToscaElementTypeEnum.ALL);
+ Either<Object, ResultStatusEnum> propertyFieldEntryScheme = findToscaElement(propertyValue, TypeUtils.ToscaTagNamesEnum.ENTRY_SCHEMA, ToscaElementTypeEnum.ALL);
if (propertyFieldEntryScheme.isLeft()) {
if (propertyFieldEntryScheme.left().value() instanceof String) {
String schemaType = (String) propertyFieldEntryScheme.left().value();
@@ -443,14 +474,12 @@ public final class ImportUtils {
SchemaDefinition schema = new SchemaDefinition();
schema.setProperty(schemeProperty);
result = Either.left(schema);
-
}
-
}
return result;
}
- public static void setField(Map<String, Object> toscaJson, ToscaTagNamesEnum tagName, Consumer<String> setter) {
+ public static void setField(Map<String, Object> toscaJson, TypeUtils.ToscaTagNamesEnum tagName, Consumer<String> setter) {
Either<String, ResultStatusEnum> fieldStringValue = findFirstToscaStringElement(toscaJson, tagName);
if (fieldStringValue.isLeft()) {
setter.accept(fieldStringValue.left().value());
@@ -459,58 +488,57 @@ public final class ImportUtils {
}
private static void setPropertyFieldRequired(Map<String, Object> propertyValue, PropertyDefinition dataDefinition) {
- Either<String, ResultStatusEnum> propertyFieldRequired = findFirstToscaBooleanElement(propertyValue, ToscaTagNamesEnum.REQUIRED);
+ Either<String, ResultStatusEnum> propertyFieldRequired = findFirstToscaBooleanElement(propertyValue, TypeUtils.ToscaTagNamesEnum.REQUIRED);
if (propertyFieldRequired.isLeft()) {
dataDefinition.setRequired(Boolean.parseBoolean(propertyFieldRequired.left().value()));
}
}
public static Either<Map<String, PropertyDefinition>, ResultStatusEnum> getProperties(Map<String, Object> toscaJson) {
- Function<String, PropertyDefinition> elementGenByName = elementName -> createProperties(elementName);
- Function<Map<String, Object>, PropertyDefinition> func = map -> createModuleProperty(map);
+ Function<String, PropertyDefinition> elementGenByName = ImportUtils::createProperties;
+ Function<Map<String, Object>, PropertyDefinition> func = ImportUtils::createModuleProperty;
- return getElements(toscaJson, ToscaTagNamesEnum.PROPERTIES, elementGenByName, func);
+ return getElements(toscaJson, TypeUtils.ToscaTagNamesEnum.PROPERTIES, elementGenByName, func);
}
- public static Either<Map<String, InputDefinition>, ResultStatusEnum> getInputs(Map<String, Object> toscaJson) {
- Function<String, InputDefinition> elementGenByName = elementName -> createInputs(elementName);
- Function<Map<String, Object>, InputDefinition> func = map -> createModuleInput(map);
+ public static Either<Map<String, InputDefinition>, ResultStatusEnum> getInputs(Map<String, Object> toscaJson, AnnotationTypeOperations annotationTypeOperations) {
+ Function<String, InputDefinition> elementGenByName = ImportUtils::createInputs;
+ Function<Map<String, Object>, InputDefinition> func = object -> createModuleInput(object, annotationTypeOperations);
- return getElements(toscaJson, ToscaTagNamesEnum.INPUTS, elementGenByName, func);
+ return getElements(toscaJson, TypeUtils.ToscaTagNamesEnum.INPUTS, elementGenByName, func);
}
public static Either<Map<String, PropertyDefinition>, ResultStatusEnum> getAttributes(Map<String, Object> toscaJson) {
- Function<String, PropertyDefinition> elementGenByName = elementName -> createAttribute(elementName);
- Function<Map<String, Object>, PropertyDefinition> func = map -> createModuleAttribute(map);
+ Function<String, PropertyDefinition> elementGenByName = ImportUtils::createAttribute;
+ Function<Map<String, Object>, PropertyDefinition> func = ImportUtils::createModuleAttribute;
- return getElements(toscaJson, ToscaTagNamesEnum.ATTRIBUTES, elementGenByName, func);
+ return getElements(toscaJson, TypeUtils.ToscaTagNamesEnum.ATTRIBUTES, elementGenByName, func);
}
- public static <ElementDefinition> Either<Map<String, ElementDefinition>, ResultStatusEnum> getElements(Map<String, Object> toscaJson, ToscaTagNamesEnum elementTagName, Function<String, ElementDefinition> elementGenByName,
- Function<Map<String, Object>, ElementDefinition> func) {
- Either<Map<String, ElementDefinition>, ResultStatusEnum> eitherResult = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
+ public static <T> Either<Map<String, T>, ResultStatusEnum> getElements(Map<String, Object> toscaJson, TypeUtils.ToscaTagNamesEnum elementTagName, Function<String, T> elementGenByName,
+ Function<Map<String, Object>, T> func) {
+ Either<Map<String, T>, ResultStatusEnum> eitherResult = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
Either<Map<String, Object>, ResultStatusEnum> toscaAttributes = findFirstToscaMapElement(toscaJson, elementTagName);
if (toscaAttributes.isLeft()) {
Map<String, Object> jsonAttributes = toscaAttributes.left().value();
- Map<String, ElementDefinition> moduleAttributes = new HashMap<>();
+ Map<String, T> moduleAttributes = new HashMap<>();
Iterator<Entry<String, Object>> propertiesNameValue = jsonAttributes.entrySet().iterator();
while (propertiesNameValue.hasNext()) {
Entry<String, Object> attributeNameValue = propertiesNameValue.next();
if (attributeNameValue.getValue() instanceof Map) {
@SuppressWarnings("unchecked")
- ElementDefinition attribute = func.apply((Map<String, Object>) attributeNameValue.getValue());
- moduleAttributes.put(String.valueOf(attributeNameValue.getKey()), attribute);
- } else {
-
- ElementDefinition element = elementGenByName.apply(String.valueOf(attributeNameValue.getValue()));
-
+ T attribute = func.apply((Map<String, Object>) attributeNameValue.getValue());
+ if (attribute != null){
+ moduleAttributes.put(String.valueOf(attributeNameValue.getKey()), attribute);
+ }
+ }
+ else {
+ T element = elementGenByName.apply(String.valueOf(attributeNameValue.getValue()));
moduleAttributes.put(String.valueOf(attributeNameValue.getKey()), element);
}
-
}
-
if (moduleAttributes.size() > 0) {
eitherResult = Either.left(moduleAttributes);
}
@@ -534,6 +562,8 @@ public final class ImportUtils {
return property;
}
+
+
private static InputDefinition createInputs(String name) {
InputDefinition input = new InputDefinition();
@@ -541,10 +571,18 @@ public final class ImportUtils {
return input;
}
+ private static Annotation createAnnotation(String name) {
+ Annotation annotation = new Annotation();
+ annotation.setName(name);
+ return annotation;
+ }
+
+
+
public static Either<List<HeatParameterDefinition>, ResultStatusEnum> getHeatParameters(Map<String, Object> heatData, String artifactType) {
Either<List<HeatParameterDefinition>, ResultStatusEnum> eitherResult = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
- Either<Map<String, Object>, ResultStatusEnum> toscaProperties = findFirstToscaMapElement(heatData, ToscaTagNamesEnum.PARAMETERS);
+ Either<Map<String, Object>, ResultStatusEnum> toscaProperties = findFirstToscaMapElement(heatData, TypeUtils.ToscaTagNamesEnum.PARAMETERS);
if (toscaProperties.isLeft()) {
Map<String, Object> jsonProperties = toscaProperties.left().value();
List<HeatParameterDefinition> moduleProperties = new ArrayList<>();
@@ -570,7 +608,7 @@ public final class ImportUtils {
}
- if (moduleProperties.size() > 0) {
+ if (!isEmpty(moduleProperties)) {
eitherResult = Either.left(moduleProperties);
}
@@ -583,7 +621,7 @@ public final class ImportUtils {
HeatParameterDefinition property = new HeatParameterDefinition();
Object value = propertyNameValue.getValue();
if (value != null) {
- property.setDefaultValue(isJson ? new Gson().toJson(value).toString() : StringEscapeUtils.escapeJava(String.valueOf(value)));
+ property.setDefaultValue(isJson ? new Gson().toJson(value) : StringEscapeUtils.escapeJava(String.valueOf(value)));
}
property.setName(String.valueOf(propertyNameValue.getKey()));
moduleProperties.add(property);
@@ -592,31 +630,35 @@ public final class ImportUtils {
private static Either<HeatParameterDefinition, ResultStatusEnum> createModuleHeatParameter(Map<String, Object> propertyValue) {
HeatParameterDefinition propertyDef = new HeatParameterDefinition();
String type;
- Either<String, ResultStatusEnum> propertyFieldType = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.TYPE);
+ Either<String, ResultStatusEnum> propertyFieldType = findFirstToscaStringElement(propertyValue, TypeUtils.ToscaTagNamesEnum.TYPE);
if (propertyFieldType.isLeft()) {
type = propertyFieldType.left().value();
propertyDef.setType(type);
} else {
return Either.right(ResultStatusEnum.INVALID_PROPERTY_TYPE);
}
- Either<String, ResultStatusEnum> propertyFieldDescription = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.DESCRIPTION);
+ Either<String, ResultStatusEnum> propertyFieldDescription = findFirstToscaStringElement(propertyValue, TypeUtils.ToscaTagNamesEnum.DESCRIPTION);
if (propertyFieldDescription.isLeft()) {
propertyDef.setDescription(propertyFieldDescription.left().value());
}
- Either<Object, ResultStatusEnum> propertyFieldDefaultVal = findToscaElement(propertyValue, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL);
+ Either<Object, ResultStatusEnum> propertyFieldDefaultVal = findToscaElement(propertyValue, TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL);
if (propertyFieldDefaultVal.isLeft()) {
if (propertyFieldDefaultVal.left().value() == null) {
return Either.right(ResultStatusEnum.INVALID_PROPERTY_VALUE);
}
Object value = propertyFieldDefaultVal.left().value();
- String defaultValue = type.equals(HeatParameterType.JSON.getType()) ? new Gson().toJson(value).toString() : StringEscapeUtils.escapeJava(String.valueOf(value));
+ String defaultValue = type.equals(HeatParameterType.JSON.getType()) ? new Gson().toJson(value) : StringEscapeUtils.escapeJava(String.valueOf(value));
propertyDef.setDefaultValue(defaultValue);
propertyDef.setCurrentValue(defaultValue);
}
return Either.left(propertyDef);
}
+ public static boolean containsGetInput(Object propValue) {
+ String value = getPropertyJsonStringValue(propValue, ToscaPropertyType.MAP.getType());
+ return value != null && value.contains(TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
+ }
public static String getPropertyJsonStringValue(Object value, String type) {
Gson gson = new Gson();
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java
index ca8b2e1fd9..8a111f359e 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java
@@ -20,16 +20,8 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.stream.Collectors;
-
-import javax.inject.Inject;
-
-import org.openecomp.sdc.be.components.property.PropertyDecelerationOrchestrator;
+import fj.data.Either;
+import org.openecomp.sdc.be.components.property.PropertyDeclarationOrchestrator;
import org.openecomp.sdc.be.components.validation.ComponentValidations;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
@@ -38,24 +30,18 @@ import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
-import org.openecomp.sdc.be.model.ComponentInstInputsMap;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.ComponentInstanceInput;
-import org.openecomp.sdc.be.model.ComponentInstanceProperty;
-import org.openecomp.sdc.be.model.ComponentParametersView;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.InputDefinition;
-import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter;
+import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
-import fj.data.Either;
+import javax.inject.Inject;
+import java.util.*;
+import java.util.stream.Collectors;
@Component("inputsBusinessLogic")
public class InputsBusinessLogic extends BaseBusinessLogic {
@@ -63,10 +49,15 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
private static final String CREATE_INPUT = "CreateInput";
private static final String UPDATE_INPUT = "UpdateInput";
- private static final Logger log = LoggerFactory.getLogger(InputsBusinessLogic.class);
+ private static final Logger log = Logger.getLogger(InputsBusinessLogic.class);
+ private static final String FAILED_TO_FOUND_COMPONENT_ERROR = "Failed to found component {}, error: {}";
+ private static final String GET_PROPERTIES_BY_INPUT = "get Properties by input";
+ private static final String FAILED_TO_FOUND_INPUT_UNDER_COMPONENT_ERROR = "Failed to found input {} under component {}, error: {}";
+ private static final String GOING_TO_EXECUTE_ROLLBACK_ON_CREATE_GROUP = "Going to execute rollback on create group.";
+ private static final String GOING_TO_EXECUTE_COMMIT_ON_CREATE_GROUP = "Going to execute commit on create group.";
@Inject
- private PropertyDecelerationOrchestrator propertyDecelerationOrchestrator;
+ private PropertyDeclarationOrchestrator propertyDeclarationOrchestrator;
@Inject
private ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
@@ -79,12 +70,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
*/
public Either<List<InputDefinition>, ResponseFormat> getInputs(String userId, String componentId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Inputs", false);
-
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
+ validateUserExists(userId, "get Inputs", false);
ComponentParametersView filters = new ComponentParametersView();
filters.disableAll();
@@ -93,7 +79,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters);
if(getComponentEither.isRight()){
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
- log.debug("Failed to found component {}, error: {}", componentId, actionStatus);
+ log.debug(FAILED_TO_FOUND_COMPONENT_ERROR, componentId, actionStatus);
return Either.right(componentsUtils.getResponseFormat(actionStatus));
}
@@ -106,13 +92,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
public Either<List<ComponentInstanceInput>, ResponseFormat> getComponentInstanceInputs(String userId, String componentId, String componentInstanceId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Inputs", false);
-
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
-
+ validateUserExists(userId, "get Inputs", false);
ComponentParametersView filters = new ComponentParametersView();
filters.disableAll();
filters.setIgnoreInputs(false);
@@ -122,7 +102,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters);
if(getComponentEither.isRight()){
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
- log.debug("Failed to found component {}, error: {}", componentId, actionStatus);
+ log.debug(FAILED_TO_FOUND_COMPONENT_ERROR, componentId, actionStatus);
return Either.right(componentsUtils.getResponseFormat(actionStatus));
}
@@ -147,10 +127,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
*/
public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesByInputId(String userId, String componentId, String instanceId, String inputId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Properties by input", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, GET_PROPERTIES_BY_INPUT, false);
String parentId = componentId;
org.openecomp.sdc.be.model.Component component = null;
ComponentParametersView filters = new ComponentParametersView();
@@ -164,7 +141,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
if(getComponentEither.isRight()){
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
- log.debug("Failed to found component {}, error: {}", parentId, actionStatus);
+ log.debug(FAILED_TO_FOUND_COMPONENT_ERROR, parentId, actionStatus);
return Either.right(componentsUtils.getResponseFormat(actionStatus));
}
@@ -186,7 +163,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
if(getComponentEither.isRight()){
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
- log.debug("Failed to found component {}, error: {}", parentId, actionStatus);
+ log.debug(FAILED_TO_FOUND_COMPONENT_ERROR, parentId, actionStatus);
return Either.right(componentsUtils.getResponseFormat(actionStatus));
}
@@ -195,7 +172,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst();
if(!op.isPresent()){
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
- log.debug("Failed to found input {} under component {}, error: {}", inputId, parentId, actionStatus);
+ log.debug(FAILED_TO_FOUND_INPUT_UNDER_COMPONENT_ERROR, inputId, parentId, actionStatus);
return Either.right(componentsUtils.getResponseFormat(actionStatus));
}
@@ -242,8 +219,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
}
private InputDefinition getInputFromInputsListById(List<InputDefinition> componentsOldInputs, InputDefinition input) {
- Optional<InputDefinition> foundInput = componentsOldInputs.stream().filter(in -> in.getUniqueId().equals(input.getUniqueId())).findFirst();
- return foundInput.isPresent() ? foundInput.get() : null;
+ return componentsOldInputs.stream().filter(in -> in.getUniqueId().equals(input.getUniqueId())).findFirst().orElse(null);
}
public Either<List<InputDefinition>, ResponseFormat> updateInputsValue(ComponentTypeEnum componentType, String componentId, List<InputDefinition> inputs, String userId, boolean shouldLockComp, boolean inTransaction) {
@@ -253,12 +229,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
org.openecomp.sdc.be.model.Component component = null;
try {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get input", false);
-
- if (resp.isRight()) {
- result = Either.right(resp.right().value());
- return result;
- }
+ validateUserExists(userId, "get input", false);
ComponentParametersView componentParametersView = new ComponentParametersView();
componentParametersView.disableAll();
@@ -299,7 +270,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
InputDefinition currInput = getInputFromInputsListById(componentsOldInputs, newInput);
if (currInput == null) {
ActionStatus actionStatus = ActionStatus.COMPONENT_NOT_FOUND;
- log.debug("Failed to found newInput {} under component {}, error: {}", newInput.getUniqueId(), componentId, actionStatus.name());
+ log.debug("Failed to found newInput {} under component {}, error: {}", newInput.getUniqueId(), componentId, actionStatus);
result = Either.right(componentsUtils.getResponseFormat(actionStatus));
return result;
}
@@ -322,12 +293,12 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
result = Either.left(returnInputs);
return result;
} finally {
- if (false == inTransaction) {
+ if (!inTransaction) {
if (result == null || result.isRight()) {
- log.debug("Going to execute rollback on create group.");
+ log.debug(GOING_TO_EXECUTE_ROLLBACK_ON_CREATE_GROUP);
titanDao.rollback();
} else {
- log.debug("Going to execute commit on create group.");
+ log.debug(GOING_TO_EXECUTE_COMMIT_ON_CREATE_GROUP);
titanDao.commit();
}
}
@@ -339,11 +310,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
}
public Either<List<ComponentInstanceInput>, ResponseFormat> getInputsForComponentInput(String userId, String componentId, String inputId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Properties by input", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
- String parentId = componentId;
+ validateUserExists(userId, GET_PROPERTIES_BY_INPUT, false);
org.openecomp.sdc.be.model.Component component = null;
ComponentParametersView filters = new ComponentParametersView();
filters.disableAll();
@@ -352,11 +319,11 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
filters.setIgnoreComponentInstancesInputs(false);
filters.setIgnoreProperties(false);
- Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(parentId, filters);
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters);
if(getComponentEither.isRight()){
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
- log.debug("Failed to found component {}, error: {}", parentId, actionStatus);
+ log.debug(FAILED_TO_FOUND_COMPONENT_ERROR, componentId, actionStatus);
return Either.right(componentsUtils.getResponseFormat(actionStatus));
}
@@ -365,7 +332,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst();
if(!op.isPresent()){
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
- log.debug("Failed to found input {} under component {}, error: {}", inputId, parentId, actionStatus);
+ log.debug(FAILED_TO_FOUND_INPUT_UNDER_COMPONENT_ERROR, inputId, componentId, actionStatus);
return Either.right(componentsUtils.getResponseFormat(actionStatus));
}
@@ -379,12 +346,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
org.openecomp.sdc.be.model.Component component = null;
try {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Properties by input", false);
-
- if (resp.isRight()) {
- result = Either.right(resp.right().value());
- return result;
- }
+ validateUserExists(userId, GET_PROPERTIES_BY_INPUT, false);
ComponentParametersView componentParametersView = new ComponentParametersView();
componentParametersView.disableAll();
@@ -392,6 +354,8 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
componentParametersView.setIgnoreComponentInstancesInputs(false);
componentParametersView.setIgnoreComponentInstances(false);
componentParametersView.setIgnoreComponentInstancesProperties(false);
+ componentParametersView.setIgnorePolicies(false);
+ componentParametersView.setIgnoreGroups(false);
componentParametersView.setIgnoreUsers(false);
Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, componentParametersView);
@@ -416,7 +380,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
return result;
}
- result = propertyDecelerationOrchestrator.declarePropertiesToInputs(component, componentInstInputsMapUi)
+ result = propertyDeclarationOrchestrator.declarePropertiesToInputs(component, componentInstInputsMapUi)
.left()
.bind(inputsToCreate -> prepareInputsForCreation(userId, componentId, inputsToCreate))
.right()
@@ -428,10 +392,10 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
if (!inTransaction) {
if (result == null || result.isRight()) {
- log.debug("Going to execute rollback on create group.");
+ log.debug(GOING_TO_EXECUTE_ROLLBACK_ON_CREATE_GROUP);
titanDao.rollback();
} else {
- log.debug("Going to execute commit on create group.");
+ log.debug(GOING_TO_EXECUTE_COMMIT_ON_CREATE_GROUP);
titanDao.commit();
}
}
@@ -457,10 +421,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
public Either<List<InputDefinition>, ResponseFormat> createInputsInGraph(Map<String, InputDefinition> inputs, org.openecomp.sdc.be.model.Component component) {
- List<InputDefinition> resList = inputs.values().stream().collect(Collectors.toList());
- Either<List<InputDefinition>, ResponseFormat> result = Either.left(resList);
List<InputDefinition> resourceProperties = component.getInputs();
-
Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache);
if (allDataTypes.isRight()) {
return Either.right(allDataTypes.right().value());
@@ -479,7 +440,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
}
if (resourceProperties != null) {
- Map<String, InputDefinition> generatedInputs = resourceProperties.stream().collect(Collectors.toMap(i -> i.getName(), i -> i));
+ Map<String, InputDefinition> generatedInputs = resourceProperties.stream().collect(Collectors.toMap(PropertyDataDefinition::getName, i -> i));
Either<Map<String, InputDefinition>, String> mergeEither = ToscaDataDefinition.mergeDataMaps(generatedInputs, inputs);
if(mergeEither.isRight()){
return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, mergeEither.right().value()));
@@ -487,14 +448,12 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
inputs = mergeEither.left().value();
}
- Either<List<InputDefinition>, StorageOperationStatus> assotiateInputsEither = toscaOperationFacade.createAndAssociateInputs(inputs, component.getUniqueId());
- if(assotiateInputsEither.isRight()){
- log.debug("Failed to create inputs under component {}. Status is {}", component.getUniqueId(), assotiateInputsEither.right().value());
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(assotiateInputsEither.right().value())));
+ Either<List<InputDefinition>, StorageOperationStatus> associateInputsEither = toscaOperationFacade.createAndAssociateInputs(inputs, component.getUniqueId());
+ if(associateInputsEither.isRight()){
+ log.debug("Failed to create inputs under component {}. Status is {}", component.getUniqueId(), associateInputsEither.right().value());
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(associateInputsEither.right().value())));
}
- result = Either.left(assotiateInputsEither.left().value());
-
- return result;
+ return Either.left(associateInputsEither.left().value());
}
/**
@@ -502,24 +461,17 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
*
* @param componentId
* @param userId
- *
* @param inputId
* @return
*/
public Either<InputDefinition, ResponseFormat> deleteInput(String componentId, String userId, String inputId) {
Either<InputDefinition, ResponseFormat> deleteEither = null;
- if (log.isDebugEnabled())
+ if (log.isDebugEnabled()) {
log.debug("Going to delete input id: {}", inputId);
-
- // Validate user (exists)
- Either<User, ResponseFormat> userEither = validateUserExists(userId, "Delete input", true);
- if (userEither.isRight()) {
- deleteEither = Either.right(userEither.right().value());
- return deleteEither;
}
- // Get component using componentType, componentId
+ validateUserExists(userId, "Delete input", true);
ComponentParametersView componentParametersView = new ComponentParametersView();
componentParametersView.disableAll();
@@ -528,6 +480,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
componentParametersView.setIgnoreComponentInstancesInputs(false);
componentParametersView.setIgnoreComponentInstancesProperties(false);
componentParametersView.setIgnorePolicies(false);
+ componentParametersView.setIgnoreGroups(false);
componentParametersView.setIgnoreUsers(false);
Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentEither = toscaOperationFacade.getToscaElement(componentId, componentParametersView);
@@ -565,7 +518,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName()));
return deleteEither;
}
- StorageOperationStatus storageOperationStatus = propertyDecelerationOrchestrator.unDeclarePropertiesAsInputs(component, inputForDelete);
+ StorageOperationStatus storageOperationStatus = propertyDeclarationOrchestrator.unDeclarePropertiesAsInputs(component, inputForDelete);
if (storageOperationStatus != StorageOperationStatus.OK) {
log.debug("Component id: {} update properties declared as input for input id: {} failed", componentId, inputId);
deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName()));
@@ -599,20 +552,18 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
PropertyValueConverter converter = type.getConverter();
// get inner type
String innerType = null;
- if (newInputDefinition != null) {
- SchemaDefinition schema = newInputDefinition.getSchema();
- if (schema != null) {
- PropertyDataDefinition prop = schema.getProperty();
- if (prop != null) {
- innerType = prop.getType();
- }
- }
- String convertedValue = null;
- if (newInputDefinition.getDefaultValue() != null) {
- convertedValue = converter.convert(newInputDefinition.getDefaultValue(), innerType, dataTypes);
- newInputDefinition.setDefaultValue(convertedValue);
+ SchemaDefinition schema = newInputDefinition.getSchema();
+ if (schema != null) {
+ PropertyDataDefinition prop = schema.getProperty();
+ if (prop != null) {
+ innerType = prop.getType();
}
}
+ String convertedValue;
+ if (newInputDefinition.getDefaultValue() != null) {
+ convertedValue = converter.convert(newInputDefinition.getDefaultValue(), innerType, dataTypes);
+ newInputDefinition.setDefaultValue(convertedValue);
+ }
}
return Either.left(newInputDefinition);
}
@@ -621,10 +572,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
Either<InputDefinition, ResponseFormat> result = null;
try {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Properties by input", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, GET_PROPERTIES_BY_INPUT, false);
ComponentParametersView filters = new ComponentParametersView();
filters.disableAll();
filters.setIgnoreComponentInstances(false);
@@ -635,7 +583,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters);
if(getComponentEither.isRight()){
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
- log.debug("Failed to found component {}, error: {}", componentId, actionStatus);
+ log.debug(FAILED_TO_FOUND_COMPONENT_ERROR, componentId, actionStatus);
return Either.right(componentsUtils.getResponseFormat(actionStatus));
}
@@ -643,7 +591,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst();
if(!op.isPresent()){
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
- log.debug("Failed to found input {} under component {}, error: {}", inputId, componentId, actionStatus);
+ log.debug(FAILED_TO_FOUND_INPUT_UNDER_COMPONENT_ERROR, inputId, componentId, actionStatus);
return Either.right(componentsUtils.getResponseFormat(actionStatus));
}
@@ -665,13 +613,13 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
} finally {
- if (false == inTransaction) {
+ if (!inTransaction) {
if (result == null || result.isRight()) {
- log.debug("Going to execute rollback on create group.");
+ log.debug(GOING_TO_EXECUTE_ROLLBACK_ON_CREATE_GROUP);
titanDao.rollback();
} else {
- log.debug("Going to execute commit on create group.");
+ log.debug(GOING_TO_EXECUTE_COMMIT_ON_CREATE_GROUP);
titanDao.commit();
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java
index 6d23cac8db..7a1c96e1ef 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java
@@ -20,26 +20,19 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import javax.annotation.Resource;
-
+import fj.data.Either;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.InterfaceDefinition;
import org.openecomp.sdc.be.model.Operation;
import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
-import fj.data.Either;
+import javax.annotation.Resource;
+import java.util.*;
@Component("interfaceLifecycleTypeImportManager")
public class InterfaceLifecycleTypeImportManager {
@@ -52,7 +45,7 @@ public class InterfaceLifecycleTypeImportManager {
@Resource
private CommonImportManager commonImportManager;
- private static final Logger log = LoggerFactory.getLogger(InterfaceLifecycleTypeImportManager.class);
+ private static final Logger log = Logger.getLogger(InterfaceLifecycleTypeImportManager.class);
public Either<List<InterfaceDefinition>, ResponseFormat> createLifecycleTypes(String interfaceLifecycleTypesYml) {
@@ -67,7 +60,7 @@ public class InterfaceLifecycleTypeImportManager {
}
private Either<List<InterfaceDefinition>, ActionStatus> createLifecyclyTypeFromYml(String interfaceLifecycleTypesYml) {
- return commonImportManager.createElementTypesFromYml(interfaceLifecycleTypesYml, (lifecycleTypeName, lifecycleTypeJsonData) -> createLifecycleType(lifecycleTypeName, lifecycleTypeJsonData));
+ return commonImportManager.createElementTypesFromYml(interfaceLifecycleTypesYml, this::createLifecycleType);
}
@@ -104,7 +97,7 @@ public class InterfaceLifecycleTypeImportManager {
InterfaceDefinition interfaceDef = new InterfaceDefinition();
interfaceDef.setType(interfaceDefinition);
- Map<String, Operation> operations = new HashMap<String, Operation>();
+ Map<String, Operation> operations = new HashMap<>();
for (Map.Entry<String, Object> entry : toscaJson.entrySet()) {
Operation operation = new Operation();
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogic.java
index 85f8c57c9f..e61e925e97 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogic.java
@@ -17,15 +17,8 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.Set;
-import java.util.UUID;
-
+import com.google.common.collect.Sets;
+import fj.data.Either;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
@@ -37,13 +30,7 @@ import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.ComponentParametersView;
-import org.openecomp.sdc.be.model.InterfaceDefinition;
-import org.openecomp.sdc.be.model.Operation;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.jsontitan.operations.InterfaceOperation;
import org.openecomp.sdc.be.model.jsontitan.utils.InterfaceUtils;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
@@ -56,9 +43,7 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-import com.google.common.collect.Sets;
-
-import fj.data.Either;
+import java.util.*;
@Component("interfaceOperationBusinessLogic")
public class InterfaceOperationBusinessLogic extends ComponentBusinessLogic{
@@ -75,6 +60,9 @@ public class InterfaceOperationBusinessLogic extends ComponentBusinessLogic{
@Autowired
private ArtifactCassandraDao artifactCassandraDao;
+ @Autowired
+ private UiComponentDataConverter uiComponentDataConverter;
+
public void setInterfaceOperation(InterfaceOperation interfaceOperation) {
this.interfaceOperation = interfaceOperation;
}
@@ -95,9 +83,7 @@ public class InterfaceOperationBusinessLogic extends ComponentBusinessLogic{
public Either<Resource, ResponseFormat> deleteInterfaceOperation(String resourceId, Set<String> interfaceOperationToDelete, User user, boolean lock) {
Resource resourceToDelete = initResourceToDeleteWFOp(resourceId, interfaceOperationToDelete);
- Either<Resource, ResponseFormat> eitherDelete = validateUserAndRole(resourceToDelete, user, "deleteInterfaceOperation");
- if (eitherDelete != null)
- return eitherDelete;
+ validateUserAndRole(resourceToDelete, user, "deleteInterfaceOperation");
if (CollectionUtils.isEmpty(interfaceOperationToDelete)){
LOGGER.debug("Invalid parameter interfaceOperationToDelete was empty");
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY));
@@ -253,10 +239,8 @@ public class InterfaceOperationBusinessLogic extends ComponentBusinessLogic{
}
private Either<Resource, ResponseFormat> createOrUpdateInterfaceOperation(String resourceId, Resource resourceUpdate, User user, boolean isUpdate, String errorContext, boolean lock) {
- Either<Resource, ResponseFormat> eitherCreator = validateUserAndRole(resourceUpdate, user, errorContext);
- if (eitherCreator != null)
- return eitherCreator;
-
+ validateUserAndRole(resourceUpdate, user, errorContext);
+
Either<Resource, ResponseFormat> resourceEither = getResourceDetails(resourceId);
if (resourceEither.isRight()){
return resourceEither;
@@ -370,18 +354,9 @@ public class InterfaceOperationBusinessLogic extends ComponentBusinessLogic{
return resourceToDelete;
}
- private Either<Resource, ResponseFormat> validateUserAndRole(Resource resourceUpdate, User user, String errorContext) {
- Either<User, ResponseFormat> userEither = validateUser(user, errorContext, resourceUpdate, null, false);
- if (userEither.isRight()) {
- return Either.right(userEither.right().value());
- }
- user = userEither.left().value();
-
- Either<Boolean, ResponseFormat> userRoleEither = validateUserRole(user, resourceUpdate, new ArrayList<>(), null, null);
- if (userRoleEither.isRight()) {
- return Either.right(userRoleEither.right().value());
- }
- return null;
+ private void validateUserAndRole(Resource resourceUpdate, User user, String errorContext) {
+ user = validateUser(user, errorContext, resourceUpdate, null, false);
+ validateUserRole(user, resourceUpdate, new ArrayList<>(), null, null);
}
@@ -417,12 +392,6 @@ public class InterfaceOperationBusinessLogic extends ComponentBusinessLogic{
}
@Override
- public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId,
- ComponentTypeEnum componentTypeEnum, String userId, String searchText) {
- return null;
- }
-
- @Override
public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId,
List<String> dataParamsToReturn) {
ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
@@ -441,8 +410,16 @@ public class InterfaceOperationBusinessLogic extends ComponentBusinessLogic{
}
Resource resource = resourceResultEither.left().value();
- UiComponentDataTransfer dataTransfer = UiComponentDataConverter.getUiDataTransferFromResourceByParams(resource,
+ UiComponentDataTransfer dataTransfer = uiComponentDataConverter.getUiDataTransferFromResourceByParams(resource,
dataParamsToReturn);
return Either.left(dataTransfer);
}
+
+ @Override
+ public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(
+ String componentId, String userId) {
+ return null;
+ }
+
+
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/MonitoringBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/MonitoringBusinessLogic.java
index 31701c7916..b0bdf45c5a 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/MonitoringBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/MonitoringBusinessLogic.java
@@ -20,21 +20,19 @@
package org.openecomp.sdc.be.components.impl;
+import fj.data.Either;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.impl.MonitoringDao;
import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.monitoring.MonitoringEvent;
import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
-import fj.data.Either;
-
@Component("monitoringBusinessLogic")
public class MonitoringBusinessLogic {
- private static final Logger log = LoggerFactory.getLogger(MonitoringBusinessLogic.class);
+ private static final Logger log = Logger.getLogger(MonitoringBusinessLogic.class);
@javax.annotation.Resource
private MonitoringDao monitoringDao;
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OnDeleteEntityOperation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OnDeleteEntityOperation.java
new file mode 100644
index 0000000000..b4bbebb909
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OnDeleteEntityOperation.java
@@ -0,0 +1,16 @@
+package org.openecomp.sdc.be.components.impl;
+
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.model.Component;
+
+public interface OnDeleteEntityOperation {
+
+ /**
+ * side effect operation to be executed when a given entity is deleted
+ * @param container the container which holds the entity to be deleted
+ * @param deletedEntityId the id of the entity that was deleted
+ * @return the status of the on delete operation
+ */
+ ActionStatus onDelete(Component container, String deletedEntityId);
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java
index 37a853ccdd..6b37318171 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java
@@ -1,34 +1,27 @@
package org.openecomp.sdc.be.components.impl;
-import static java.util.stream.Collectors.toMap;
-import static org.openecomp.sdc.be.components.validation.PolicyUtils.getExcludedPolicyTypesByComponent;
-import static org.openecomp.sdc.be.components.validation.PolicyUtils.getNextPolicyCounter;
-import static org.openecomp.sdc.be.components.validation.PolicyUtils.validatePolicyFields;
-
-import java.util.List;
-import java.util.Map;
-import java.util.function.Function;
-
+import fj.data.Either;
import org.apache.commons.collections.CollectionUtils;
-import org.apache.commons.lang3.StringUtils;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.elements.PolicyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentParametersView;
-import org.openecomp.sdc.be.model.PolicyDefinition;
-import org.openecomp.sdc.be.model.PolicyTypeDefinition;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.common.datastructure.Wrapper;
+import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import fj.data.Either;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import static java.util.stream.Collectors.toMap;
+import static org.openecomp.sdc.be.components.validation.PolicyUtils.*;
/**
* Provides specified business logic to create, retrieve, update, delete a policy
@@ -37,7 +30,7 @@ import fj.data.Either;
public class PolicyBusinessLogic extends BaseBusinessLogic {
private static final String FAILED_TO_VALIDATE_COMPONENT = "#{} - failed to validate the component {} before policy processing. ";
- private static final Logger log = LoggerFactory.getLogger(PolicyBusinessLogic.class);
+ private static final Logger log = Logger.getLogger(PolicyBusinessLogic.class);
/**
* Adds the newly created policy of the specified type to the component
@@ -75,14 +68,14 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
/**
* Retrieves the policy of the component by UniqueId
*
- * @param componentType
- * @param componentId
- * @param policyId
- * @param userId
- * @return
+ * @param componentType the type of the component
+ * @param componentId the ID of the component
+ * @param policyId the ID of the policy
+ * @param userId the ID of the user
+ * @return either policy or error response
*/
public Either<PolicyDefinition, ResponseFormat> getPolicy(ComponentTypeEnum componentType, String componentId, String policyId, String userId) {
- Either<PolicyDefinition, ResponseFormat> result = null;
+ Either<PolicyDefinition, ResponseFormat> result;
log.trace("#getPolicy - starting to retrieve the policy {} of the component {}. ", policyId, componentId);
try {
result = validateContainerComponentAndUserBeforeReadOperation(componentType, componentId, userId)
@@ -100,7 +93,7 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
*
* @param componentType the type of the component
* @param componentId the id of the component which the policy resides under
- * @param policy
+ * @param policy the policy to update
* @param userId the user modifier id
* @param shouldLock the flag defining if the component should be locked
* @return a policy or an error in a response format
@@ -158,8 +151,6 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
Either<PolicyDefinition, ResponseFormat> result = null;
log.debug("updating the policy id {} targets with the components {}. ", policyId, componentId);
- Component component = null;
-
try {
//not right error response
result = validateAndLockComponentAndUserBeforeWriteOperation(componentTypeEnum, componentId, userId, true)
@@ -176,25 +167,41 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
}
private Either<PolicyDefinition, ResponseFormat> validateAndUpdatePolicyTargets(Component component, String policyId, Map<PolicyTargetType, List<String>> targets) {
- if (!validateTargetsExistAndTypesCorrect(component.getUniqueId(), targets)) {
- log.debug("Error finding all the targets: {} .", targets);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.POLICY_TARGET_DOES_NOT_EXIST, StringUtils.join(targets.values())));
- }
- return updateTargets(component.getUniqueId(), component.getPolicyById(policyId), targets, policyId);
+ return validateTargetsExistAndTypesCorrect(component.getUniqueId(), targets)
+ .left()
+ .bind(cmp ->updateTargets(component.getUniqueId(), component.getPolicyById(policyId), targets, policyId));
}
- private boolean validateTargetsExistAndTypesCorrect(String componentId, Map<PolicyTargetType, List<String>> targets) {
+ private Either<Component, ResponseFormat> validateTargetsExistAndTypesCorrect(String componentId, Map<PolicyTargetType, List<String>> targets) {
Either<Component, StorageOperationStatus> componentEither = toscaOperationFacade.getToscaFullElement(componentId);
+ if (componentEither.isRight()) {
+ return Either.right(componentsUtils.getResponseFormat(componentEither.right().value()));
+ }
Component parentComponent = componentEither.left().value();
+ return validateTargetExists(parentComponent, targets.entrySet());
+ }
- return targets.entrySet().stream().noneMatch(t -> checkTargetNotExistOnComponentByType(parentComponent, t));
+
+
+ private Either<Component, ResponseFormat> validateTargetExists(Component parentComponent, Set<Map.Entry<PolicyTargetType, List<String>>> entries) {
+ for(Map.Entry<PolicyTargetType, List<String>> entry : entries){
+ Either<Component, ResponseFormat> result = checkTargetNotExistOnComponentByType(parentComponent, entry);
+ if(result.isRight()){
+ return result;
+ }
+ }
+ return Either.left(parentComponent);
}
- private boolean checkTargetNotExistOnComponentByType(Component parentComponent, Map.Entry<PolicyTargetType, List<String>> targetEntry) {
+ private Either<Component, ResponseFormat> checkTargetNotExistOnComponentByType(Component parentComponent, Map.Entry<PolicyTargetType, List<String>> targetEntry) {
- return targetEntry.getValue().stream()
- .anyMatch(id -> checkNotPresenceInComponentByType(parentComponent, id, targetEntry.getKey().toString()));
+ for(String id : targetEntry.getValue()){
+ if(checkNotPresenceInComponentByType(parentComponent, id, targetEntry.getKey().getName())){
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.POLICY_TARGET_DOES_NOT_EXIST, id));
+ }
+ }
+ return Either.left(parentComponent);
}
private boolean checkNotPresenceInComponentByType(Component parentComponent, String uniqueId, String type) {
@@ -246,7 +253,8 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
log.trace("#updatePolicyProperties - starting to update properties of the policy {} on the component {}. ", policyId, componentId);
Wrapper<Component> component = new Wrapper<>();
try {
- result = validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock).left().bind(c -> setComponentValidateUpdatePolicyProperties(policyId, properties, component, c));
+ result = validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock).left()
+ .bind(c -> setComponentValidateUpdatePolicyProperties(policyId, properties, component, c));
} catch (Exception e) {
log.error("#updatePolicyProperties - the exception {} occurred upon update properties of the policy {} for the component {}: ", policyId, componentId, e);
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -260,9 +268,14 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
private Either<List<PropertyDataDefinition>, ResponseFormat> setComponentValidateUpdatePolicyProperties(String policyId, PropertyDataDefinition[] properties, Wrapper<Component> component, Component c) {
component.setInnerElement(c);
+ Set<String> updatedPropertyNames = Arrays.stream(properties).map(PropertyDataDefinition::getName).collect(Collectors.toSet());
return validateAndUpdatePolicyProperties(c, policyId, properties)
.left()
- .map(PolicyDefinition::getProperties);
+ .map(policyDefinition -> getFilteredProperties(policyDefinition.getProperties(), updatedPropertyNames));
+ }
+
+ private List<PropertyDataDefinition> getFilteredProperties(List<PropertyDataDefinition> all, Set<String> filtered) {
+ return all.stream().filter(pd -> filtered.contains(pd.getName())).collect(Collectors.toList());
}
private void unlockComponent(boolean shouldLock, Either<PolicyDefinition, ResponseFormat> result, Wrapper<Component> component) {
@@ -333,18 +346,12 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
}
private Either<Component, ResponseFormat> validateContainerComponentAndUserBeforeReadOperation(ComponentTypeEnum componentType, String componentId, String userId) {
- Either<Component, ResponseFormat> result = null;
+ Either<Component, ResponseFormat> result;
log.trace("#validateContainerComponentAndUserBeforeReadOperation - starting to validate the user {} before policy processing. ", userId);
- Either<User, ResponseFormat> resp = validateUserExists(userId, "create Policy", false);
- if (resp.isRight()) {
- log.error("#validateContainerComponentAndUserBeforeReadOperation - failed to validate the user {} before policy processing. ", userId);
- result = Either.right(resp.right().value());
- } else {
- result = validateComponentExists(componentType, componentId);
- if (result.isRight()) {
- log.error(FAILED_TO_VALIDATE_COMPONENT, "#validateContainerComponentAndUserBeforeReadOperation", componentId);
- }
- return result;
+ validateUserExists(userId, "create Policy", false);
+ result = validateComponentExists(componentType, componentId);
+ if (result.isRight()) {
+ log.error(FAILED_TO_VALIDATE_COMPONENT, "#validateContainerComponentAndUserBeforeReadOperation", componentId);
}
return result;
}
@@ -394,10 +401,10 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
Map<String, PropertyDataDefinition> oldProperties = policy.getProperties().stream().collect(toMap(PropertyDataDefinition::getName, Function.identity()));
for (PropertyDataDefinition newProperty : newProperties) {
if (!oldProperties.containsKey(newProperty.getName())) {
- log.error("#updatePropertyValues - failed to update properites of the policy {}. Properties were not found on the policy. ");
+ log.error("#updatePropertyValues - failed to update properites of the policy {}. Properties were not found on the policy. ", policy.getName());
return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, newProperty.getName()));
}
- Either<String, ResponseFormat> newPropertyValueEither = updatePropertyObjectValue(newProperty, true);
+ Either<String, ResponseFormat> newPropertyValueEither = updateInputPropertyObjectValue(newProperty);
if (newPropertyValueEither.isRight()) {
return Either.right(newPropertyValueEither.right().value());
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogic.java
index a65a23e5f4..cb4b6ff58c 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogic.java
@@ -1,8 +1,7 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.List;
-import java.util.Set;
-
+import fj.data.Either;
+import org.apache.commons.lang.StringUtils;
import org.openecomp.sdc.be.components.validation.UserValidations;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
@@ -10,17 +9,21 @@ import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.PolicyTypeDefinition;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.PolicyTypeOperation;
+import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
+import org.springframework.transaction.annotation.Transactional;
-import fj.data.Either;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import static java.util.Collections.emptySet;
@Component
public class PolicyTypeBusinessLogic {
- private static final Logger log = LoggerFactory.getLogger(PolicyTypeBusinessLogic.class);
+ private static final Logger log = Logger.getLogger(PolicyTypeBusinessLogic.class);
private PolicyTypeOperation policyTypeOperation;
private TitanDao titanDao;
private ComponentsUtils componentsUtils;
@@ -33,21 +36,24 @@ public class PolicyTypeBusinessLogic {
this.userValidations = userValidations;
}
- public Either<List<PolicyTypeDefinition>, ResponseFormat> getAllPolicyTypes(String userId, String internalComponentType) {
- try {
- Set<String> excludedPolicyTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedPolicyTypesMapping().get(internalComponentType);
- return userValidations.validateUserExists(userId, "get policy types", true)
- .left()
- .bind(user -> getPolicyTypes(excludedPolicyTypes));
- } finally {
- titanDao.commit();
+ @Transactional
+ public List<PolicyTypeDefinition> getAllPolicyTypes(String userId, String internalComponentType) {
+ Set<String> excludedPolicyTypes = getExcludedPolicyTypes(internalComponentType);
+ userValidations.validateUserExists(userId, "get policy types", true);
+ return getPolicyTypes(excludedPolicyTypes);
+ }
+
+ public Set<String> getExcludedPolicyTypes(String internalComponentType) {
+ if (StringUtils.isEmpty(internalComponentType)) {
+ return emptySet();
}
+ Map<String, Set<String>> excludedPolicyTypesMapping = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedPolicyTypesMapping();
+ Set<String> excludedTypes = excludedPolicyTypesMapping.get(internalComponentType);
+ return excludedTypes == null ? emptySet() : excludedTypes;
}
- private Either<List<PolicyTypeDefinition>, ResponseFormat> getPolicyTypes(Set<String> excludedTypes) {
- return policyTypeOperation.getAllPolicyTypes(excludedTypes)
- .right()
- .bind(this::convertToResponseFormatOrNotFoundErrorToEmptyList);
+ private List<PolicyTypeDefinition> getPolicyTypes(Set<String> excludedTypes) {
+ return policyTypeOperation.getAllPolicyTypes(excludedTypes);
}
private Either<List<PolicyTypeDefinition>, ResponseFormat> convertToResponseFormatOrNotFoundErrorToEmptyList(StorageOperationStatus err) {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java
index 7efff56003..f40e0e97f5 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java
@@ -20,15 +20,10 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.List;
-import java.util.Map;
-import java.util.function.Consumer;
-
-import javax.annotation.Resource;
-
+import fj.data.Either;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum;
-import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
+import org.openecomp.sdc.be.components.impl.model.ToscaTypeImportData;
import org.openecomp.sdc.be.components.impl.utils.PolicyTypeImportUtils;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.impl.ComponentsUtils;
@@ -37,39 +32,42 @@ import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
import org.openecomp.sdc.be.model.operations.api.IPolicyTypeOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.utils.TypeUtils;
import org.openecomp.sdc.exception.ResponseFormat;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-import fj.data.Either;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Consumer;
@Component("policyTypeImportManager")
public class PolicyTypeImportManager {
- @Resource
- private IPolicyTypeOperation policyTypeOperation;
- @Resource
- private ComponentsUtils componentsUtils;
- @Autowired
- protected IGroupOperation groupOperation;
- @Autowired
- private ToscaOperationFacade toscaOperationFacade;
-
- @Resource
- private CommonImportManager commonImportManager;
+ private final IPolicyTypeOperation policyTypeOperation;
+ private final ComponentsUtils componentsUtils;
+ private final IGroupOperation groupOperation;
+ private final ToscaOperationFacade toscaOperationFacade;
+ private final CommonImportManager commonImportManager;
+
+ public PolicyTypeImportManager(IPolicyTypeOperation policyTypeOperation, ComponentsUtils componentsUtils, IGroupOperation groupOperation, ToscaOperationFacade toscaOperationFacade, CommonImportManager commonImportManager) {
+ this.policyTypeOperation = policyTypeOperation;
+ this.componentsUtils = componentsUtils;
+ this.groupOperation = groupOperation;
+ this.toscaOperationFacade = toscaOperationFacade;
+ this.commonImportManager = commonImportManager;
+ }
- public Either<List<ImmutablePair<PolicyTypeDefinition, Boolean>>, ResponseFormat> createPolicyTypes(String policyTypesYml) {
- return commonImportManager.createElementTypes(policyTypesYml, this::createPolicyTypesFromYml, this::upsertPolicyTypesByDao, ElementTypeEnum.PolicyType);
+ public Either<List<ImmutablePair<PolicyTypeDefinition, Boolean>>, ResponseFormat> createPolicyTypes(ToscaTypeImportData toscaTypeImportData) {
+ return commonImportManager.createElementTypes(toscaTypeImportData, this::createPolicyTypesFromYml, this::upsertPolicyTypesByDao);
}
private Either<List<PolicyTypeDefinition>, ActionStatus> createPolicyTypesFromYml(String policyTypesYml) {
-
return commonImportManager.createElementTypesFromYml(policyTypesYml, this::createPolicyType);
}
private Either<List<ImmutablePair<PolicyTypeDefinition, Boolean>>, ResponseFormat> upsertPolicyTypesByDao(List<PolicyTypeDefinition> policyTypesToCreate) {
- return commonImportManager.createElementTypesByDao(policyTypesToCreate, this::validatePolicyType, policyType -> new ImmutablePair<>(ElementTypeEnum.PolicyType, policyType.getType()),
- policyTypeName -> policyTypeOperation.getLatestPolicyTypeByType(policyTypeName), policyType -> policyTypeOperation.addPolicyType(policyType), this::updatePolicyType);
+ return commonImportManager.createElementTypesByDao(policyTypesToCreate, this::validatePolicyType, policyType -> new ImmutablePair<>(ElementTypeEnum.POLICY_TYPE, policyType.getType()),
+ policyTypeOperation::getLatestPolicyTypeByType, policyTypeOperation::addPolicyType, this::updatePolicyType);
}
private Either<PolicyTypeDefinition, StorageOperationStatus> updatePolicyType(PolicyTypeDefinition newPolicyType, PolicyTypeDefinition oldPolicyType) {
@@ -115,25 +113,25 @@ public class PolicyTypeImportManager {
if (toscaJson != null) {
// Description
- final Consumer<String> descriptionSetter = description -> policyType.setDescription(description);
- commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DESCRIPTION.getElementName(), descriptionSetter);
+ final Consumer<String> descriptionSetter = policyType::setDescription;
+ commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName(), descriptionSetter);
// Derived From
- final Consumer<String> derivedFromSetter = derivedFrom -> policyType.setDerivedFrom(derivedFrom);
- commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DERIVED_FROM.getElementName(), derivedFromSetter);
+ final Consumer<String> derivedFromSetter = policyType::setDerivedFrom;
+ commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DERIVED_FROM.getElementName(), derivedFromSetter);
// Properties
- commonImportManager.setProperties(toscaJson, (values) -> policyType.setProperties(values));
+ CommonImportManager.setProperties(toscaJson, policyType::setProperties);
// Metadata
- final Consumer<Map<String, String>> metadataSetter = metadata -> policyType.setMetadata(metadata);
- commonImportManager.setField(toscaJson, ToscaTagNamesEnum.METADATA.getElementName(), metadataSetter);
+ final Consumer<Map<String, String>> metadataSetter = policyType::setMetadata;
+ commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.METADATA.getElementName(), metadataSetter);
// Targets
- final Consumer <List<String>> targetsSetter = targets -> policyType.setTargets(targets);
- commonImportManager.setField(toscaJson, ToscaTagNamesEnum.TARGETS.getElementName(), targetsSetter);
+ final Consumer <List<String>> targetsSetter = policyType::setTargets;
+ commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.TARGETS.getElementName(), targetsSetter);
policyType.setType(groupTypeName);
policyType.setHighestVersion(true);
- policyType.setVersion(ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION);
+ policyType.setVersion(TypeUtils.FIRST_CERTIFIED_VERSION_VERSION);
}
return policyType;
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java
index f6a789b248..dac241ba2f 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java
@@ -20,14 +20,8 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.stream.Collectors;
-
+import fj.data.Either;
+import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datamodel.api.CategoryTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
@@ -39,30 +33,29 @@ import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.category.GroupingDefinition;
import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
-import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation;
-import org.openecomp.sdc.be.model.operations.api.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
import org.openecomp.sdc.be.user.Role;
+import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import fj.data.Either;
+import java.util.*;
+import java.util.stream.Collectors;
@org.springframework.stereotype.Component("productBusinessLogic")
public class ProductBusinessLogic extends ComponentBusinessLogic {
private static final String PRODUCT_FULL_NAME = "full";
private static final String PRODUCT_ABBREVIATED_NAME = "abbreviated";
- private static final Logger log = LoggerFactory.getLogger(ProductBusinessLogic.class);
+ private static final Logger log = Logger.getLogger(ProductBusinessLogic.class);
private static final String INITIAL_VERSION = "0.1";
+ private static final String CREATE_PRODUCT = "Create Product";
private static List<Role> creationRoles;
private static List<Role> updateRoles;
private static List<Role> contactsRoles;
@@ -80,17 +73,11 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
}
@Autowired
- private IElementOperation elementDao;
-
- @Autowired
private ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
@Autowired
private ICacheMangerOperation cacheManagerOperation;
- @Autowired
- ToscaOperationFacade toscaOperationFacade;
-
public Either<Product, ResponseFormat> createProduct(Product product, User user) {
AuditingActionEnum actionEnum = AuditingActionEnum.CREATE_RESOURCE;
ComponentTypeEnum typeEnum = ComponentTypeEnum.PRODUCT;
@@ -98,17 +85,9 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
// validate user - should be first to get the maximum auditing info in
// case of subsequent failures
log.debug("get user from DB");
- Either<User, ResponseFormat> eitherCreator = validateUser(user, "Create Product", product, actionEnum, false);
- if (eitherCreator.isRight()) {
- return Either.right(eitherCreator.right().value());
- }
- user = eitherCreator.left().value();
-
+ user = validateUser(user, CREATE_PRODUCT, product, actionEnum, false);
// validate user role
- Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, product, creationRoles, actionEnum, null);
- if (validateRes.isRight()) {
- return Either.right(validateRes.right().value());
- }
+ validateUserRole(user, product, creationRoles, actionEnum, null);
if (product == null) {
log.debug("Invalid product json. Check product servlet log for createProduct entry params");
@@ -127,7 +106,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
log.debug("send product {} to dao for create", product.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
- Either<Boolean, ResponseFormat> lockResult = lockComponentByName(product.getSystemName(), product, "Create Product");
+ Either<Boolean, ResponseFormat> lockResult = lockComponentByName(product.getSystemName(), product, CREATE_PRODUCT);
if (lockResult.isRight()) {
ResponseFormat responseFormat = lockResult.right().value();
componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
@@ -218,10 +197,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
return tagsValidation;
}
- Either<Boolean, ResponseFormat> validateIconResponse = validateIcon(user, product, actionEnum);
- if (validateIconResponse.isRight()) {
- return validateIconResponse;
- }
+ validateIcon(user, product, actionEnum);
Either<Boolean, ResponseFormat> projectCodeValidation = validateProjectCode(user, product, actionEnum);
if (projectCodeValidation.isRight()) {
@@ -242,21 +218,14 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
return productFullNameValidation;
}
- Either<Boolean, ResponseFormat> descValidation = validateDescriptionAndCleanup(user, product, actionEnum);
- if (descValidation.isRight()) {
- return descValidation;
- }
+ validateDescriptionAndCleanup(user, product, actionEnum);
return Either.left(true);
}
public Either<Map<String, Boolean>, ResponseFormat> validateProductNameExists(String productName, String userId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "validate Product Name Exists", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
+ validateUserExists(userId, "validate Product Name Exists", false);
Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(productName, null, ComponentTypeEnum.PRODUCT);
// DE242223
titanDao.commit();
@@ -298,26 +267,16 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
return Either.right(responseFormat);
}
- User contactUser = new User();
- contactUser.setUserId(contact);
- Either<User, ResponseFormat> validateUser = validateUserExists(contact, "Create Product", false);
- if (validateUser.isRight()) {
- log.debug("Cannot set contact with userId {} as product contact, error: {}", contact, validateUser.right().value());
+ User contactUser;
+ try{
+ contactUser = validateUserExists(contact, CREATE_PRODUCT, false);
+ validateUserRole(contactUser, contactsRoles);
+ } catch(ComponentException e){
+ log.debug("Cannot set contact with userId {} as product contact, error: {}", contact, e.getActionStatus());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PRODUCT_CONTACT, contact);
componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
- return Either.right(responseFormat);
+ throw new ComponentException(e.getActionStatus(), e.getParams());
}
-
- contactUser = validateUser.left().value();
-
- Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(contactUser, contactsRoles);
- if (validateUserRole.isRight()) {
- log.debug("Cannot set contact with userId {} as product contact, error: {}", contact, validateUserRole.right().value());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PRODUCT_CONTACT, contact);
- componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
- return Either.right(responseFormat);
- }
-
}
if (!isProductCreatorInContacts) {
@@ -326,7 +285,9 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
}
// passed - setting all contacts userIds to lowercase
- List<String> tempContacts = contacts.stream().map(e -> e.toLowerCase()).collect(Collectors.toList());
+ List<String> tempContacts = contacts.stream()
+ .map(String::toLowerCase)
+ .collect(Collectors.toList());
ValidationUtils.removeDuplicateFromList(tempContacts);
product.setContacts(tempContacts);
@@ -339,11 +300,11 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
log.debug("Grouping list is empty for product: {}", product.getName());
return Either.left(true);
}
- Map<String, Map<String, Set<String>>> nonDuplicatedCategories = new HashMap<String, Map<String, Set<String>>>();
+ Map<String, Map<String, Set<String>>> nonDuplicatedCategories = new HashMap<>();
// remove duplicated entries
for (CategoryDefinition cat : categories) {
String catName = cat.getName();
- if (ValidationUtils.validateStringNotEmpty(catName) == false) {
+ if (!ValidationUtils.validateStringNotEmpty(catName)) {
// error missing cat name
log.debug("Missing category name for product: {}", product.getName());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.PRODUCT.getValue());
@@ -352,7 +313,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
}
Map<String, Set<String>> catEntry = nonDuplicatedCategories.get(catName);
if (catEntry == null) {
- catEntry = new HashMap<String, Set<String>>();
+ catEntry = new HashMap<>();
nonDuplicatedCategories.put(catName, catEntry);
}
List<SubCategoryDefinition> subcategories = cat.getSubcategories();
@@ -365,7 +326,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
}
for (SubCategoryDefinition subcat : subcategories) {
String subCatName = subcat.getName();
- if (ValidationUtils.validateStringNotEmpty(subCatName) == false) {
+ if (!ValidationUtils.validateStringNotEmpty(subCatName)) {
// error missing sub cat name for cat
log.debug("Missing or empty sub-category for category {} in product {}", catName, product.getName());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
@@ -374,13 +335,13 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
}
Set<String> subcatEntry = catEntry.get(subCatName);
if (subcatEntry == null) {
- subcatEntry = new HashSet<String>();
+ subcatEntry = new HashSet<>();
catEntry.put(subCatName, subcatEntry);
}
List<GroupingDefinition> groupings = subcat.getGroupings();
for (GroupingDefinition group : groupings) {
String groupName = group.getName();
- if (ValidationUtils.validateStringNotEmpty(groupName) == false) {
+ if (!ValidationUtils.validateStringNotEmpty(groupName)) {
// error missing grouping for sub cat name and cat
log.debug("Missing or empty groupng name for sub-category: {} for categor: {} in product: {}", subCatName, catName, product.getName());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
@@ -407,7 +368,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
boolean catExist;
// convert non-duplicated to data modeling format and update in the
// input object
- List<CategoryDefinition> newCatList = new ArrayList<CategoryDefinition>();
+ List<CategoryDefinition> newCatList = new ArrayList<>();
// over all categories from request
for (Map.Entry<String, Map<String, Set<String>>> entry : nonDuplicatedCategories.entrySet()) {
@@ -485,15 +446,8 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
public Either<Product, ResponseFormat> getProduct(String productId, User user) {
String ecompErrorContext = "Get product";
- Either<User, ResponseFormat> validateEmptyResult = validateUserNotEmpty(user, ecompErrorContext);
- if (validateEmptyResult.isRight()) {
- return Either.right(validateEmptyResult.right().value());
- }
-
- Either<User, ResponseFormat> eitherCreator = validateUserExists(user, ecompErrorContext, false);
- if (eitherCreator.isRight()) {
- return Either.right(eitherCreator.right().value());
- }
+ validateUserNotEmpty(user, ecompErrorContext);
+ validateUserExists(user, ecompErrorContext, false);
Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(productId);
@@ -511,15 +465,8 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
public Either<Product, ResponseFormat> deleteProduct(String productId, User user) {
String ecompErrorContext = "Delete product";
- Either<User, ResponseFormat> validateEmptyResult = validateUserNotEmpty(user, ecompErrorContext);
- if (validateEmptyResult.isRight()) {
- return Either.right(validateEmptyResult.right().value());
- }
-
- Either<User, ResponseFormat> eitherCreator = validateUserExists(user, ecompErrorContext, false);
- if (eitherCreator.isRight()) {
- return Either.right(eitherCreator.right().value());
- }
+ validateUserNotEmpty(user, ecompErrorContext);
+ validateUserExists(user, ecompErrorContext, false);
Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.deleteToscaComponent(productId);
@@ -599,13 +546,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
// normalizations.
private Either<Boolean, ResponseFormat> validateTagsListAndRemoveDuplicates(User user, Product product, String oldProductName, AuditingActionEnum actionEnum) {
List<String> tagsList = product.getTags();
-
- Either<Boolean, ResponseFormat> validateTags = validateComponentTags(tagsList, oldProductName, ComponentTypeEnum.PRODUCT);
- if (validateTags.isRight()) {
- ResponseFormat responseFormat = validateTags.right().value();
- componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
- return Either.right(responseFormat);
- }
+ validateComponentTags(tagsList, oldProductName, ComponentTypeEnum.PRODUCT, user, product, actionEnum);
ValidationUtils.removeDuplicateFromList(tagsList);
return Either.left(true);
}
@@ -617,18 +558,9 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
public Either<Product, ResponseFormat> updateProductMetadata(String productId, Product updatedProduct, User user) {
ComponentTypeEnum typeEnum = ComponentTypeEnum.PRODUCT;
- Either<User, ResponseFormat> eitherCreator = validateUser(user, "Update Product", updatedProduct, null, false);
- if (eitherCreator.isRight()) {
- return Either.right(eitherCreator.right().value());
- }
- user = eitherCreator.left().value();
-
+ user = validateUser(user, "Update Product", updatedProduct, null, false);
// validate user role
- Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, updatedProduct, updateRoles, null, null);
- if (validateRes.isRight()) {
- return Either.right(validateRes.right().value());
- }
-
+ validateUserRole(user, updatedProduct, updateRoles, null, null);
if (updatedProduct == null) {
log.debug("Invalid product json. Check product servlet log for updateProduct entry params");
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
@@ -744,7 +676,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
private Either<Boolean, ResponseFormat> validateAndUpdateProductName(User user, Product currentProduct, Product updatedProduct) {
String updatedProductName = updatedProduct.getName();
- String tags = "";
+ String tags;
String currentProductName = currentProduct.getName();
if (updatedProductName != null) {
Either<Boolean, ResponseFormat> validatProductNameResponse = validateProductNameAndCleanup(user, updatedProduct, null);
@@ -789,15 +721,14 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
}
private Either<Boolean, ResponseFormat> validateAndUpdateCategory(User user, Product currentProduct, Product updatedProduct) {
- List<CategoryDefinition> categoryUpdated = updatedProduct.getCategories();
- Either<Boolean, ResponseFormat> validatCategoryResponse = validateGrouping(user, updatedProduct, null);
- if (validatCategoryResponse.isRight()) {
- ResponseFormat errorResponse = validatCategoryResponse.right().value();
+ Either<Boolean, ResponseFormat> validateCategoryResponse = validateGrouping(user, updatedProduct, null);
+ if (validateCategoryResponse.isRight()) {
+ ResponseFormat errorResponse = validateCategoryResponse.right().value();
return Either.right(errorResponse);
}
- categoryUpdated = updatedProduct.getCategories();
+ List<CategoryDefinition> categoryUpdated = updatedProduct.getCategories();
if (categoryUpdated != null) {
currentProduct.setCategories(categoryUpdated);
}
@@ -848,10 +779,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
}
public Either<Product, ResponseFormat> getProductByNameAndVersion(String productName, String productVersion, String userId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Service By Name And Version", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "get Service By Name And Version", false);
Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.PRODUCT, productName, productVersion);
if (storageStatus.isRight()) {
log.debug("failed to get service by name {} and version {}", productName, productVersion);
@@ -867,7 +795,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
}
@Override
- public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) {
+ public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, String userId) {
return null;
}
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 aeab3cd592..5f40606177 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
@@ -20,14 +20,8 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.function.Supplier;
-
-import javax.servlet.ServletContext;
-
+import com.google.gson.JsonElement;
+import fj.data.Either;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
@@ -41,37 +35,35 @@ import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.IComplexDefaultValue;
import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter;
-import org.openecomp.sdc.be.model.tosca.validators.DataTypeValidatorConverter;
import org.openecomp.sdc.be.model.tosca.validators.PropertyTypeValidator;
import org.openecomp.sdc.be.resources.data.EntryData;
import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
-import com.google.gson.JsonElement;
-
-import fj.data.Either;
+import javax.servlet.ServletContext;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.function.Supplier;
@Component("propertyBusinessLogic")
public class PropertyBusinessLogic extends BaseBusinessLogic {
private static final String CREATE_PROPERTY = "CreateProperty";
- private static final Logger log = LoggerFactory.getLogger(PropertyBusinessLogic.class);
+ private static final Logger log = Logger.getLogger(PropertyBusinessLogic.class);
private static final String EMPTY_VALUE = null;
- private DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance();
-
protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) {
WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
@@ -81,8 +73,7 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
}
public Either<Map<String, DataTypeDefinition>, ResponseFormat> getAllDataTypes() {
- Either<Map<String, DataTypeDefinition>, ResponseFormat> eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache);
- return eitherAllDataTypes;
+ return getAllDataTypes(applicationDataTypeCache);
}
/**
@@ -92,17 +83,13 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
* @param propertyName
* @param newPropertyDefinition
* @param userId
- * @return Either<PropertyDefinition, ActionStatus>
+ * @return either properties or response format
*/
public Either<EntryData<String, PropertyDefinition>, ResponseFormat> createProperty(String resourceId, String propertyName, PropertyDefinition newPropertyDefinition, String userId) {
Either<EntryData<String, PropertyDefinition>, ResponseFormat> result = null;
- Either<User, ResponseFormat> resp = validateUserExists(userId, "create Property", false);
- if (resp.isRight()) {
- result = Either.right(resp.right().value());
- return result;
- }
+ validateUserExists(userId, "create Property", false);
StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource);
if (!lockResult.equals(StorageOperationStatus.OK)) {
@@ -131,11 +118,9 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
// verify property not exist in resource
List<PropertyDefinition> resourceProperties = resource.getProperties();
- if (resourceProperties != null) {
- if (isPropertyExist(resourceProperties, resourceId, propertyName, newPropertyDefinition.getType())) {
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, propertyName));
- return result;
- }
+ if (resourceProperties != null && isPropertyExist(resourceProperties, resourceId, propertyName, newPropertyDefinition.getType())) {
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, propertyName));
+ return result;
}
Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache);
@@ -152,27 +137,8 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
result = Either.right(defaultValuesValidation.right().value());
return result;
}
- // convert property
- ToscaPropertyType type = getType(newPropertyDefinition.getType());
- if (type != null) {
- PropertyValueConverter converter = type.getConverter();
- // get inner type
- String innerType = null;
- if (newPropertyDefinition != null) {
- SchemaDefinition schema = newPropertyDefinition.getSchema();
- if (schema != null) {
- PropertyDataDefinition prop = schema.getProperty();
- if (prop != null) {
- innerType = prop.getType();
- }
- }
- String convertedValue = null;
- if (newPropertyDefinition.getDefaultValue() != null) {
- convertedValue = converter.convert(newPropertyDefinition.getDefaultValue(), innerType, allDataTypes.left().value());
- newPropertyDefinition.setDefaultValue(convertedValue);
- }
- }
- }
+ convertProperty(newPropertyDefinition, allDataTypes);
+
// add the new property to resource on graph
// need to get StorageOpaerationStatus and convert to ActionStatus
@@ -184,7 +150,7 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
}
PropertyDefinition createdPropertyDefinition = either.left().value();
- EntryData<String, PropertyDefinition> property = new EntryData<String, PropertyDefinition>(propertyName, createdPropertyDefinition);
+ EntryData<String, PropertyDefinition> property = new EntryData<>(propertyName, createdPropertyDefinition);
result = Either.left(property);
return result;
@@ -196,21 +162,33 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
}
+ private void convertProperty(PropertyDefinition newPropertyDefinition, Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes) {
+ ToscaPropertyType type = getType(newPropertyDefinition.getType());
+ if (type != null) {
+ String innerType = null;
+ SchemaDefinition schema = newPropertyDefinition.getSchema();
+ if (schema != null && schema.getProperty() != null) {
+ innerType = schema.getProperty().getType();
+ }
+ if (newPropertyDefinition.getDefaultValue() != null) {
+ newPropertyDefinition.setDefaultValue(
+ type.getConverter().convert(
+ newPropertyDefinition.getDefaultValue(), innerType, allDataTypes.left().value()));
+ }
+ }
+ }
+
/**
* Get property of resource
*
* @param resourceId
* @param propertyId
* @param userId
- * @return
+ * @return either properties or response format
*/
public Either<Entry<String, PropertyDefinition>, ResponseFormat> getProperty(String resourceId, String propertyId, String userId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "create Component Instance", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
+ validateUserExists(userId, "create Component Instance", false);
// Get the resource from DB
Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId);
if (status.isRight()) {
@@ -239,16 +217,13 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
* @param resourceId
* @param propertyId
* @param userId
- * @return
+ * @return either properties or response format
*/
public Either<Entry<String, PropertyDefinition>, ResponseFormat> deleteProperty(String resourceId, String propertyId, String userId) {
Either<Entry<String, PropertyDefinition>, ResponseFormat> result = null;
- Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Property", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "delete Property", false);
StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource);
if (!lockResult.equals(StorageOperationStatus.OK)) {
@@ -303,7 +278,7 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
* @param propertyId
* @param newPropertyDefinition
* @param userId
- * @return
+ * @return either properties or response format
*/
public Either<EntryData<String, PropertyDefinition>, ResponseFormat> updateProperty(String resourceId, String propertyId, PropertyDefinition newPropertyDefinition, String userId) {
@@ -347,7 +322,7 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
return result;
}
- Either<PropertyDefinition, StorageOperationStatus> either = handleProperty(propertyId, newPropertyDefinition, dataTypes);
+ Either<PropertyDefinition, StorageOperationStatus> either = handleProperty(newPropertyDefinition, dataTypes);
if (either.isRight()) {
log.debug("Problem while updating property with id {}. Reason - {}", propertyId, either.right().value());
result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName()));
@@ -361,7 +336,7 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
return result;
}
- EntryData<String, PropertyDefinition> property = new EntryData<String, PropertyDefinition>(propertyName, either.left().value());
+ EntryData<String, PropertyDefinition> property = new EntryData<>(propertyName, either.left().value());
result = Either.left(property);
return result;
@@ -387,7 +362,7 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
return result;
}
- private Either<PropertyDefinition, StorageOperationStatus> handleProperty(String propertyId, PropertyDefinition newPropertyDefinition, Map<String, DataTypeDefinition> dataTypes) {
+ private Either<PropertyDefinition, StorageOperationStatus> handleProperty(PropertyDefinition newPropertyDefinition, Map<String, DataTypeDefinition> dataTypes) {
StorageOperationStatus validateAndUpdateProperty = validateAndUpdateProperty(newPropertyDefinition, dataTypes);
if (validateAndUpdateProperty != StorageOperationStatus.OK) {
@@ -407,21 +382,16 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
ToscaPropertyType type = getType(propertyType);
if (type == null) {
-
DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
if (dataTypeDefinition == null) {
log.debug("The type {} of property cannot be found.", propertyType);
return StorageOperationStatus.INVALID_TYPE;
}
-
- StorageOperationStatus status = validateAndUpdateComplexValue(propertyDefinition, propertyType, value, dataTypeDefinition, dataTypes);
-
- return status;
-
+ return validateAndUpdateComplexValue(propertyDefinition, propertyType, value, dataTypeDefinition, dataTypes);
}
- String innerType = null;
+ String innerType;
- Either<String, TitanOperationStatus> checkInnerType = getInnerType(type, () -> propertyDefinition.getSchema());
+ Either<String, TitanOperationStatus> checkInnerType = getInnerType(type, propertyDefinition::getSchema);
if (checkInnerType.isRight()) {
return StorageOperationStatus.INVALID_TYPE;
}
@@ -430,7 +400,7 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
log.trace("After validating property type {}", propertyType);
boolean isValidProperty = isValidValue(type, value, innerType, dataTypes);
- if (false == isValidProperty) {
+ if (!isValidProperty) {
log.info("The value {} of property from type {} is invalid", value, type);
return StorageOperationStatus.INVALID_VALUE;
}
@@ -440,20 +410,19 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
if (isEmptyValue(value)) {
log.debug("Default value was not sent for property {}. Set default value to {}", propertyDefinition.getName(), EMPTY_VALUE);
propertyDefinition.setDefaultValue(EMPTY_VALUE);
- } else if (false == isEmptyValue(value)) {
+ } else if (!isEmptyValue(value)) {
String convertedValue = converter.convert(value, innerType, dataTypes);
propertyDefinition.setDefaultValue(convertedValue);
}
return StorageOperationStatus.OK;
}
- protected StorageOperationStatus validateAndUpdateComplexValue(IComplexDefaultValue propertyDefinition, String propertyType,
-
- String value, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> dataTypes) {
+ private StorageOperationStatus validateAndUpdateComplexValue(IComplexDefaultValue propertyDefinition, String propertyType,
+ String value, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> dataTypes) {
ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, dataTypes);
- if (validateResult.right.booleanValue() == false) {
+ if (validateResult.right) {
log.debug("The value {} of property from type {} is invalid", propertyType, propertyType);
return StorageOperationStatus.INVALID_VALUE;
}
@@ -467,29 +436,24 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
return StorageOperationStatus.OK;
}
- protected void updateValue(IComplexDefaultValue propertyDefinition, JsonElement jsonElement) {
+ private void updateValue(IComplexDefaultValue propertyDefinition, JsonElement jsonElement) {
propertyDefinition.setDefaultValue(getValueFromJsonElement(jsonElement));
}
+ @Override
protected String getValueFromJsonElement(JsonElement jsonElement) {
- String value = null;
-
if (jsonElement == null || jsonElement.isJsonNull()) {
- value = EMPTY_VALUE;
- } else {
- if (jsonElement.toString().isEmpty()) {
- value = "";
- } else {
- value = jsonElement.toString();
- }
+ return EMPTY_VALUE;
}
-
- return value;
+ if(jsonElement.toString().isEmpty()){
+ return "";
+ }
+ return jsonElement.toString();
}
- protected Either<String, TitanOperationStatus> getInnerType(ToscaPropertyType type, Supplier<SchemaDefinition> schemeGen) {
+ private Either<String, TitanOperationStatus> getInnerType(ToscaPropertyType type, Supplier<SchemaDefinition> schemeGen) {
String innerType = null;
if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
@@ -507,26 +471,18 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
}
return Either.left(innerType);
}
+
+ @Override
protected boolean isValidValue(ToscaPropertyType type, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
if (isEmptyValue(value)) {
return true;
}
-
PropertyTypeValidator validator = type.getValidator();
-
- boolean isValid = validator.isValid(value, innerType, dataTypes);
- if (true == isValid) {
- return true;
- } else {
- return false;
- }
-
+ return validator.isValid(value, innerType, dataTypes);
}
+ @Override
public boolean isEmptyValue(String value) {
- if (value == null) {
- return true;
- }
- return false;
+ return value == null;
}
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementsBusinessLogic.java
index 6454379af8..eb4bb33d70 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementsBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementsBusinessLogic.java
@@ -21,13 +21,12 @@
package org.openecomp.sdc.be.components.impl;
import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import org.openecomp.sdc.common.log.wrappers.Logger;
import org.springframework.stereotype.Component;
@Component("requirementsBusinessLogic")
public class RequirementsBusinessLogic {
- private static final Logger log = LoggerFactory.getLogger(RequirementsBusinessLogic.class);
+ private static final Logger log = Logger.getLogger(RequirementsBusinessLogic.class);
@javax.annotation.Resource
private ComponentsUtils componentsUtils;
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 fd1a272174..5678a628c5 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
@@ -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.
@@ -21,42 +21,24 @@
package org.openecomp.sdc.be.components.impl;
-import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN;
-
-import java.util.ArrayList;
-import java.util.Collection;
-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.Matcher;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
-
-import javax.servlet.ServletContext;
-
+import fj.data.Either;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.components.csar.CsarArtifactsAndGroupsBusinessLogic;
+import org.openecomp.sdc.be.components.csar.CsarBusinessLogic;
+import org.openecomp.sdc.be.components.csar.CsarInfo;
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationInfo;
import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
-import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaElementTypeEnum;
-import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
+import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
-import org.openecomp.sdc.be.components.merge.resource.MergeResourceBLFactory;
-import org.openecomp.sdc.be.components.merge.resource.MergeResourceBusinessLogic;
+import org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic;
+import org.openecomp.sdc.be.components.merge.utils.MergeInstanceUtils;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
import org.openecomp.sdc.be.config.ConfigurationManager;
@@ -65,110 +47,81 @@ import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils;
import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
+import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.CreatedFrom;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
import org.openecomp.sdc.be.info.NodeTypeInfoToUpdateArtifacts;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.CapabilityDefinition;
-import org.openecomp.sdc.be.model.CapabilityRequirementRelationship;
-import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.ComponentInstanceInput;
-import org.openecomp.sdc.be.model.ComponentInstanceProperty;
-import org.openecomp.sdc.be.model.ComponentParametersView;
-import org.openecomp.sdc.be.model.CsarInfo;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.GroupDefinition;
-import org.openecomp.sdc.be.model.GroupProperty;
-import org.openecomp.sdc.be.model.GroupTypeDefinition;
-import org.openecomp.sdc.be.model.InputDefinition;
-import org.openecomp.sdc.be.model.InterfaceDefinition;
-import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.NodeTypeInfo;
-import org.openecomp.sdc.be.model.Operation;
-import org.openecomp.sdc.be.model.ParsedToscaYamlInfo;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.model.RelationshipImpl;
-import org.openecomp.sdc.be.model.RelationshipInfo;
-import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
-import org.openecomp.sdc.be.model.RequirementDefinition;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.UploadCapInfo;
-import org.openecomp.sdc.be.model.UploadComponentInstanceInfo;
-import org.openecomp.sdc.be.model.UploadPropInfo;
-import org.openecomp.sdc.be.model.UploadReqInfo;
-import org.openecomp.sdc.be.model.UploadResourceInfo;
-import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
-import org.openecomp.sdc.be.model.jsontitan.operations.InterfaceOperation;
-import org.openecomp.sdc.be.model.jsontitan.utils.InterfaceUtils;
import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
-import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation;
-import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation;
-import org.openecomp.sdc.be.model.operations.api.IElementOperation;
-import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
-import org.openecomp.sdc.be.model.operations.api.IPropertyOperation;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.CsarOperation;
+import org.openecomp.sdc.be.model.operations.StorageException;
+import org.openecomp.sdc.be.model.operations.api.*;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
import org.openecomp.sdc.be.tosca.CsarUtils;
import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo;
import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
import org.openecomp.sdc.be.user.IUserBusinessLogic;
-import org.openecomp.sdc.be.user.Role;
import org.openecomp.sdc.be.user.UserBusinessLogic;
import org.openecomp.sdc.be.utils.CommonBeUtils;
+import org.openecomp.sdc.be.utils.TypeUtils;
import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
import org.openecomp.sdc.common.api.ArtifactTypeEnum;
import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.datastructure.FunctionalInterfaces;
import org.openecomp.sdc.common.datastructure.Wrapper;
import org.openecomp.sdc.common.kpi.api.ASDCKpiApi;
+import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.GeneralUtility;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
-import org.yaml.snakeyaml.parser.ParserException;
-import com.google.gson.Gson;
+import javax.servlet.ServletContext;
+import java.util.*;
+import java.util.Map.Entry;
+import java.util.function.Function;
+import java.util.regex.Pattern;
-import fj.data.Either;
+import static java.util.stream.Collectors.*;
+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;
@org.springframework.stereotype.Component("resourceBusinessLogic")
public class ResourceBusinessLogic extends ComponentBusinessLogic {
+ private static final String DELETE_RESOURCE = "Delete Resource";
+ private static final String IN_RESOURCE = " in resource {} ";
private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
public static final String INITIAL_VERSION = "0.1";
-
- private Pattern STR_REPLACE_PATTERN = Pattern.compile("^[ ]*\\{[ ]*" + "str_replace" + "=");
- private Pattern TOKEN_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "token" + "=");
- private Pattern GET_PROPERTY_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "get_property" + "=");
- private Pattern CONCAT_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "concat" + "=");
- private Pattern GET_ATTRIBUTE_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "get_attribute" + "=");
-
- private static final Logger log = LoggerFactory.getLogger(ResourceBusinessLogic.class);
-
- private static Pattern pattern = Pattern.compile("\\..(.*?)\\..");
+ private static final Logger log = Logger.getLogger(ResourceBusinessLogic.class);
+ private static final String CERTIFICATION_ON_IMPORT = "certification on import";
+ private static final String CREATE_RESOURCE = "Create Resource";
+ private static final String VALIDATE_DERIVED_BEFORE_UPDATE = "validate derived before update";
+ private static final String CATEGORY_IS_EMPTY = "Resource category is empty";
+ private static final String CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES = "Create Resource - validateCapabilityTypesCreate";
+ private static final String COMPONENT_INSTANCE_WITH_NAME = "component instance with name ";
+ private static final String COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE = "component instance with name {} in resource {} ";
/**
* Default constructor
@@ -187,18 +140,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
private LifecycleBusinessLogic lifecycleBusinessLogic;
@Autowired
- private IPropertyOperation propertyOperation;
-
- @Autowired
- private CsarOperation csarOperation;
-
- @Autowired
private ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
@Autowired
private ResourceImportManager resourceImportManager;
-
@Autowired
private InputsBusinessLogic inputsBusinessLogic;
@@ -209,30 +155,19 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
private ICacheMangerOperation cacheManagerOperation;
@Autowired
- private ApplicationDataTypeCache dataTypeCache;
-
- @Autowired
- private MergeResourceBLFactory mergeResourceBLFactory;
+ private ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic;
@Autowired
private CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic;
@Autowired
- private InterfaceOperation interfaceOperation;
-
- private Gson gson = new Gson();
-
- public void setInterfaceOperation(InterfaceOperation interfaceOperation) {
- this.interfaceOperation = interfaceOperation;
- }
+ private MergeInstanceUtils mergeInstanceUtils;
- public CsarOperation getCsarOperation() {
- return csarOperation;
- }
+ @Autowired
+ private UiComponentDataConverter uiComponentDataConverter;
- public void setCsarOperation(CsarOperation csarOperation) {
- this.csarOperation = csarOperation;
- }
+ @Autowired
+ private CsarBusinessLogic csarBusinessLogic;
public LifecycleBusinessLogic getLifecycleBusinessLogic() {
return lifecycleBusinessLogic;
@@ -274,10 +209,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
this.artifactsBusinessLogic = artifactsManager;
}
- public void setPropertyOperation(IPropertyOperation propertyOperation) {
- this.propertyOperation = propertyOperation;
- }
-
public ApplicationDataTypeCache getApplicationDataTypeCache() {
return applicationDataTypeCache;
}
@@ -286,10 +217,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
this.applicationDataTypeCache = applicationDataTypeCache;
}
- public void setInterfaceTypeOperation(IInterfaceLifecycleOperation interfaceTypeOperation) {
- this.interfaceTypeOperation = interfaceTypeOperation;
- }
-
/**
* the method returns a list of all the resources that are certified, the
* returned resources are only abstract or only none abstract according to
@@ -299,12 +226,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
* @param userId TODO
* @return
*/
- public Either<List<Resource>, ResponseFormat> getAllCertifiedResources(boolean getAbstract,
- HighestFilterEnum highestFilter, String userId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get All Certified Resources", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ public List<Resource> getAllCertifiedResources(boolean getAbstract,
+ HighestFilterEnum highestFilter, String userId) {
+ User user = validateUserExists(userId, "get All Certified Resources", false);
Boolean isHighest = null;
switch (highestFilter) {
case ALL:
@@ -322,20 +246,16 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
.getAllCertifiedResources(getAbstract, isHighest);
if (getResponse.isRight()) {
- return Either.right(componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(getResponse.right().value())));
+ throw new StorageException(getResponse.right().value());
}
- return Either.left(getResponse.left().value());
+ return getResponse.left().value();
}
public Either<Map<String, Boolean>, ResponseFormat> validateResourceNameExists(String resourceName,
ResourceTypeEnum resourceTypeEnum, String userId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "validate Resource Name Exists", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "validate Resource Name Exists", false);
Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
.validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE);
@@ -355,109 +275,60 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.right(responseFormat);
}
- public Either<Resource, ResponseFormat> createResource(Resource resource, AuditingActionEnum auditingAction,
- User user, Map<String, byte[]> csarUIPayload, String payloadName) {
- Either<Resource, ResponseFormat> createResourceResponse = validateResourceBeforeCreate(resource, user, false);
- if (createResourceResponse.isRight()) {
- return createResourceResponse;
- }
-
- // Creating resource either by DAO or from CSAR
- String csarUUID = null;
- if (payloadName == null) {
- csarUUID = resource.getCsarUUID();
- } else {
- csarUUID = payloadName;
- }
- if (csarUUID != null && !csarUUID.isEmpty()) {
- // check if VF with the same Csar UUID or with he same name already
- // exists
- Either<Integer, StorageOperationStatus> validateCsarUuidUniquenessRes = toscaOperationFacade
- .validateCsarUuidUniqueness(csarUUID);
- if (validateCsarUuidUniquenessRes.isRight()) {
- log.debug("Failed to validate uniqueness of CsarUUID {} for resource", csarUUID,
- resource.getSystemName());
- return Either.right(componentsUtils.getResponseFormat(
- componentsUtils.convertFromStorageResponse(validateCsarUuidUniquenessRes.right().value())));
- }
-
- Integer existingResourceRes = validateCsarUuidUniquenessRes.left().value();
- if (existingResourceRes.intValue() > 0) {
- log.debug("Failed to create resource {}, csarUUID {} already exist for a different VF ",
- resource.getSystemName(), csarUUID);
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS,
- csarUUID);
- componentsUtils.auditResource(errorResponse, user, resource, auditingAction);
- return Either.right(errorResponse);
- }
-
+ public Resource createResource(Resource resource, AuditingActionEnum auditingAction,
+ User user, Map<String, byte[]> csarUIPayload, String payloadName) {
+ validateResourceBeforeCreate(resource, user, false);
+ String csarUUID = payloadName == null ? resource.getCsarUUID() : payloadName;
+ if (StringUtils.isNotEmpty(csarUUID)) {
+ csarBusinessLogic.validateCsarBeforeCreate(resource, auditingAction, user, csarUUID);
log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID);
- createResourceResponse = createResourceFromCsar(resource, user, Either.left(csarUIPayload), csarUUID);
- return createResourceResponse;
+ return createResourceFromCsar(resource, user, csarUIPayload, csarUUID);
}
return createResourceByDao(resource, user, auditingAction, false, false);
}
- public Either<Resource, ResponseFormat> validateAndUpdateResourceFromCsar(Resource resource, User user,
- Map<String, byte[]> csarUIPayload, String payloadName, String resourceUniqueId) {
- Either<Resource, ResponseFormat> updateResourceResponse = null;
- Either<Resource, ResponseFormat> validateResourceResponse = null;
- Wrapper<ResponseFormat> responseWrapper = new Wrapper<ResponseFormat>();
- String csarUUID = null;
+ public Resource validateAndUpdateResourceFromCsar(Resource resource, User user,
+ Map<String, byte[]> csarUIPayload, String payloadName, String resourceUniqueId) {
+ String csarUUID = payloadName;
String csarVersion = null;
+ Resource updatedResource = null;
if (payloadName == null) {
csarUUID = resource.getCsarUUID();
csarVersion = resource.getCsarVersion();
- } else {
- csarUUID = payloadName;
}
if (csarUUID != null && !csarUUID.isEmpty()) {
- Resource oldResource = getResourceByUniqueId(responseWrapper, resourceUniqueId);
- if (responseWrapper.isEmpty()) {
- validateCsarUuidMatching(responseWrapper, oldResource, resource, csarUUID, resourceUniqueId, user);
- }
- if (responseWrapper.isEmpty()) {
- validateCsarIsNotAlreadyUsed(responseWrapper, oldResource, resource, csarUUID, user);
- }
- if (responseWrapper.isEmpty()) {
- if (oldResource != null && ValidationUtils.hasBeenCertified(oldResource.getVersion())) {
- overrideImmutableMetadata(oldResource, resource);
- }
- validateResourceResponse = validateResourceBeforeCreate(resource, user, false);
- if (validateResourceResponse.isRight()) {
- responseWrapper.setInnerElement(validateResourceResponse.right().value());
- }
- }
- if (responseWrapper.isEmpty()) {
- String oldCsarVersion = oldResource.getCsarVersion();
- log.debug("CsarUUID is {} - going to update resource with UniqueId {} from CSAR", csarUUID,
- resourceUniqueId);
- // (on boarding flow): If the update includes same csarUUID and
- // same csarVersion as already in the VF - no need to import the
- // csar (do only metadata changes if there are).
- if (csarVersion != null && oldCsarVersion != null && oldCsarVersion.equals(csarVersion)) {
- updateResourceResponse = updateResourceMetadata(resourceUniqueId, resource, oldResource, user,
- false);
- } else {
- updateResourceResponse = updateResourceFromCsar(oldResource, resource, user,
- AuditingActionEnum.UPDATE_RESOURCE_METADATA, false, Either.left(csarUIPayload), csarUUID);
- }
+ Resource oldResource = getResourceByUniqueId(resourceUniqueId);
+ validateCsarUuidMatching(oldResource, resource, csarUUID, resourceUniqueId, user);
+ validateCsarIsNotAlreadyUsed(oldResource, resource, csarUUID, user);
+ if (oldResource != null && ValidationUtils.hasBeenCertified(oldResource.getVersion())) {
+ overrideImmutableMetadata(oldResource, resource);
+ }
+ validateResourceBeforeCreate(resource, user, false);
+ String oldCsarVersion = oldResource.getCsarVersion();
+ log.debug("CsarUUID is {} - going to update resource with UniqueId {} from CSAR", csarUUID,
+ resourceUniqueId);
+ // (on boarding flow): If the update includes same csarUUID and
+ // same csarVersion as already in the VF - no need to import the
+ // csar (do only metadata changes if there are).
+ if (csarVersion != null && oldCsarVersion != null && oldCsarVersion.equals(csarVersion)) {
+ updatedResource = updateResourceMetadata(resourceUniqueId, resource, oldResource, user,
+ false);
+ } else {
+ updatedResource = updateResourceFromCsar(oldResource, resource, user,
+ AuditingActionEnum.UPDATE_RESOURCE_METADATA, false, csarUIPayload, csarUUID);
}
} else {
log.debug("Failed to update resource {}, csarUUID or payload name is missing", resource.getSystemName());
ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CSAR_UUID,
resource.getName());
componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.CREATE_RESOURCE);
- responseWrapper.setInnerElement(errorResponse);
+ throw new ComponentException(ActionStatus.MISSING_CSAR_UUID, resource.getName());
}
- if (responseWrapper.isEmpty()) {
- return updateResourceResponse;
- }
- return Either.right(responseWrapper.getInnerElement());
+ return updatedResource;
}
- private void validateCsarIsNotAlreadyUsed(Wrapper<ResponseFormat> responseWrapper, Resource oldResource,
+ private void validateCsarIsNotAlreadyUsed(Resource oldResource,
Resource resource, String csarUUID, User user) {
// (on boarding flow): If the update includes a csarUUID: verify this
// csarUUID is not in use by another VF, If it is - use same error as
@@ -471,19 +342,19 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (!StorageOperationStatus.NOT_FOUND.equals(resourceLinkedToCsarRes.right().value())) {
log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID,
resource.getSystemName());
- responseWrapper.setInnerElement(componentsUtils.getResponseFormat(
- componentsUtils.convertFromStorageResponse(resourceLinkedToCsarRes.right().value())));
+ throw new StorageException(resourceLinkedToCsarRes.right().value());
}
} else if (!resourceLinkedToCsarRes.left().value().getUniqueId().equals(oldResource.getUniqueId())
&& !resourceLinkedToCsarRes.left().value().getName().equals(oldResource.getName())) {
ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID,
resourceLinkedToCsarRes.left().value().getName());
componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
- responseWrapper.setInnerElement(errorResponse);
+ throw new ComponentException(ActionStatus.VSP_ALREADY_EXISTS, csarUUID,
+ resourceLinkedToCsarRes.left().value().getName());
}
}
- private void validateCsarUuidMatching(Wrapper<ResponseFormat> responseWrapper, Resource resource,
+ private void validateCsarUuidMatching(Resource resource,
Resource oldResource, String csarUUID, String resourceUniqueId, User user) {
// (on boarding flow): If the update includes csarUUID which is
// different from the csarUUID of the VF - fail with
@@ -497,18 +368,16 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
ResponseFormat errorResponse = componentsUtils.getResponseFormat(
ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
- responseWrapper.setInnerElement(errorResponse);
+ throw new ComponentException(ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
}
}
- private Resource getResourceByUniqueId(Wrapper<ResponseFormat> responseWrapper, String resourceUniqueId) {
+ private Resource getResourceByUniqueId(String resourceUniqueId) {
Either<Resource, StorageOperationStatus> oldResourceRes = toscaOperationFacade.getToscaFullElement(resourceUniqueId);
if (oldResourceRes.isRight()) {
log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId,
oldResourceRes.right().value());
- responseWrapper.setInnerElement(componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(oldResourceRes.right().value())));
- return null;
+ throw new StorageException(oldResourceRes.right().value());
}
return oldResourceRes.left().value();
}
@@ -517,216 +386,128 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
resource.setName(oldRresource.getName());
resource.setIcon(oldRresource.getIcon());
resource.setTags(oldRresource.getTags());
- resource.setVendorName(oldRresource.getVendorName());
resource.setCategories(oldRresource.getCategories());
resource.setDerivedFrom(oldRresource.getDerivedFrom());
}
- private Either<Resource, ResponseFormat> updateResourceFromCsar(Resource oldRresource, Resource newRresource,
- User user, AuditingActionEnum updateResource, boolean inTransaction,
- Either<Map<String, byte[]>, StorageOperationStatus> csarUIPayload, String csarUUID) {
-
- // check state
- if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.equals(oldRresource.getLifecycleState())) {
- if (!oldRresource.getLastUpdaterUserId().equals(user.getUserId())) {
- log.debug("Current user is not last updater, last updater userId: {}, current user userId: {}",
- oldRresource.getLastUpdaterUserId(), user.getUserId());
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
- }
- }
- String lockedResourceId = oldRresource.getUniqueId();
+ private Resource updateResourceFromCsar(Resource oldResource, Resource newResource,
+ User user, AuditingActionEnum updateResource, boolean inTransaction,
+ Map<String, byte[]> csarUIPayload, String csarUUID) {
+ Resource updatedResource = null;
+ validateLifecycleState(oldResource, user);
+ String lockedResourceId = oldResource.getUniqueId();
List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
-
- Either<Map<String, byte[]>, StorageOperationStatus> csar = null;
- if (csarUIPayload != null && csarUIPayload.left() != null && csarUIPayload.left().value() != null) {
- csar = csarUIPayload;
- } else {
- csar = csarOperation.getCsar(csarUUID, user);
- }
- if (csar.isRight()) {
- log.debug("Failed to get csar for casrUUID{} ", csarUUID);
- return Either.right(componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(csar.right().value())));
- }
-
- Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = validateAndParseCsar(newRresource,
- user, csarUUID, csar);
- if (toscaYamlCsarStatus.isRight()) {
- return Either.right(toscaYamlCsarStatus.right().value());
- }
- Either<String, ResponseFormat> checksum = CsarValidationUtils.getToscaYamlChecksum(csar.left().value(),
- csarUUID, componentsUtils);
- if (checksum.isRight()) {
- log.debug("Failed to calculate checksum for casrUUID{} error {} ", csarUUID, checksum.right().value());
- return Either.right(checksum.right().value());
- }
- if (!checksum.left().value().equals(
- oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition().getImportedToscaChecksum())) {
- log.debug("The checksum of main template yaml of csar with csarUUID {} is not equal to the previous one, existing checksum is {}, new one is {}.", csarUUID,
- oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition()
- .getImportedToscaChecksum(),
- checksum.left().value());
- oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition()
- .setImportedToscaChecksum(checksum.left().value());
- }
-
- Either<Boolean, ResponseFormat> lockResult = lockComponent(lockedResourceId, oldRresource,
+ CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(newResource, oldResource, user, csarUIPayload, csarUUID);
+ Either<Boolean, ResponseFormat> lockResult = lockComponent(lockedResourceId, oldResource,
"update Resource From Csar");
if (lockResult.isRight()) {
- return Either.right(lockResult.right().value());
+ throw new ComponentException(lockResult.right().value());
}
- String yamlFileName = toscaYamlCsarStatus.left().value().getKey();
- String yamlFileContents = toscaYamlCsarStatus.left().value().getValue();
- CsarInfo csarInfo = new CsarInfo(newRresource.getName(), user, csarUUID, csar.left().value(), yamlFileContents,
- true);
- Map<String, NodeTypeInfo> nodeTypesInfo = extractNodeTypesInfo(csarInfo);
- Either<Resource, ResponseFormat> result = null;
+ Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
- nodeTypesInfo, csarInfo, oldRresource);
+ nodeTypesInfo, csarInfo, oldResource);
if (findNodeTypesArtifactsToHandleRes.isRight()) {
log.debug("failed to find node types for update with artifacts during import csar {}. ",
csarInfo.getCsarUUID());
- result = Either.right(findNodeTypesArtifactsToHandleRes.right().value());
- return result;
+ throw new ComponentException(findNodeTypesArtifactsToHandleRes.right().value());
}
Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes
.left().value();
try {
- result = updateResourceFromYaml(oldRresource, newRresource, updateResource, createdArtifacts, yamlFileName,
- yamlFileContents, csarInfo, nodeTypesInfo, nodeTypesArtifactsToHandle, null, false);
+ updatedResource = updateResourceFromYaml(oldResource, newResource, updateResource, createdArtifacts, csarInfo.getMainTemplateName(),
+ csarInfo.getMainTemplateContent(), csarInfo, nodeTypesInfo, nodeTypesArtifactsToHandle, null, false);
- } finally {
- if (result == null || result.isRight()) {
- log.warn("operation failed. do rollback");
- titanDao.rollback();
- } else {
- log.debug("operation success. do commit");
- titanDao.commit();
- }
+ connectUiRelations(oldResource, updatedResource);
+
+ } catch (ComponentException|StorageException e){
+ rollback(inTransaction, newResource, createdArtifacts, null);
+ throw e;
+ }
+ finally {
+ titanDao.commit();
log.debug("unlock resource {}", lockedResourceId);
graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
}
- return result;
+ return updatedResource;
}
- private Either<Resource, ResponseFormat> updateResourceFromYaml(Resource oldRresource, Resource newRresource,
- AuditingActionEnum updateResource, List<ArtifactDefinition> createdArtifacts,
- String yamlFileName, String yamlFileContent, CsarInfo csarInfo, Map<String, NodeTypeInfo> nodeTypesInfo,
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
- String nodeName, boolean isNested) {
- Either<Resource, ResponseFormat> result;
- Either<Map<String, Resource>, ResponseFormat> parseNodeTypeInfoYamlEither;
- boolean inTransaction = true;
- boolean shouldLock = false;
-
- Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> prepareForUpdate;
- Resource preparedResource;
- Either<ParsedToscaYamlInfo, ResponseFormat> uploadComponentInstanceInfoMap = parseResourceInfoFromYaml(
- yamlFileName, newRresource, yamlFileContent, csarInfo.getCreatedNodesToscaResourceNames(),
- nodeTypesInfo, nodeName);
- if (uploadComponentInstanceInfoMap.isRight()) {
- ResponseFormat responseFormat = uploadComponentInstanceInfoMap.right().value();
- componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), newRresource, updateResource);
- result = Either.right(responseFormat);
- return result;
+ private void validateLifecycleState(Resource oldResource, User user) {
+ if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.equals(oldResource.getLifecycleState()) &&
+ !oldResource.getLastUpdaterUserId().equals(user.getUserId())) {
+ log.debug("#validateLifecycleState - Current user is not last updater, last updater userId: {}, current user userId: {}",
+ oldResource.getLastUpdaterUserId(), user.getUserId());
+ throw new ComponentException(ActionStatus.RESTRICTED_OPERATION);
}
+ }
- Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.left().value()
- .getInstances();
+ private Either<Resource, ResponseFormat> connectUiRelations(Resource oldResource, Resource newResource) {
+ Either<Resource, ResponseFormat> result;
- prepareForUpdate = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(),
- inTransaction, shouldLock, isNested);
- if (prepareForUpdate.isRight()) {
- log.debug("Failed to prepare resource for update : {}", prepareForUpdate.right().value());
- result = Either.right(prepareForUpdate.right().value());
- return result;
- }
- preparedResource = prepareForUpdate.left().value().left;
+ List<RequirementCapabilityRelDef> updatedUiRelations = mergeInstanceUtils.updateUiRelationsInResource(oldResource, newResource);
- log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent);
+ StorageOperationStatus status = toscaOperationFacade.associateResourceInstances(newResource.getUniqueId(), updatedUiRelations);
+ if (status == StorageOperationStatus.OK) {
+ newResource.getComponentInstancesRelations().addAll(updatedUiRelations);
+ result = Either.left(newResource);
+ } else {
+ result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status), newResource));
+ }
- Either<Resource, ResponseFormat> genericResourceEither = handleResourceGenericType(preparedResource);
- if (genericResourceEither.isRight()) {
- log.debug("failed to get resource generic type. status is {}", genericResourceEither.right().value());
- ResponseFormat responseFormat = genericResourceEither.right().value();
- componentsUtils.auditResource(genericResourceEither.right().value(), csarInfo.getModifier(),
- preparedResource, updateResource);
- return Either.right(responseFormat);
- }
+ return result;
+ }
- parseNodeTypeInfoYamlEither = this.handleNodeTypes(yamlFileName, preparedResource, yamlFileContent,
+ private Resource updateResourceFromYaml(Resource oldRresource, Resource newRresource,
+ AuditingActionEnum actionEnum, List<ArtifactDefinition> createdArtifacts,
+ String yamlFileName, String yamlFileContent, CsarInfo csarInfo, Map<String, NodeTypeInfo> nodeTypesInfo,
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
+ String nodeName, boolean isNested) {
+ boolean inTransaction = true;
+ boolean shouldLock = false;
+ Resource preparedResource = null;
+ ParsedToscaYamlInfo uploadComponentInstanceInfoMap = null;
+ try {
+ uploadComponentInstanceInfoMap = csarBusinessLogic.getParsedToscaYamlInfo(yamlFileContent, yamlFileName, nodeTypesInfo, csarInfo, nodeName);
+ Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.getInstances();
+ preparedResource = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(),
+ inTransaction, shouldLock, isNested).left;
+ log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent);
+ handleResourceGenericType(preparedResource);
+ handleNodeTypes(yamlFileName, preparedResource, yamlFileContent,
shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo, csarInfo, nodeName);
- if (parseNodeTypeInfoYamlEither.isRight()) {
- ResponseFormat responseFormat = parseNodeTypeInfoYamlEither.right().value();
- componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource, updateResource);
- result = Either.right(responseFormat);
- return result;
- }
-
- Map<String, InputDefinition> inputs = uploadComponentInstanceInfoMap.left().value().getInputs();
- Either<Resource, ResponseFormat> createInputsOnResource = createInputsOnResource(preparedResource,
- csarInfo.getModifier(), inputs, inTransaction);
- if (createInputsOnResource.isRight()) {
- log.debug("failed to create resource inputs status is {}", createInputsOnResource.right().value());
- ResponseFormat responseFormat = createInputsOnResource.right().value();
- componentsUtils.auditResource(createInputsOnResource.right().value(), csarInfo.getModifier(),
- preparedResource, updateResource);
- result = Either.right(responseFormat);
- return result;
- }
- preparedResource = createInputsOnResource.left().value();
-
- Either<Resource, ResponseFormat> createResourcesInstancesEither = createResourceInstances(
- csarInfo.getModifier(), yamlFileName, preparedResource, instances, inTransaction, shouldLock,
- csarInfo.getCreatedNodes());
- if (createResourcesInstancesEither.isRight()) {
- log.debug("failed to create resource instances status is {}",
- createResourcesInstancesEither.right().value());
- ResponseFormat responseFormat = createResourcesInstancesEither.right().value();
- componentsUtils.auditResource(createResourcesInstancesEither.right().value(), csarInfo.getModifier(),
- preparedResource, updateResource);
- result = Either.right(responseFormat);
- return result;
- }
- preparedResource = createResourcesInstancesEither.left().value();
-
- createResourcesInstancesEither = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName,
- preparedResource, instances);
- if (createResourcesInstancesEither.isRight()) {
- log.debug("failed to create relation between resource instances status is {}",
- createResourcesInstancesEither.right().value());
- result = Either.right(createResourcesInstancesEither.right().value());
- return result;
- }
-
- preparedResource = createResourcesInstancesEither.left().value();
-
- Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
- .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.left().value().getGroups(),
- preparedResource.getSystemName());
- if (validateUpdateVfGroupNamesRes.isRight()) {
-
- return Either.right(validateUpdateVfGroupNamesRes.right().value());
- }
- // add groups to resource
- Map<String, GroupDefinition> groups;
-
- if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
- groups = validateUpdateVfGroupNamesRes.left().value();
- } else {
- groups = uploadComponentInstanceInfoMap.left().value().getGroups();
- }
- Either<Resource, ResponseFormat> updatedGroupsOnResource = updateGroupsOnResource(preparedResource,
- csarInfo.getModifier(), groups);
- if (updatedGroupsOnResource.isRight()) {
-
- return updatedGroupsOnResource;
- }
- preparedResource = updatedGroupsOnResource.left().value();
-
+ preparedResource = createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs());
+ preparedResource = createResourceInstances(yamlFileName, preparedResource, instances, csarInfo.getCreatedNodes());
+ preparedResource = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, instances);
+ } catch (ComponentException e) {
+ ResponseFormat responseFormat = e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
+ log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat);
+ componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum);
+ throw e;
+ } catch (StorageException e){
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
+ log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat);
+ componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum);
+ throw e;
+ }
+ Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
+ .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.getGroups(),
+ preparedResource.getSystemName());
+ if (validateUpdateVfGroupNamesRes.isRight()) {
+
+ throw new ComponentException(validateUpdateVfGroupNamesRes.right().value());
+ }
+ // add groups to resource
+ Map<String, GroupDefinition> groups;
+
+ if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
+ groups = validateUpdateVfGroupNamesRes.left().value();
+ } else {
+ groups = uploadComponentInstanceInfoMap.getGroups();
+ }
+ handleGroupsProperties(preparedResource, groups);
+ preparedResource = updateGroupsOnResource(preparedResource, groups);
NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
nodeTypesArtifactsToHandle);
@@ -734,25 +515,18 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
if (updateArtifactsEither.isRight()) {
log.debug("failed to update artifacts {}", updateArtifactsEither.right().value());
- result = Either.right(updateArtifactsEither.right().value());
- return result;
+ throw new ComponentException(updateArtifactsEither.right().value());
}
- preparedResource = updateArtifactsEither.left().value();
+ preparedResource = getResourceWithGroups(updateArtifactsEither.left().value().getUniqueId());
- ActionStatus mergingPropsAndInputsStatus = mergeResourceEntities(oldRresource, preparedResource);
+ ActionStatus mergingPropsAndInputsStatus = resourceDataMergeBusinessLogic.mergeResourceEntities(oldRresource, preparedResource);
if (mergingPropsAndInputsStatus != ActionStatus.OK) {
ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus,
preparedResource);
- return Either.right(responseFormat);
+ throw new ComponentException(responseFormat);
}
-
- Either<List<ComponentInstance>, ResponseFormat> eitherSetPosition = compositionBusinessLogic
- .setPositionsForComponentInstances(preparedResource, csarInfo.getModifier().getUserId());
- result = eitherSetPosition.isRight() ? Either.right(eitherSetPosition.right().value())
- : Either.left(preparedResource);
-
- return result;
-
+ compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier().getUserId());
+ return preparedResource;
}
private Either<Resource, ResponseFormat> createOrUpdateArtifacts(ArtifactOperationEnum operation, List<ArtifactDefinition> createdArtifacts,
@@ -785,100 +559,30 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(resource);
}
- private ActionStatus mergeResourceEntities(Resource oldResource, Resource newResource) {
- Either<MergeResourceBusinessLogic, ActionStatus> mergeResourceBLEither = mergeResourceBLFactory
- .getInstance(oldResource, newResource);
- if (mergeResourceBLEither.isRight()) {
- return mergeResourceBLEither.right().value();
- }
- MergeResourceBusinessLogic mergeResourceBusinessLogic = mergeResourceBLEither.left().value();
- return mergeResourceBusinessLogic.mergeResourceEntities(oldResource, newResource);
- }
-
- private Either<Resource, ResponseFormat> handleResourceGenericType(Resource resource) {
- Either<Resource, ResponseFormat> genericResourceEither = fetchAndSetDerivedFromGenericType(resource);
- if (genericResourceEither.isRight()) {
- return genericResourceEither;
- }
+ private Resource handleResourceGenericType(Resource resource) {
+ Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
if (resource.shouldGenerateInputs()) {
- generateAndAddInputsFromGenericTypeProperties(resource, genericResourceEither.left().value());
+ generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
}
- return genericResourceEither;
+ return genericResource;
}
private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(
Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Resource oldResource) {
- Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils
- .extractVfcsArtifactsFromCsar(csarInfo.getCsar());
Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
- Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes;
+ Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes
+ = Either.left(nodeTypesArtifactsToHandle);
try {
- nodeTypesArtifactsToHandleRes = Either.left(nodeTypesArtifactsToHandle);
- Map<String, ImmutablePair<String, String>> extractedVfcToscaNames = extractVfcToscaNames(nodeTypesInfo,
- oldResource.getName(), csarInfo);
- Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> curNodeTypeArtifactsToHandleRes;
- EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
+ Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csarInfo.getCsar());
+ Map<String, ImmutablePair<String, String>> extractedVfcToscaNames =
+ extractVfcToscaNames(nodeTypesInfo, oldResource.getName(), csarInfo);
log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ",
oldResource.getName(), csarInfo.getCsarUUID());
-
- for (Entry<String, ImmutablePair<String, String>> currVfcToscaNameEntry : extractedVfcToscaNames
- .entrySet()) {
- String currVfcToscaName = currVfcToscaNameEntry.getValue().getLeft();
- String previousVfcToscaName = currVfcToscaNameEntry.getValue().getRight();
- String currNamespace = currVfcToscaNameEntry.getKey();
- log.debug("Going to fetch node type with tosca name {}. ", currVfcToscaName);
-
- Either<Resource, StorageOperationStatus> curVfcRes = toscaOperationFacade
- .getLatestByToscaResourceName(currVfcToscaName);
- Resource curNodeType = null;
- if (curVfcRes.isRight() && curVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
- curVfcRes = toscaOperationFacade.getLatestByToscaResourceName(previousVfcToscaName);
- }
- if (curVfcRes.isRight() && curVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
- log.debug("Error occured during fetching node type with tosca name {}, error: {}", currVfcToscaName,
- curVfcRes.right().value());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(
- componentsUtils.convertFromStorageResponse(curVfcRes.right().value()),
- csarInfo.getCsarUUID());
- componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), oldResource, AuditingActionEnum.CREATE_RESOURCE);
- nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
- break;
- } else if (curVfcRes.isLeft()) {
- curNodeType = curVfcRes.left().value();
- }
- if (!MapUtils.isEmpty(extractedVfcsArtifacts)) {
- List<ArtifactDefinition> currArtifacts = new ArrayList<>();
- if (extractedVfcsArtifacts.containsKey(currNamespace)) {
- handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(currNamespace));
- }
- curNodeTypeArtifactsToHandleRes = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
- if (curNodeTypeArtifactsToHandleRes.isRight()) {
- nodeTypesArtifactsToHandleRes = Either.right(curNodeTypeArtifactsToHandleRes.right().value());
- break;
- }
- curNodeTypeArtifactsToHandle = curNodeTypeArtifactsToHandleRes.left().value();
-
- } else if (curNodeType != null) {
- // delete all artifacts if have not received artifacts from
- // csar
- curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
- List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
- // delete all informational artifacts
- artifactsToDelete.addAll(curNodeType.getArtifacts().values().stream()
- .filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
- .collect(Collectors.toList()));
- // delete all deployment artifacts
- artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values());
- if (!artifactsToDelete.isEmpty()) {
- curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
- }
- }
- if (MapUtils.isNotEmpty(curNodeTypeArtifactsToHandle)) {
- nodeTypesArtifactsToHandle.put(currVfcToscaNameEntry.getKey(), curNodeTypeArtifactsToHandle);
- }
- }
+ extractedVfcToscaNames.forEach((namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo, nodeTypesArtifactsToHandle, oldResource,
+ extractedVfcsArtifacts,
+ namespace, vfcToscaNames));
} catch (Exception e) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
@@ -887,86 +591,142 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return nodeTypesArtifactsToHandleRes;
}
- private Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> findNodeTypeArtifactsToHandle(
+ private void findAddNodeTypeArtifactsToHandle(CsarInfo csarInfo, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
+ Resource resource, Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts, String namespace, ImmutablePair<String, String> vfcToscaNames){
+
+ EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
+ log.debug("Going to fetch node type with tosca name {}. ", vfcToscaNames.getLeft());
+ Resource curNodeType = findVfcResource(csarInfo, resource, vfcToscaNames.getLeft(), vfcToscaNames.getRight(), null);
+ if (!isEmpty(extractedVfcsArtifacts)) {
+ List<ArtifactDefinition> currArtifacts = new ArrayList<>();
+ if (extractedVfcsArtifacts.containsKey(namespace)) {
+ handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(namespace));
+ }
+ curNodeTypeArtifactsToHandle = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
+ } else if (curNodeType != null) {
+ // delete all artifacts if have not received artifacts from
+ // csar
+ curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
+ List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
+ // delete all informational artifacts
+ artifactsToDelete.addAll(curNodeType.getArtifacts().values().stream()
+ .filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
+ .collect(toList()));
+ // delete all deployment artifacts
+ artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values());
+ if (!artifactsToDelete.isEmpty()) {
+ curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
+ }
+ }
+ if (isNotEmpty(curNodeTypeArtifactsToHandle)) {
+ nodeTypesArtifactsToHandle.put(namespace, curNodeTypeArtifactsToHandle);
+ }
+ }
+
+ private Resource findVfcResource(CsarInfo csarInfo, Resource resource, String currVfcToscaName, String previousVfcToscaName, StorageOperationStatus status) {
+ if (status != null && status != StorageOperationStatus.NOT_FOUND) {
+ log.debug("Error occured during fetching node type with tosca name {}, error: {}", currVfcToscaName, status);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
+ componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.CREATE_RESOURCE);
+ throw new ComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
+ } else if (StringUtils.isNotEmpty(currVfcToscaName)) {
+ return (Resource)toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName)
+ .left()
+ .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st));
+ }
+ return null;
+ }
+
+ private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> findNodeTypeArtifactsToHandle(
Resource curNodeType, List<ArtifactDefinition> extractedArtifacts) {
- Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> nodeTypeArtifactsToHandleRes = null;
EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
- Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
try {
List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
- if (curNodeType != null) {
- Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>();
- if (curNodeType.getDeploymentArtifacts() != null) {
- existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
- }
- if (curNodeType.getArtifacts() != null) {
- existingArtifacts
- .putAll(curNodeType.getArtifacts().entrySet().stream()
- .filter(e -> e.getValue()
- .getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
- .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())));
- }
- for (ArtifactDefinition currNewArtifact : extractedArtifacts) {
- ArtifactDefinition foundArtifact;
-
- if (!existingArtifacts.isEmpty()) {
- foundArtifact = existingArtifacts.values().stream()
- .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst()
- .orElse(null);
- if (foundArtifact != null) {
- if (foundArtifact.getArtifactType().equals(currNewArtifact.getArtifactType())) {
- if (!foundArtifact.getArtifactChecksum()
- .equals(currNewArtifact.getArtifactChecksum())) {
- foundArtifact.setPayload(currNewArtifact.getPayloadData());
- foundArtifact.setPayloadData(
- Base64.encodeBase64String(currNewArtifact.getPayloadData()));
- foundArtifact.setArtifactChecksum(GeneralUtility
- .calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
- artifactsToUpdate.add(foundArtifact);
- }
- existingArtifacts.remove(foundArtifact.getArtifactLabel());
- artifactsToUpload.remove(currNewArtifact);
- } else {
- log.debug("Can't upload two artifact with the same name {}.",
- currNewArtifact.getArtifactName());
- ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(
- ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
- currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(),
- foundArtifact.getArtifactType());
- responseWrapper.setInnerElement(responseFormat);
- break;
- }
- }
- }
- }
- if (responseWrapper.isEmpty()) {
- artifactsToDelete.addAll(existingArtifacts.values());
- }
+ processExistingNodeTypeArtifacts(extractedArtifacts, artifactsToUpload, artifactsToUpdate, artifactsToDelete,
+ collectExistingArtifacts(curNodeType));
+ nodeTypeArtifactsToHandle = putFoundArtifacts(artifactsToUpload, artifactsToUpdate, artifactsToDelete);
+ } catch (Exception e) {
+ log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
+ throw new ComponentException(ActionStatus.GENERAL_ERROR);
+ }
+ return nodeTypeArtifactsToHandle;
+ }
+
+ private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> putFoundArtifacts(List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete) {
+ EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
+ if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
+ nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
+ if (!artifactsToUpload.isEmpty()) {
+ nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
}
- if (responseWrapper.isEmpty()) {
- if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
- nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
- if (!artifactsToUpload.isEmpty())
- nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
- if (!artifactsToUpdate.isEmpty())
- nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
- if (!artifactsToDelete.isEmpty())
- nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
- }
- nodeTypeArtifactsToHandleRes = Either.left(nodeTypeArtifactsToHandle);
+ if (!artifactsToUpdate.isEmpty()) {
+ nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
}
- if (!responseWrapper.isEmpty()) {
- nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
+ if (!artifactsToDelete.isEmpty()) {
+ nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
}
- } catch (Exception e) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- responseWrapper.setInnerElement(responseFormat);
- log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
}
- return nodeTypeArtifactsToHandleRes;
+ return nodeTypeArtifactsToHandle;
+ }
+
+ private void processExistingNodeTypeArtifacts(List<ArtifactDefinition> extractedArtifacts, List<ArtifactDefinition> artifactsToUpload,
+ List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete,
+ Map<String, ArtifactDefinition> existingArtifacts) {
+ if (!existingArtifacts.isEmpty()) {
+ extractedArtifacts.stream().forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a));
+ artifactsToDelete.addAll(existingArtifacts.values());
+ }
+ }
+
+ 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();
+ if (foundArtifact.isPresent()) {
+ if (foundArtifact.get().getArtifactType().equals(currNewArtifact.getArtifactType())) {
+ updateFoundArtifact(artifactsToUpdate, currNewArtifact, foundArtifact.get());
+ existingArtifacts.remove(foundArtifact.get().getArtifactLabel());
+ artifactsToUpload.remove(currNewArtifact);
+ } else {
+ log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
+ throw new ComponentException(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
+ currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(),
+ foundArtifact.get().getArtifactType());
+ }
+ }
+ }
+
+ private void updateFoundArtifact(List<ArtifactDefinition> artifactsToUpdate, ArtifactDefinition currNewArtifact, ArtifactDefinition foundArtifact) {
+ if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
+ foundArtifact.setPayload(currNewArtifact.getPayloadData());
+ foundArtifact.setPayloadData(
+ Base64.encodeBase64String(currNewArtifact.getPayloadData()));
+ foundArtifact.setArtifactChecksum(GeneralUtility
+ .calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
+ artifactsToUpdate.add(foundArtifact);
+ }
+ }
+
+ private Map<String, ArtifactDefinition> collectExistingArtifacts(Resource curNodeType) {
+ Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>();
+ if (curNodeType == null) {
+ return existingArtifacts;
+ }
+ if (MapUtils.isNotEmpty(curNodeType.getDeploymentArtifacts())) {
+ existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
+ }
+ 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)));
+ }
+ return existingArtifacts;
}
/**
@@ -987,7 +747,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
resource.getName());
Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(
resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
- new LifecycleChangeInfoWithAction("certification on import",
+ new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
LifecycleChanceActionEnum.CREATE_FROM_CSAR),
inTransaction, true);
if (checkoutRes.isRight()) {
@@ -1099,216 +859,42 @@ 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, ToscaTagNamesEnum.NODE_TYPES);
+ .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
if (eitherNodeTypes.isLeft()) {
nodes.putAll(eitherNodeTypes.left().value());
}
}
- public Either<Resource, ResponseFormat> createResourceFromCsar(Resource resource, User user,
- Either<Map<String, byte[]>, StorageOperationStatus> csarUIPayload, String csarUUID) {
+ public Resource createResourceFromCsar(Resource resource, User user,
+ Map<String, byte[]> csarUIPayload, String csarUUID) {
log.trace("************* created successfully from YAML, resource TOSCA ");
- Either<Map<String, byte[]>, StorageOperationStatus> csar = null;
- if (csarUIPayload != null && csarUIPayload.left() != null && csarUIPayload.left().value() != null) {
- csar = csarUIPayload;
- } else {
- csar = csarOperation.getCsar(csarUUID, user);
- }
-
- Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = validateAndParseCsar(resource, user,
- csarUUID, csar);
- if (toscaYamlCsarStatus.isRight()) {
- return Either.right(toscaYamlCsarStatus.right().value());
- }
- Either<String, ResponseFormat> toscaYamlChecksum = CsarValidationUtils.getToscaYamlChecksum(csar.left().value(),
- csarUUID, componentsUtils);
- if (toscaYamlChecksum.isRight()) {
- log.debug("Failed to calculate checksum for CSAR {}, error {}", csarUUID,
- toscaYamlChecksum.right().value());
- return Either.right(toscaYamlChecksum.right().value());
- }
- resource.getComponentMetadataDefinition().getMetadataDataDefinition()
- .setImportedToscaChecksum(toscaYamlChecksum.left().value());
-
- String yamlFileName = toscaYamlCsarStatus.left().value().getKey();
- String yamlFileContents = toscaYamlCsarStatus.left().value().getValue();
- log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContents);
+ CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(resource, null, user, csarUIPayload, csarUUID);
- CsarInfo csarInfo = new CsarInfo(resource.getName(), user, csarUUID, csar.left().value(), yamlFileContents,
- false);
- Map<String, NodeTypeInfo> nodeTypesInfo = extractNodeTypesInfo(csarInfo);
+ Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
nodeTypesInfo, csarInfo, resource);
if (findNodeTypesArtifactsToHandleRes.isRight()) {
log.debug("failed to find node types for update with artifacts during import csar {}. ",
csarInfo.getCsarUUID());
- return Either.right(findNodeTypesArtifactsToHandleRes.right().value());
+ throw new ComponentException(findNodeTypesArtifactsToHandleRes.right().value());
}
- Either<Resource, ResponseFormat> createResourceFromYaml = createResourceFromYaml(resource, yamlFileContents,
- yamlFileName, nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left().value(), true, false,
+ Resource vfResource = createResourceFromYaml(resource, csarInfo.getMainTemplateContent(), csarInfo.getMainTemplateName(),
+ nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left().value(), true, false,
null);
- if (createResourceFromYaml.isRight()) {
- log.debug("Couldn't create resource from YAML");
- return Either.right(createResourceFromYaml.right().value());
- }
-
- Resource vfResource = createResourceFromYaml.left().value();
log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}",
vfResource.getToscaResourceName());
- return Either.left(vfResource);
- }
-
- private Map<String, NodeTypeInfo> extractNodeTypesInfo(CsarInfo csarInfo) {
- Map<String, NodeTypeInfo> nodeTypesInfo = new HashMap<>();
- List<Entry<String, byte[]>> globalSubstitutes = new ArrayList<>();
- for (Map.Entry<String, byte[]> entry : csarInfo.getCsar().entrySet()) {
- extractNodeTypeInfo(nodeTypesInfo, globalSubstitutes, entry);
- }
- if (CollectionUtils.isNotEmpty(globalSubstitutes)) {
- setDerivedFrom(nodeTypesInfo, globalSubstitutes);
- }
- markNestedVfc(csarInfo.getMappedToscaMainTemplate(), nodeTypesInfo);
- return nodeTypesInfo;
- }
-
- @SuppressWarnings("unchecked")
- private void setDerivedFrom(Map<String, NodeTypeInfo> nodeTypesInfo,
- List<Entry<String, byte[]>> globalSubstitutes) {
- for (Map.Entry<String, byte[]> entry : globalSubstitutes) {
- String yamlFileContents = new String(entry.getValue());
- Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(yamlFileContents);
- Either<Object, ResultStatusEnum> nodeTypesEither = ImportUtils.findToscaElement(mappedToscaTemplate,
- ToscaTagNamesEnum.NODE_TYPES, ToscaElementTypeEnum.MAP);
- if (nodeTypesEither.isLeft()) {
- Map<String, Object> nodeTypes = (Map<String, Object>) nodeTypesEither.left().value();
- for (Entry<String, Object> nodeType : nodeTypes.entrySet()) {
- Map<String, Object> nodeTypeMap = (Map<String, Object>) nodeType.getValue();
- if (nodeTypeMap.containsKey(ToscaTagNamesEnum.DERIVED_FROM.getElementName())) {
- if (nodeTypesInfo.containsKey(nodeType.getKey())) {
- NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(nodeType.getKey());
- List<String> derivedFrom = new ArrayList<>();
- derivedFrom.add((String) nodeTypeMap.get(ToscaTagNamesEnum.DERIVED_FROM.getElementName()));
- nodeTypeInfo.setDerivedFrom(derivedFrom);
- }
- }
- }
- }
- }
- }
-
- @SuppressWarnings("unchecked")
- private void extractNodeTypeInfo(Map<String, NodeTypeInfo> nodeTypesInfo,
- List<Entry<String, byte[]>> globalSubstitutes, Map.Entry<String, byte[]> entry) {
- if (Pattern.compile(CsarUtils.SERVICE_TEMPLATE_PATH_PATTERN).matcher(entry.getKey()).matches()) {
- if (!isGlobalSubstitute(entry.getKey())) {
- String yamlFileContents = new String(entry.getValue());
- Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(yamlFileContents);
- Either<Object, ResultStatusEnum> substitutionMappingsEither = ImportUtils.findToscaElement(
- mappedToscaTemplate, ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS, ToscaElementTypeEnum.MAP);
- if (substitutionMappingsEither.isLeft()) {
- Map<String, Object> substitutionMappings = (Map<String, Object>) substitutionMappingsEither.left()
- .value();
- if (substitutionMappings.containsKey(ToscaTagNamesEnum.NODE_TYPE.getElementName())) {
- NodeTypeInfo nodeTypeInfo = new NodeTypeInfo();
- nodeTypeInfo.setType(
- (String) substitutionMappings.get(ToscaTagNamesEnum.NODE_TYPE.getElementName()));
- nodeTypeInfo.setTemplateFileName(entry.getKey());
- nodeTypeInfo.setMappedToscaTemplate(mappedToscaTemplate);
- nodeTypesInfo.put(nodeTypeInfo.getType(), nodeTypeInfo);
- }
- }
- } else {
- globalSubstitutes.add(entry);
- }
- }
- }
-
- @SuppressWarnings("unchecked")
- private void markNestedVfc(Map<String, Object> mappedToscaTemplate, Map<String, NodeTypeInfo> nodeTypesInfo) {
- Either<Object, ResultStatusEnum> nodeTemplatesEither = ImportUtils.findToscaElement(mappedToscaTemplate,
- ToscaTagNamesEnum.NODE_TEMPLATES, ToscaElementTypeEnum.MAP);
- if (nodeTemplatesEither.isLeft()) {
- Map<String, Object> nodeTemplates = (Map<String, Object>) nodeTemplatesEither.left().value();
- for (Entry<String, Object> nodeTemplateEntry : nodeTemplates.entrySet()) {
- Map<String, Object> nodeTemplate = (Map<String, Object>) nodeTemplateEntry.getValue();
- if (nodeTemplate.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
- String type = (String) nodeTemplate.get(ToscaTagNamesEnum.TYPE.getElementName());
- if (nodeTypesInfo.containsKey(type)) {
- NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(type);
- nodeTypeInfo.setNested(true);
- }
- }
- }
- }
- }
-
- private boolean isGlobalSubstitute(String fileName) {
- return fileName.equalsIgnoreCase(Constants.GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE)
- || fileName.equalsIgnoreCase(Constants.ABSTRACT_SUBSTITUTE_GLOBAL_TYPES_SERVICE_TEMPLATE);
+ return vfResource;
}
- private Either<ImmutablePair<String, String>, ResponseFormat> validateAndParseCsar(Resource resource, User user,
- String csarUUID, Either<Map<String, byte[]>, StorageOperationStatus> csar) {
- if (csar.isRight()) {
- StorageOperationStatus value = csar.right().value();
- log.debug("Error when fetching csar with ID {}, error: {}", csarUUID, value);
- BeEcompErrorManager.getInstance()
- .logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
- ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(value), csarUUID);
- componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.CREATE_RESOURCE);
- return Either.right(responseFormat);
- }
-
- Either<Boolean, ResponseFormat> validateCsarStatus = CsarValidationUtils.validateCsar(csar.left().value(),
- csarUUID, componentsUtils);
- if (validateCsarStatus.isRight()) {
- ResponseFormat responseFormat = validateCsarStatus.right().value();
- log.debug("Error when validate csar with ID {}, error: {}", csarUUID, responseFormat);
- BeEcompErrorManager.getInstance()
- .logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
- componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.CREATE_RESOURCE);
- return Either.right(responseFormat);
- }
-
- Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = CsarValidationUtils
- .getToscaYaml(csar.left().value(), csarUUID, componentsUtils);
-
- if (toscaYamlCsarStatus.isRight()) {
- ResponseFormat responseFormat = toscaYamlCsarStatus.right().value();
- log.debug("Error when try to get csar toscayamlFile with csar ID {}, error: {}", csarUUID, responseFormat);
- BeEcompErrorManager.getInstance()
- .logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
- componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.CREATE_RESOURCE);
- return Either.right(responseFormat);
- }
- return toscaYamlCsarStatus;
- }
-
- private Either<Resource, ResponseFormat> validateResourceBeforeCreate(Resource resource, User user,
- boolean inTransaction) {
+ private Resource validateResourceBeforeCreate(Resource resource, User user, boolean inTransaction) {
log.trace("validating resource before create");
- Either<User, ResponseFormat> eitherCreator = validateUser(user, "Create Resource", resource,
- AuditingActionEnum.CREATE_RESOURCE, false);
- if (eitherCreator.isRight()) {
- return Either.right(eitherCreator.right().value());
- }
- user.copyData(eitherCreator.left().value());
-
+ user.copyData(validateUser(user, CREATE_RESOURCE, resource, AuditingActionEnum.CREATE_RESOURCE, false));
// validate user role
- Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, resource, new ArrayList<Role>(),
- AuditingActionEnum.CREATE_RESOURCE, null);
- if (validateRes.isRight()) {
- return Either.right(validateRes.right().value());
- }
+ validateUserRole(user, resource, new ArrayList<>(), AuditingActionEnum.CREATE_RESOURCE, null);
// VF / PNF "derivedFrom" should be null (or ignored)
if (ModelConverter.isAtomicComponent(resource)) {
- Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty = validateDerivedFromNotEmpty(user, resource,
- AuditingActionEnum.CREATE_RESOURCE);
- if (validateDerivedFromNotEmpty.isRight()) {
- return Either.right(validateDerivedFromNotEmpty.right().value());
- }
+ validateDerivedFromNotEmpty(user, resource, AuditingActionEnum.CREATE_RESOURCE);
}
return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction, null);
@@ -1316,239 +902,180 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
// resource, yamlFileContents, yamlFileName, nodeTypesInfo,csarInfo,
// nodeTypesArtifactsToCreate, true, false, null
- private Either<Resource, ResponseFormat> createResourceFromYaml(Resource resource, String topologyTemplateYaml,
- String yamlName, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
- boolean shouldLock, boolean inTransaction, String nodeName) {
-
- List<ArtifactDefinition> createdArtifacts = new ArrayList<ArtifactDefinition>();
- log.trace("************* createResourceFromYaml before parse yaml ");
- Either<ParsedToscaYamlInfo, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceInfoFromYaml(
- yamlName, resource, topologyTemplateYaml, csarInfo.getCreatedNodesToscaResourceNames(), nodeTypesInfo,
- nodeName);
- if (parseResourceInfoFromYamlEither.isRight()) {
- ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value();
+ private Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml,
+ String yamlName, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
+ boolean shouldLock, boolean inTransaction, String nodeName) {
+
+ List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
+ Resource createdResource;
+ try{
+ ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic.getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName);
+ log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", resource.getName());
+ createdResource = createResourceAndRIsFromYaml(yamlName, resource,
+ parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml,
+ nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
+ log.debug("#createResourceFromYaml - The resource {} has been created ", resource.getName());
+ } catch (ComponentException e) {
+ ResponseFormat responseFormat = e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
- return Either.right(responseFormat);
- }
- log.trace("************* createResourceFromYaml after parse yaml ");
- ParsedToscaYamlInfo parsedToscaYamlInfo = parseResourceInfoFromYamlEither.left().value();
- log.debug("The parsed tosca yaml info is {}", parsedToscaYamlInfo);
- log.trace("************* createResourceFromYaml before create ");
- Either<Resource, ResponseFormat> createdResourceResponse = createResourceAndRIsFromYaml(yamlName, resource,
- parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml,
- nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
- log.trace("************* createResourceFromYaml after create ");
- if (createdResourceResponse.isRight()) {
- ResponseFormat responseFormat = createdResourceResponse.right().value();
+ throw e;
+ } catch (StorageException e){
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
- return Either.right(responseFormat);
+ throw e;
}
-
- return createdResourceResponse;
+ return createdResource;
}
- public Either<Map<String, Resource>, ResponseFormat> createResourcesFromYamlNodeTypesList(String yamlName,
- Resource resource, Map<String, Object> mappedToscaTemplate, boolean needLock,
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
- List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
- CsarInfo csarInfo) {
+ public Map<String, Resource> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, Map<String, Object> mappedToscaTemplate, boolean needLock,
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
+ List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
+ CsarInfo csarInfo) {
- Either<String, ResultStatusEnum> tosca_version = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate,
- ToscaTagNamesEnum.TOSCA_VERSION);
- if (tosca_version.isRight()) {
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
- return Either.right(responseFormat);
+ Either<String, ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate,
+ TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
+ if (toscaVersion.isRight()) {
+ throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE);
}
- Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils
- .findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES);
- Either<Map<String, Resource>, ResponseFormat> result = Either.left(csarInfo.getCreatedNodes());
- Map<String, Object> mapToConvert = new HashMap<String, Object>();
- mapToConvert.put(ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), tosca_version.left().value());
+ Map<String, Object> mapToConvert = new HashMap<>();
+ mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left().value());
+ Map<String, Object> nodeTypes = getNodeTypesFromTemplate(mappedToscaTemplate);
+ createNodeTypes(yamlName, resource, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, mapToConvert, nodeTypes);
+ return csarInfo.getCreatedNodes();
+ }
+
+ private Map<String,Object> getNodeTypesFromTemplate(Map<String, Object> mappedToscaTemplate) {
+ return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES)
+ .left().orValue(HashMap::new);
+ }
+
+ private void createNodeTypes(String yamlName, Resource resource, boolean needLock, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Map<String, Object> mapToConvert, Map<String, Object> nodeTypes) {
+ Iterator<Entry<String, Object>> nodesNameValueIter = nodeTypes.entrySet().iterator();
Resource vfcCreated = null;
- if (eitherNodeTypes.isLeft()) {
- Iterator<Entry<String, Object>> nodesNameValue = eitherNodeTypes.left().value().entrySet().iterator();
- while (nodesNameValue.hasNext()) {
- Entry<String, Object> nodeType = nodesNameValue.next();
- Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null
- || nodeTypesArtifactsToHandle.isEmpty() ? null
- : nodeTypesArtifactsToHandle.get(nodeType.getKey());
-
- if (nodeTypesInfo.containsKey(nodeType.getKey())) {
- log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
- Either<Resource, ResponseFormat> handleNeatedVfcYaml = handleNestedVfc(resource,
- nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
- nodeType.getKey());
- log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
- if (handleNeatedVfcYaml.isRight()) {
- return Either.right(handleNeatedVfcYaml.right().value());
- }
- vfcCreated = handleNeatedVfcYaml.left().value();
- } else if (csarInfo.getCreatedNodesToscaResourceNames() != null
- && !csarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())) {
- log.trace("************* Going to create node {}", nodeType.getKey());
- Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> resourceCreated = this
- .createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert,
- resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true,
- csarInfo, true);
- log.debug("************* Finished to create node {}", nodeType.getKey());
-
- if (resourceCreated.isRight()) {
- return Either.right(resourceCreated.right().value());
- }
- vfcCreated = resourceCreated.left().value().getLeft();
- csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(),
- vfcCreated.getToscaResourceName());
- }
- if (vfcCreated != null) {
- csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated);
- }
- mapToConvert.remove(ToscaTagNamesEnum.NODE_TYPES.getElementName());
+ while (nodesNameValueIter.hasNext()) {
+ Entry<String, Object> nodeType = nodesNameValueIter.next();
+ Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = 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());
+ log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
+ } else if (csarInfo.getCreatedNodesToscaResourceNames() != null
+ && !csarInfo.getCreatedNodesToscaResourceNames().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);
+ log.debug("************* Finished to create node {}", nodeType.getKey());
+
+ vfcCreated = resourceCreated.getLeft();
+ csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(),
+ vfcCreated.getToscaResourceName());
+ }
+ if (vfcCreated != null) {
+ csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated);
}
+ mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName());
}
- return result;
}
- private Either<Resource, ResponseFormat> handleNestedVfc(Resource resource,
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
- List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
- String nodeName) {
+ private Resource handleNestedVfc(Resource resource, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
+ List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
+ String nodeName) {
- Either<Resource, ResponseFormat> handleNestedVfcRes = Either.left(resource);
String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
log.debug("************* Going to create node types from yaml {}", yamlName);
- Either<Map<String, Resource>, ResponseFormat> createNodeTypesRes = createResourcesFromYamlNodeTypesList(
- yamlName, resource, nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
- csarInfo);
- if (createNodeTypesRes.isRight()) {
- log.debug("Failed to create node types from yaml {}. Status is {}", yamlName,
- createNodeTypesRes.right().value());
- return Either.right(createNodeTypesRes.right().value());
- }
+ createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false,
+ nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo);
log.debug("************* Finished to create node types from yaml {}", yamlName);
- if (nestedVfcJsonMap.containsKey(ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
+ if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
- handleNestedVfcRes = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
+ resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
csarInfo, nodeName, yamlName);
}
- return handleNestedVfcRes;
+ return resource;
}
- private Either<Resource, ResponseFormat> handleComplexVfc(Resource resource,
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
- List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
- String nodeName, String yamlName) {
+ private Resource handleComplexVfc(Resource resource, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
+ List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
+ String nodeName, String yamlName) {
- Either<Resource, ResponseFormat> result = null;
Resource oldComplexVfc = null;
- Resource newComplexVfc = null;
-
- Either<Resource, ResponseFormat> buildCvfcRes = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo);
- if (buildCvfcRes.isRight()) {
- log.debug("Failed to validate complex VFC for node {}. ", nodeName);
- result = buildCvfcRes;
- }
- if (result == null) {
- newComplexVfc = buildCvfcRes.left().value();
- Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade
- .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
- if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
- oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
- 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());
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- } else if (oldComplexVfcRes.isLeft()) {
- log.debug("validate derived before update");
- Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(
- oldComplexVfcRes.left().value(), newComplexVfc,
- ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
- if (eitherValidation.isLeft()) {
- oldComplexVfc = oldComplexVfcRes.left().value();
- }
- }
- }
- if (result == null) {
- result = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName,
- oldComplexVfc, newComplexVfc);
- }
- if (result.isLeft()) {
- newComplexVfc = result.left().value();
- csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
- LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(
- "certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR);
- log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
- result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false,
- true);
- if (result.isRight()) {
- log.debug("Failed to certify complex VFC resource {}. ", newComplexVfc.getName());
- }
- }
- if (result.isLeft()) {
- csarInfo.getCreatedNodes().put(nodeName, result.left().value());
- csarInfo.getCvfcToCreateQueue().remove();
+ Resource newComplexVfc = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo);
+ Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade
+ .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
+ if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
+ oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
+ 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());
+ throw new ComponentException(ActionStatus.GENERAL_ERROR);
+ } else if (oldComplexVfcRes.isLeft()) {
+ log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
+ Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(
+ oldComplexVfcRes.left().value(), newComplexVfc,
+ ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
+ if (eitherValidation.isLeft()) {
+ oldComplexVfc = oldComplexVfcRes.left().value();
+ }
+ }
+ newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName,
+ oldComplexVfc, newComplexVfc);
+ csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
+ LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(
+ CERTIFICATION_ON_IMPORT, LifecycleChanceActionEnum.CREATE_FROM_CSAR);
+ log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
+ Either<Resource, ResponseFormat> result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false,
+ true);
+ if (result.isRight()) {
+ log.debug("Failed to certify complex VFC resource {}. ", newComplexVfc.getName());
}
- return result;
+ csarInfo.getCreatedNodes().put(nodeName, result.left().value());
+ csarInfo.removeNodeFromQueue();
+ return result.left().value();
}
- private Either<Resource, ResponseFormat> handleComplexVfc(
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
- List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
- String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) {
+ private Resource handleComplexVfc(Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
+ List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
+ String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) {
- Either<Resource, ResponseFormat> handleComplexVfcRes;
+ Resource handleComplexVfcRes;
Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName).getMappedToscaTemplate();
String yamlContent = new String(csarInfo.getCsar().get(yamlName));
Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet().stream()
- .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().getUnmarkedCopy()));
- markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
+ .collect(toMap(Entry::getKey, e -> e.getValue().getUnmarkedCopy()));
+ CsarInfo.markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
if (oldComplexVfc == null) {
handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo,
csarInfo, nodesArtifactsToHandle, false, true, nodeName);
- if (handleComplexVfcRes.isRight()) {
- log.debug("Failed to create resource {} from YAML {}. ", newComplexVfc.getName(), yamlName);
- }
} else {
handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc,
AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, yamlContent, yamlName, csarInfo,
newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true);
- if (handleComplexVfcRes.isRight()) {
- log.debug("Failed to update resource {} from YAML {}. ", oldComplexVfc.getName(), yamlName);
- }
}
return handleComplexVfcRes;
}
- private Either<Resource, ResponseFormat> buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName,
- Map<String, NodeTypeInfo> nodesInfo) {
+ private Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName,
+ Map<String, NodeTypeInfo> nodesInfo) {
- Either<Resource, ResponseFormat> result = null;
Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo);
log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
-
- if (!csarInfo.getCvfcToCreateQueue().contains(nodeName)) {
- csarInfo.getCvfcToCreateQueue().add(nodeName);
- } else {
- log.debug("Failed to validate complex VFC {}. Loop detected, VSP {}. ", complexVfc.getName(),
- csarInfo.getVfResourceName());
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.CFVC_LOOP_DETECTED,
- csarInfo.getVfResourceName(), complexVfc.getName()));
- }
- if (result == null) {
- result = validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(),
- AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
- if (result.isRight()) {
- log.debug("Failed to validate complex VFC {}. ", complexVfc.getName());
- }
- }
- return result;
+ csarInfo.addNodeToQueue(nodeName);
+ return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(),
+ AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
}
private String getNodeTypeActualName(String fullName) {
@@ -1559,29 +1086,19 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return nameWithouNamespacePrefix.substring(resourceType.length());
}
- private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createNodeTypeResourceFromYaml(
+ private ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(
String yamlName, Entry<String, Object> nodeNameValue, User user, Map<String, Object> mapToConvert,
Resource resourceVf, boolean needLock,
Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
boolean isNested) {
- Either<UploadResourceInfo, ResponseFormat> resourceMetaData = fillResourceMetadata(yamlName, resourceVf,
- nodeNameValue.getKey(), user);
- if (resourceMetaData.isRight()) {
- return Either.right(resourceMetaData.right().value());
- }
- String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert,
- resourceMetaData.left().value().getResourceType(), csarInfo);
-
- Either<User, ResponseFormat> eitherCreator = validateUser(user, "CheckIn Resource", resourceVf,
- AuditingActionEnum.CHECKIN_RESOURCE, true);
- if (eitherCreator.isRight()) {
- return Either.right(eitherCreator.right().value());
- }
- user = eitherCreator.left().value();
+ UploadResourceInfo resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
- return this.createResourceFromNodeType(singleVfcYaml, resourceMetaData.left().value(), user, true, needLock,
+ 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);
}
@@ -1597,47 +1114,44 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Map<String, Object> node = new HashMap<>();
node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey())
.getLeft(), nodeNameValue.getValue());
- mapToConvert.put(ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
+ mapToConvert.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
return yaml.dumpAsMap(mapToConvert);
}
public Either<Boolean, ResponseFormat> validateResourceCreationFromNodeType(Resource resource, User creator) {
-
- Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty = this.validateDerivedFromNotEmpty(creator,
- resource, AuditingActionEnum.CREATE_RESOURCE);
- if (validateDerivedFromNotEmpty.isRight()) {
- return Either.right(validateDerivedFromNotEmpty.right().value());
- }
+ validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
return Either.left(true);
}
- public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResourceFromNodeType(String nodeTypeYaml,
- UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock,
- Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
- List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
- String nodeName, boolean isNested) {
+ public ImmutablePair<Resource, ActionStatus> createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock,
+ Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
+ List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
+ String nodeName, boolean isNested) {
- LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction("certification on import",
+ LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
LifecycleChanceActionEnum.CREATE_FROM_CSAR);
- Function<Resource, Either<Boolean, ResponseFormat>> validator = (resource) -> this
- .validateResourceCreationFromNodeType(resource, creator);
- return this.resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator,
+ Function<Resource, Either<Boolean, ResponseFormat>> validator = resource -> validateResourceCreationFromNodeType(resource, creator);
+ return resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator,
lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle,
- nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested);
+ nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested)
+ .left().on(this::failOnCertification);
+ }
+
+ private ImmutablePair<Resource,ActionStatus> failOnCertification(ResponseFormat error) {
+ throw new ComponentException(error);
}
- private Either<UploadResourceInfo, ResponseFormat> fillResourceMetadata(String yamlName, Resource resourceVf,
- String nodeName, User user) {
+ private UploadResourceInfo fillResourceMetadata(String yamlName, Resource resourceVf,
+ String nodeName, User user) {
UploadResourceInfo resourceMetaData = new UploadResourceInfo();
// validate nodetype name prefix
if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
log.debug("invalid nodeName:{} does not start with {}.", nodeName,
Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
+ throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
yamlName, resourceMetaData.getName(), nodeName);
- return Either.right(responseFormat);
}
String actualName = this.getNodeTypeActualName(nodeName);
@@ -1654,9 +1168,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(),
ResourceTypeEnum.values());
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
+ throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
yamlName, resourceMetaData.getName(), nodeName);
- return Either.right(responseFormat);
}
// Setting name
@@ -1687,7 +1200,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
categories.add(category);
resourceMetaData.setCategories(categories);
- return Either.left(resourceMetaData);
+ return resourceMetaData;
}
private Resource buildComplexVfcMetadata(Resource resourceVf, CsarInfo csarInfo, String nodeName,
@@ -1741,75 +1254,52 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return addCvfcSuffixToResourceName(resourceName);
}
- private Either<Resource, ResponseFormat> createResourceAndRIsFromYaml(String yamlName, Resource resource,
- ParsedToscaYamlInfo parsedToscaYamlInfo, AuditingActionEnum actionEnum, boolean isNormative,
- List<ArtifactDefinition> createdArtifacts, String topologyTemplateYaml,
- Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
- boolean shouldLock, boolean inTransaction, String nodeName) {
+ private Resource createResourceAndRIsFromYaml(String yamlName, Resource resource,
+ ParsedToscaYamlInfo parsedToscaYamlInfo, AuditingActionEnum actionEnum, boolean isNormative,
+ List<ArtifactDefinition> createdArtifacts, String topologyTemplateYaml,
+ Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
+ boolean shouldLock, boolean inTransaction, String nodeName) {
- boolean result = true;
List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
if (shouldLock) {
Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
- "Create Resource");
+ CREATE_RESOURCE);
if (lockResult.isRight()) {
- ResponseFormat responseFormat = lockResult.right().value();
- return Either.right(responseFormat);
+ rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
+ throw new ComponentException(lockResult.right().value());
}
log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
}
try {
log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
- Either<Resource, ResponseFormat> genericResourceEither = fetchAndSetDerivedFromGenericType(resource);
- if (genericResourceEither.isRight()) {
- result = false;
- return genericResourceEither;
- }
- Either<Resource, ResponseFormat> createResourcesEither = createResourceTransaction(resource,
- csarInfo.getModifier(), isNormative, inTransaction);
+ Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
+ resource = createResourceTransaction(resource,
+ csarInfo.getModifier(), isNormative);
log.trace("************* createResourceFromYaml after full create resource {}", yamlName);
- if (createResourcesEither.isRight()) {
- result = false;
- return createResourcesEither;
- }
- resource = createResourcesEither.left().value();
- // add groups to resource
log.trace("************* Going to add inputs from yaml {}", yamlName);
if (resource.shouldGenerateInputs())
- generateAndAddInputsFromGenericTypeProperties(resource, genericResourceEither.left().value());
+ generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
- Either<Resource, ResponseFormat> createInputsOnResource = createInputsOnResource(resource,
- csarInfo.getModifier(), inputs, inTransaction);
- if (createInputsOnResource.isRight()) {
- result = false;
- return createInputsOnResource;
- }
- resource = createInputsOnResource.left().value();
+ resource = createInputsOnResource(resource, inputs);
log.trace("************* Finish to add inputs from yaml {}", yamlName);
Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo
.getInstances();
log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName);
- createResourcesEither = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap,
- actionEnum, topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
+ resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap,
+ topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
nodeTypesArtifactsToCreate, nodeName);
log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName);
- if (createResourcesEither.isRight()) {
- result = false;
- return createResourcesEither;
- }
-
- resource = createResourcesEither.left().value();
// validate update vf module group names
Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
.validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName());
if (validateUpdateVfGroupNamesRes.isRight()) {
- result = false;
- return Either.right(validateUpdateVfGroupNamesRes.right().value());
+ rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
+ throw new ComponentException(validateUpdateVfGroupNamesRes.right().value());
}
// add groups to resource
Map<String, GroupDefinition> groups;
@@ -1820,11 +1310,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
} else {
groups = parsedToscaYamlInfo.getGroups();
}
+
Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource,
- csarInfo.getModifier(), groups);
+ groups);
if (createGroupsOnResource.isRight()) {
- result = false;
- return createGroupsOnResource;
+ rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
+ throw new ComponentException(createGroupsOnResource.right().value());
}
resource = createGroupsOnResource.left().value();
log.trace("************* Finished to add groups from yaml {}", yamlName);
@@ -1837,31 +1328,23 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.CREATE, createdArtifacts, yamlName,
csarInfo, resource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
if (createArtifactsEither.isRight()) {
- log.debug("failed to update artifacts {}", createArtifactsEither.right().value());
- return createArtifactsEither;
-
+ rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
+ throw new ComponentException(createArtifactsEither.right().value());
}
- resource = createArtifactsEither.left().value();
+
+ resource = getResourceWithGroups(createArtifactsEither.left().value().getUniqueId());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum);
ASDCKpiApi.countCreatedResourcesKPI();
- return Either.left(resource);
+ return resource;
+ } catch(ComponentException|StorageException e) {
+ rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
+ throw e;
} finally {
if (!inTransaction) {
- if (!result) {
- log.warn("operation failed. do rollback");
- titanDao.rollback();
- if (!createdArtifacts.isEmpty() || !nodeTypesNewCreatedArtifacts.isEmpty()) {
- createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
- log.debug("component and all its artifacts were deleted, id = {}", resource.getName());
- }
-
- } else {
- log.debug("operation success. do commit");
- titanDao.commit();
- }
+ titanDao.commit();
}
if (shouldLock) {
graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
@@ -1870,19 +1353,36 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
}
- private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource, User user,
+ private void rollback(boolean inTransaction, Resource resource, List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
+ if(!inTransaction) {
+ titanDao.rollback();
+ }
+ if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) {
+ createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
+ log.debug("Found {} newly created artifacts to deleted, the component name: {}",createdArtifacts.size(), resource.getName());
+ }
+ }
+
+ private Resource getResourceWithGroups(String resourceId) {
+
+ ComponentParametersView filter = new ComponentParametersView();
+ filter.setIgnoreGroups(false);
+ Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter);
+ if (updatedResource.isRight()) {
+ rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resourceId);
+ }
+ return updatedResource.left().value();
+ }
+
+ private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource,
Map<String, GroupDefinition> groups) {
if (groups != null && !groups.isEmpty()) {
- Either<List<GroupDefinition>, ResponseFormat> mergeGroupsUsingResource = updateGroupMembersUsingResource(
+ List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(
groups, resource);
-
- if (mergeGroupsUsingResource.isRight()) {
- log.debug("Failed to prepare groups for creation");
- return Either.right(mergeGroupsUsingResource.right().value());
- }
- List<GroupDefinition> groupsAsList = mergeGroupsUsingResource.left().value();
+ handleGroupsProperties(resource, groups);
+ fillGroupsFinalFields(groupsAsList);
Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource,
- groupsAsList);
+ groupsAsList, true);
if (createGroups.isRight()) {
return Either.right(createGroups.right().value());
}
@@ -1899,178 +1399,218 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(updatedResource.left().value());
}
- private Either<Resource, ResponseFormat> updateGroupsOnResource(Resource resource, User user,
- Map<String, GroupDefinition> groups) {
- if (groups != null && false == groups.isEmpty()) {
- List<GroupDefinition> groupsFromResource = resource.getGroups();
- Either<List<GroupDefinition>, ResponseFormat> mergeGroupsUsingResource = updateGroupMembersUsingResource(
- groups, resource);
-
- if (mergeGroupsUsingResource.isRight()) {
- log.debug("Failed to prepare groups for creation");
- return Either.right(mergeGroupsUsingResource.right().value());
- }
- List<GroupDefinition> groupsAsList = mergeGroupsUsingResource.left().value();
- List<GroupDefinition> groupsToUpdate = new ArrayList<GroupDefinition>();
- List<GroupDefinition> groupsToDelete = new ArrayList<GroupDefinition>();
- List<GroupDefinition> groupsToCreate = new ArrayList<GroupDefinition>();
- if (groupsFromResource != null && !groupsFromResource.isEmpty()) {
- for (GroupDefinition group : groupsAsList) {
- Optional<GroupDefinition> op = groupsFromResource.stream()
- .filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny();
- if (op.isPresent()) {
- GroupDefinition groupToUpdate = op.get();
- groupToUpdate.setMembers(group.getMembers());
- groupsToUpdate.add(groupToUpdate);
- } else {
- groupsToCreate.add(group);
- }
- }
- for (GroupDefinition group : groupsFromResource) {
- Optional<GroupDefinition> op = groupsAsList.stream()
- .filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny();
- if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) {
-
- groupsToDelete.add(group);
- }
-
- }
- } else
- groupsToCreate.addAll(groupsAsList);
- Either<List<GroupDefinition>, ResponseFormat> prepareGroups = null;
- if (!groupsToCreate.isEmpty()) {
-
- if (groupsFromResource != null && !groupsFromResource.isEmpty()) {
- prepareGroups = groupBusinessLogic.addGroups(resource,
- groupsToCreate);
- } else {
- prepareGroups = groupBusinessLogic.createGroups(resource,
- groupsToCreate);
- }
+ private void handleGroupsProperties(Resource resource, Map<String, GroupDefinition> groups) {
+ 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));
+ }
+ }
- if (prepareGroups.isRight()) {
- return Either.right(prepareGroups.right().value());
- }
+ private void handleGetInputs(PropertyDataDefinition property, List<InputDefinition> inputs) {
+ if (isNotEmpty(property.getGetInputValues())) {
+ 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());
}
-
- if (!groupsToDelete.isEmpty()) {
- prepareGroups = groupBusinessLogic.deleteGroups(resource,
- groupsToDelete);
- if (prepareGroups.isRight()) {
- return Either.right(prepareGroups.right().value());
+ ListIterator<GetInputValueDataDefinition> getInputValuesIter = property.getGetInputValues().listIterator();
+ while (getInputValuesIter.hasNext()) {
+ GetInputValueDataDefinition getInput = getInputValuesIter.next();
+ InputDefinition input = findInputByName(inputs, getInput);
+ getInput.setInputId(input.getUniqueId());
+ if (getInput.getGetInputIndex() != null) {
+ GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
+ input = findInputByName(inputs, getInputIndex);
+ getInputIndex.setInputId(input.getUniqueId());
+ getInputValuesIter.add(getInputIndex);
}
}
+ }
+ }
- if (groupsToUpdate != null && !groupsToUpdate.isEmpty()) {
- prepareGroups = groupBusinessLogic.updateGroups(resource, groupsToUpdate);
- if (prepareGroups.isRight()) {
- return Either.right(prepareGroups.right().value());
- }
- }
+ private InputDefinition findInputByName(List<InputDefinition> inputs, GetInputValueDataDefinition getInput) {
+ Optional<InputDefinition> inputOpt = inputs.stream()
+ .filter(p -> p.getName().equals(getInput.getInputName()))
+ .findFirst();
+ if (!inputOpt.isPresent()) {
+ log.debug("#findInputByName - Failed to find the input {} ", getInput.getInputName());
+ rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, getInput.getInputName());
+ }
+ return inputOpt.get();
+ }
+
+ private void fillGroupsFinalFields(List<GroupDefinition> groupsAsList) {
+ groupsAsList.forEach(groupDefinition -> {
+ groupDefinition.setInvariantName(groupDefinition.getName());
+ groupDefinition.setCreatedFrom(CreatedFrom.CSAR);
+ });
+ }
+ private Resource updateGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
+ if (isEmpty(groups)) {
+ return resource;
} else {
- return Either.left(resource);
+ updateOrCreateGroups(resource, groups);
}
-
Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
.getToscaElement(resource.getUniqueId());
if (updatedResource.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
- componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
- return Either.right(responseFormat);
+ throw new ComponentException(componentsUtils.getResponseFormatByResource(
+ componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
+ }
+ return updatedResource.left().value();
+ }
+
+ private void updateOrCreateGroups(Resource resource, Map<String, GroupDefinition> groups) {
+ List<GroupDefinition> groupsFromResource = resource.getGroups();
+ List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
+ List<GroupDefinition> groupsToUpdate = new ArrayList<>();
+ List<GroupDefinition> groupsToDelete = new ArrayList<>();
+ List<GroupDefinition> groupsToCreate = new ArrayList<>();
+ if (isNotEmpty(groupsFromResource)) {
+ addGroupsToCreateOrUpdate(groupsFromResource, groupsAsList, groupsToUpdate, groupsToCreate);
+ addGroupsToDelete(groupsFromResource, groupsAsList, groupsToDelete);
+ } else {
+ groupsToCreate.addAll(groupsAsList);
+ }
+ if (isNotEmpty(groupsToCreate)) {
+ fillGroupsFinalFields(groupsToCreate);
+ if (isNotEmpty(groupsFromResource)) {
+ groupBusinessLogic.addGroups(resource,
+ groupsToCreate, true)
+ .left()
+ .on(this::throwComponentException);
+ } else {
+ groupBusinessLogic.createGroups(resource,
+ groupsToCreate, true)
+ .left()
+ .on(this::throwComponentException);
+ }
+ }
+ if (isNotEmpty(groupsToDelete)) {
+ groupBusinessLogic.deleteGroups(resource, groupsToDelete)
+ .left()
+ .on(this::throwComponentException);
+ }
+ if (isNotEmpty(groupsToUpdate)) {
+ groupBusinessLogic.updateGroups(resource, groupsToUpdate, true)
+ .left()
+ .on(this::throwComponentException);
}
- return Either.left(updatedResource.left().value());
}
- private Either<Resource, ResponseFormat> createInputsOnResource(Resource resource, User user,
- Map<String, InputDefinition> inputs, boolean inTransaction) {
+ private void addGroupsToDelete(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList, List<GroupDefinition> groupsToDelete) {
+ for (GroupDefinition group : groupsFromResource) {
+ Optional<GroupDefinition> op = groupsAsList.stream()
+ .filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny();
+ if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) {
+ groupsToDelete.add(group);
+ }
+ }
+ }
+
+ private void addGroupsToCreateOrUpdate(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList, List<GroupDefinition> groupsToUpdate, List<GroupDefinition> groupsToCreate) {
+ for (GroupDefinition group : groupsAsList) {
+ Optional<GroupDefinition> op = groupsFromResource.stream()
+ .filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName())).findAny();
+ if (op.isPresent()) {
+ GroupDefinition groupToUpdate = op.get();
+ groupToUpdate.setMembers(group.getMembers());
+ groupToUpdate.setCapabilities(group.getCapabilities());
+ groupToUpdate.setProperties(group.getProperties());
+ groupsToUpdate.add(groupToUpdate);
+ } else {
+ groupsToCreate.add(group);
+ }
+ }
+ }
+
+ private Resource createInputsOnResource(Resource resource, Map<String, InputDefinition> inputs) {
List<InputDefinition> resourceProperties = resource.getInputs();
- if ((inputs != null && false == inputs.isEmpty())
- || (resourceProperties != null && false == resourceProperties.isEmpty())) {
+ if (MapUtils.isNotEmpty(inputs)|| isNotEmpty(resourceProperties)) {
Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs,
resource);
if (createInputs.isRight()) {
- return Either.right(createInputs.right().value());
+ throw new ComponentException(createInputs.right().value());
}
} else {
- return Either.left(resource);
+ return resource;
}
-
Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
.getToscaElement(resource.getUniqueId());
if (updatedResource.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
- componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
- return Either.right(responseFormat);
+ throw new ComponentException(componentsUtils.getResponseFormatByResource(
+ componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
}
- return Either.left(updatedResource.left().value());
+ return updatedResource.left().value();
}
- private Either<List<GroupDefinition>, ResponseFormat> updateGroupMembersUsingResource(
- Map<String, GroupDefinition> groups, Resource component) {
+ private List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, Resource component) {
List<GroupDefinition> result = new ArrayList<>();
-
List<ComponentInstance> componentInstances = component.getComponentInstances();
if (groups != null) {
Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups);
if (validateCyclicGroupsDependencies.isRight()) {
- return FunctionalInterfaces.convertEitherRight(validateCyclicGroupsDependencies);
+ throw new ComponentException(validateCyclicGroupsDependencies.right().value());
}
for (Entry<String, GroupDefinition> entry : groups.entrySet()) {
String groupName = entry.getKey();
-
GroupDefinition groupDefinition = entry.getValue();
-
GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
updatedGroupDefinition.setMembers(null);
-
- // get the members of the group
Map<String, String> members = groupDefinition.getMembers();
if (members != null) {
- Set<String> compInstancesNames = members.keySet();
-
- if (componentInstances == null || true == componentInstances.isEmpty()) {
- String membersAstString = compInstancesNames.stream().collect(Collectors.joining(","));
- log.debug(
- "The members: {}, in group: {}, cannot be found in component {}. There are no component instances.",
- membersAstString, groupName, component.getNormalizedName());
- return Either.right(componentsUtils.getResponseFormat(
- ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
- component.getNormalizedName(), getComponentTypeForResponse(component)));
- }
- // Find all component instances with the member names
- Map<String, String> memberNames = componentInstances.stream()
- .collect(Collectors.toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
- memberNames.putAll(groups.keySet().stream().collect(Collectors.toMap(g -> g, g -> "")));
- Map<String, String> relevantInstances = memberNames.entrySet().stream()
- .filter(n -> compInstancesNames.contains(n.getKey()))
- .collect(Collectors.toMap(n -> n.getKey(), n -> n.getValue()));
-
- if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
-
- List<String> foundMembers = new ArrayList<>();
- if (relevantInstances != null) {
- foundMembers = relevantInstances.keySet().stream().collect(Collectors.toList());
- }
- compInstancesNames.removeAll(foundMembers);
- String membersAstString = compInstancesNames.stream().collect(Collectors.joining(","));
- log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString,
- groupName, component.getNormalizedName());
- return Either.right(componentsUtils.getResponseFormat(
- ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
- component.getNormalizedName(), getComponentTypeForResponse(component)));
- }
-
- updatedGroupDefinition.setMembers(relevantInstances);
+ updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members);
}
-
result.add(updatedGroupDefinition);
}
}
- return Either.left(result);
+ return result;
+ }
+
+ private void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition, Resource component, List<ComponentInstance> componentInstances, String groupName, Map<String, String> members) {
+ Set<String> compInstancesNames = members.keySet();
+
+ if (CollectionUtils.isEmpty(componentInstances)) {
+ String membersAstString = compInstancesNames.stream().collect(joining(","));
+ log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.",
+ membersAstString, groupName, component.getNormalizedName());
+ throw new ComponentException(componentsUtils.getResponseFormat(
+ ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
+ 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));
+
+ if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
+
+ List<String> foundMembers = new ArrayList<>();
+ if (relevantInstances != null) {
+ foundMembers = relevantInstances.keySet().stream().collect(toList());
+ }
+ compInstancesNames.removeAll(foundMembers);
+ String membersAstString = compInstancesNames.stream().collect(joining(","));
+ log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString,
+ groupName, component.getNormalizedName());
+ throw new ComponentException(componentsUtils.getResponseFormat(
+ ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
+ component.getNormalizedName(), getComponentTypeForResponse(component)));
+ }
+ updatedGroupDefinition.setMembers(relevantInstances);
}
/**
@@ -2130,11 +1670,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
// are groups
List<String> currGroupFilteredMembers = currGroupMembers.stream().
// Keep Only Elements of type group and not Resource Instances
- filter(innerGroupName -> allGroups.containsKey(innerGroupName)).
+ filter(allGroups::containsKey).
// Add Filtered Elements to main Set
- peek(innerGroupName -> allGroupMembers.add(innerGroupName)).
+ peek(allGroupMembers::add).
// Collect results
- collect(Collectors.toList());
+ collect(toList());
// Recursively call the method for all the filtered group members
for (String innerGroupName : currGroupFilteredMembers) {
@@ -2154,7 +1694,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
// In Case Group Has no members stop
if (!stop) {
GroupDefinition groupDefinition = allGroups.get(groupName);
- stop = MapUtils.isEmpty(groupDefinition.getMembers());
+ stop = isEmpty(groupDefinition.getMembers());
}
// In Case all group members already contained stop
@@ -2162,130 +1702,91 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
final Set<String> allMembers = allGroups.get(groupName).getMembers().keySet();
Set<String> membersOfTypeGroup = allMembers.stream().
// Filter In Only Group members
- filter(innerGroupName -> allGroups.containsKey(innerGroupName)).
+ filter(allGroups::containsKey).
// Collect
- collect(Collectors.toSet());
+ collect(toSet());
stop = allGroupMembers.containsAll(membersOfTypeGroup);
}
return stop;
}
- private Either<Resource, ResponseFormat> createRIAndRelationsFromYaml(String yamlName, Resource resource,
- Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap, AuditingActionEnum actionEnum,
- String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
- Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
- String nodeName) {
-
- Either<Resource, ResponseFormat> result;
- Either<Resource, ResponseFormat> createResourcesInstancesEither;
+ private Resource createRIAndRelationsFromYaml(String yamlName, Resource resource,
+ Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap,
+ String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
+ Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
+ String nodeName) {
log.debug("************* Going to create all nodes {}", yamlName);
- Either<Map<String, Resource>, ResponseFormat> createdResourcesFromdNodeTypeMap = this.handleNodeTypes(yamlName,
- resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts,
+ handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts,
nodeTypesInfo, csarInfo, nodeName);
log.debug("************* Finished to create all nodes {}", yamlName);
- if (createdResourcesFromdNodeTypeMap.isRight()) {
- log.debug("failed to resources from node types status is {}",
- createdResourcesFromdNodeTypeMap.right().value());
- return Either.right(createdResourcesFromdNodeTypeMap.right().value());
- }
-
log.debug("************* Going to create all resource instances {}", yamlName);
- createResourcesInstancesEither = createResourceInstances(csarInfo.getModifier(), yamlName, resource,
- uploadComponentInstanceInfoMap, true, false, csarInfo.getCreatedNodes());
-
+ resource = createResourceInstances(yamlName, resource,
+ uploadComponentInstanceInfoMap, csarInfo.getCreatedNodes());
log.debug("************* Finished to create all resource instances {}", yamlName);
- if (createResourcesInstancesEither.isRight()) {
- log.debug("failed to create resource instances status is {}",
- createResourcesInstancesEither.right().value());
- result = createResourcesInstancesEither;
- return createResourcesInstancesEither;
- }
- resource = createResourcesInstancesEither.left().value();
log.debug("************* Going to create all relations {}", yamlName);
- createResourcesInstancesEither = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource,
- uploadComponentInstanceInfoMap);
-
+ resource = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap);
log.debug("************* Finished to create all relations {}", yamlName);
-
- if (createResourcesInstancesEither.isRight()) {
- log.debug("failed to create relation between resource instances status is {}",
- createResourcesInstancesEither.right().value());
- result = createResourcesInstancesEither;
- return result;
- } else {
- resource = createResourcesInstancesEither.left().value();
- }
-
log.debug("************* Going to create positions {}", yamlName);
- Either<List<ComponentInstance>, ResponseFormat> eitherSetPosition = compositionBusinessLogic
- .setPositionsForComponentInstances(resource, csarInfo.getModifier().getUserId());
+ compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier().getUserId());
log.debug("************* Finished to set positions {}", yamlName);
- result = eitherSetPosition.isRight() ? Either.right(eitherSetPosition.right().value()) : Either.left(resource);
-
- return result;
+ return resource;
}
private void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts,
List<ArtifactDefinition> artifactsToAdd) {
- List<String> vfcArtifactNames = vfcArtifacts.stream().map(a -> a.getArtifactName())
- .collect(Collectors.toList());
+ List<String> vfcArtifactNames = vfcArtifacts.stream().map(ArtifactDataDefinition::getArtifactName)
+ .collect(toList());
artifactsToAdd.stream().forEach(a -> {
if (!vfcArtifactNames.contains(a.getArtifactName())) {
vfcArtifacts.add(a);
} else {
- log.error("Can't upload two artifact with the same name {}. ", a.getArtifactName());
+ log.debug("Can't upload two artifact with the same name {}. ", a.getArtifactName());
}
});
}
@SuppressWarnings("unchecked")
- private Either<Map<String, Resource>, ResponseFormat> handleNodeTypes(String yamlName, Resource resource,
- String topologyTemplateYaml, boolean needLock,
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
- List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
- CsarInfo csarInfo, String nodeName) {
-
- Either<Map<String, Resource>, ResponseFormat> result = Either.left(csarInfo.getCreatedNodes());
- for (Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
- if (nodeTypeEntry.getValue().isNested()) {
-
- Either<Resource, ResponseFormat> createResourceFromYaml = handleNestedVfc(resource,
- nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
- nodeTypeEntry.getKey());
- log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
- if (createResourceFromYaml.isRight()) {
- return Either.right(createResourceFromYaml.right().value());
- }
- }
- }
-
- Map<String, Object> mappedToscaTemplate = null;
- if (StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo)
- && nodeTypesInfo.containsKey(nodeName)) {
- mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
- }
- if (MapUtils.isEmpty(mappedToscaTemplate)) {
- mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
- }
-
- Either<Map<String, Resource>, ResponseFormat> createdNodeTypeFromMainTemplateEither = createResourcesFromYamlNodeTypesList(
- yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle,
- nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
- if (createdNodeTypeFromMainTemplateEither.isRight()) {
- ResponseFormat responseFormat = createdNodeTypeFromMainTemplateEither.right().value();
+ private void handleNodeTypes(String yamlName, Resource resource,
+ String topologyTemplateYaml, boolean needLock,
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
+ List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
+ CsarInfo csarInfo, String nodeName) {
+ try{
+ for (Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
+ if (nodeTypeEntry.getValue().isNested()) {
+
+ handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts,
+ nodeTypesInfo, csarInfo, nodeTypeEntry.getKey());
+ log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
+ }
+ }
+ Map<String, Object> mappedToscaTemplate = null;
+ if (StringUtils.isNotEmpty(nodeName) && isNotEmpty(nodeTypesInfo)
+ && nodeTypesInfo.containsKey(nodeName)) {
+ mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
+ }
+ if (isEmpty(mappedToscaTemplate)) {
+ mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
+ }
+ createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle,
+ nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
+ } catch(ComponentException e){
+ ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat()
+ : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
- return Either.right(responseFormat);
+ throw e;
+ } catch (StorageException e){
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
+ componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
+ throw e;
}
-
// add the created node types to the cache although they are not in the
// graph.
csarInfo.getCreatedNodes().values().stream()
.forEach(p -> cacheManagerOperation.storeComponentInCache(p, NodeTypeEnum.Resource));
-
- return result;
}
private Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo,
@@ -2300,10 +1801,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts();
if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
for (Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
- if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL))
+ if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) {
vendorLicenseModelId = artifactEntry.getValue().getUniqueId();
- if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL))
+ }
+ if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) {
vfLicenseModelId = artifactEntry.getValue().getUniqueId();
+ }
}
}
@@ -2313,13 +1816,13 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
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, false, shouldLock,
+ 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, false, shouldLock, inTransaction);
+ artifactOperation, null, true, shouldLock, inTransaction);
Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource,
createdArtifacts, shouldLock, inTransaction, artifactOperation);
@@ -2343,10 +1846,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
Either<Resource, ResponseFormat> createArtifactsFromCsar;
- if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum()))
+ if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
- else
+ } else {
createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
+ }
if (createArtifactsFromCsar.isRight()) {
log.debug("Couldn't create artifacts from artifacts.meta");
@@ -2436,36 +1940,19 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
try {
- 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(e -> e.isLeft())
- // Convert from Either to NonMetaArtifactInfo
- .map(e -> e.left().value())
- // collect to List
- .collect(Collectors.toList());
-
- Either<Boolean, String> responseFormatEither = validateArtifactNames(artifactPathAndNameList);
- if (responseFormatEither.isRight()) {
+ Either<List<NonMetaArtifactInfo>, String> artifactPathAndNameList = getValidArtifactNames(csarInfo, collectedWarningMessages);
+ if (artifactPathAndNameList.isRight()) {
return Either.right(getComponentsUtils().getResponseFormatByArtifactId(
- ActionStatus.ARTIFACT_NAME_INVALID, responseFormatEither.right().value()));
+ ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right().value()));
}
-
EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
- vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList);
+ vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left().value());
} else {
Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(
- resource, artifactPathAndNameList, csarInfo.getModifier());
+ resource, artifactPathAndNameList.left().value(), csarInfo.getModifier());
if (findVfCsarArtifactsToHandleRes.isRight()) {
resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value());
@@ -2474,37 +1961,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left().value();
}
}
-
-
if (resStatus == null && vfCsarArtifactsToHandle != null) {
-
- 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().getType(),
- e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
- CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(),
- artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
- currArtifactOperationPair.getKey()),
- createdArtifacts, e.isFromCsar(), shouldLock, inTransaction))
- // filter in only error
- .filter(e -> e.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());
- break;
- }
- }
+ resStatus = processCsarArtifacts(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, resStatus, vfCsarArtifactsToHandle);
}
if (resStatus == null) {
resStatus = Either.left(resource);
@@ -2518,14 +1976,60 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return resStatus;
}
- private Either<Boolean, String> validateArtifactNames(List<NonMetaArtifactInfo> artifactPathAndNameList) {
+ private Either<Resource, ResponseFormat> processCsarArtifacts(CsarInfo csarInfo, Resource resource, List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction, Either<Resource, ResponseFormat> resStatus, 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().getType(),
+ e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
+ CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(),
+ artifactsBusinessLogic.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());
+ break;
+ }
+ }
+ return resStatus;
+ }
+
+ 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());
Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) {
return Either.right(nonMetaArtifactInfo.getArtifactName());
}
}
- return Either.left(true);
+ return Either.left(artifactPathAndNameList);
}
private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(
@@ -2542,19 +2046,20 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
existingArtifacts = existingArtifacts.stream()
// filter MANDATORY artifacts, LICENSE artifacts and artifacts
// was created from HEAT.meta
- .filter(this::isNonMetaArtifact).collect(Collectors.toList());
+ .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) {
resource.getGroups().stream().forEach(g -> {
- if (g.getArtifacts() != null && !g.getArtifacts().isEmpty())
+ if (g.getArtifacts() != null && !g.getArtifacts().isEmpty()) {
artifactsToIgnore.addAll(g.getArtifacts());
+ }
});
}
existingArtifacts = existingArtifacts.stream()
// filter artifacts which belongs to any group
- .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(Collectors.toList());
+ .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(toList());
return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user);
}
@@ -2576,228 +2081,185 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return result;
}
- private Either<Resource, ResponseFormat> createResourceInstancesRelations(User user, String yamlName,
- Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
- log.debug("createResourceInstancesRelations try to create relations ");
+ private Resource createResourceInstancesRelations(User user, String yamlName, Resource resource,
+ Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
+ log.debug("#createResourceInstancesRelations - Going to create relations ");
List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
- if (uploadResInstancesMap == null) {
- log.debug("UploadComponentInstanceInfo is empty, fileName {}", yamlName);
- BeEcompErrorManager.getInstance().logInternalDataError("UploadComponentInstanceInfo is emty, fileName {}",
- yamlName, ErrorSeverity.ERROR);
-
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE,
- yamlName);
- return Either.right(responseFormat);
- }
-
- if (componentInstancesList == null || componentInstancesList.isEmpty()) {
- log.debug("componentInstancesList is empty in resource {} ", resource.getUniqueId());
- BeEcompErrorManager.getInstance().logInternalDataError("componentInstancesList is empty in resource {} ",
- resource.getUniqueId(), ErrorSeverity.ERROR);
-
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE,
- yamlName);
- return Either.right(responseFormat);
+ if (isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)) {
+ log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ", resource.getUniqueId(), yamlName);
+ BeEcompErrorManager.getInstance().logInternalDataError("createResourceInstancesRelations","No instances found in a resource or nn yaml template. ", ErrorSeverity.ERROR);
+ throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName));
}
+ Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
+ Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
+ Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
+ Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
+ Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
+ Map<String, List<PropertyDefinition>> instAttributes = new HashMap<>();
+ Map<String, Resource> originCompMap = new HashMap<>();
+ List<RequirementCapabilityRelDef> relations = new ArrayList<>();
+ Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
- log.debug("Before validateAndUpdatePropertyValue");
+ log.debug("#createResourceInstancesRelations - Before get all datatypes. ");
Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
if (allDataTypes.isRight()) {
TitanOperationStatus status = allDataTypes.right().value();
BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance",
"Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
+ throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
DaoStatusConverter.convertTitanStatusToStorageStatus(status)), yamlName));
}
+ Resource finalResource = resource;
+ uploadResInstancesMap
+ .values()
+ .forEach(i ->processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes,
+ instProperties, instCapabilities, instRequirements, instDeploymentArtifacts,
+ instArtifacts, instAttributes, originCompMap, instInputs, i));
- Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
- Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties = new HashMap<>();
- Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
- Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
- Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
- Map<String, List<PropertyDefinition>> instAttributes = new HashMap<>();
- Map<String, Resource> originCompMap = new HashMap<>();
- List<RequirementCapabilityRelDef> relations = new ArrayList<>();
+ associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties);
+ associateComponentInstanceInputsToComponent(yamlName, resource, instInputs);
+ associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts);
+ associateArtifactsToInstances(yamlName, resource, instArtifacts);
+ associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements);
+ associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes);
- Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
+ resource = getResourceAfterCreateRelations(resource);
- for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
- log.trace("Processing entry: {}", entry);
- UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
- ComponentInstance currentCompInstance = null;
- for (ComponentInstance compInstance : componentInstancesList) {
- log.trace("Processing component instance: {}", compInstance);
- if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
- currentCompInstance = compInstance;
- break;
- }
-
- }
- 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);
- ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
- return Either.right(responseFormat);
- }
- String resourceInstanceId = currentCompInstance.getUniqueId();
- Resource originResource;
- if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
- Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade
- .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);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(
- componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName);
- return Either.right(responseFormat);
- }
- originResource = getOriginResourceRes.left().value();
- originCompMap.put(originResource.getUniqueId(), originResource);
- } else {
- originResource = originCompMap.get(currentCompInstance.getComponentUid());
- }
- if (originResource.getRequirements() != null && !originResource.getRequirements().isEmpty())
- instRequirements.put(currentCompInstance, originResource.getRequirements());
- if (MapUtils.isNotEmpty(originResource.getCapabilities())) {
- Map<String, List<CapabilityDefinition>> originCapabilities;
- if (MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) {
- originCapabilities = new HashMap<>();
- originResource.getCapabilities().entrySet().stream().forEach(e -> {
- List<CapabilityDefinition> list = e.getValue().stream().map(l -> new CapabilityDefinition(l))
- .collect(Collectors.toList());
- originCapabilities.put(e.getKey(), list);
- });
- Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>();
- for (List<UploadCapInfo> capabilities : uploadComponentInstanceInfo.getCapabilities().values()) {
- for (UploadCapInfo capability : capabilities) {
- if (CollectionUtils.isNotEmpty(capability.getProperties())) {
- newPropertiesMap.put(capability.getName(), capability.getProperties().stream()
- .collect(Collectors.toMap(p -> p.getName(), p -> p)));
- }
- }
- }
- for (List<CapabilityDefinition> capabilities : originCapabilities.values()) {
- List<CapabilityDefinition> filteredCapabilities = capabilities.stream()
- .filter(c -> newPropertiesMap.containsKey(c.getName())).collect(Collectors.toList());
- for (CapabilityDefinition cap : filteredCapabilities) {
- Either<Boolean, ResponseFormat> updateRes = updatePropertyValues(cap.getProperties(),
- newPropertiesMap.get(cap.getName()), allDataTypes.left().value());
- if (updateRes.isRight()) {
- log.debug("Failed to update capability properties of capability {} . Status is {}. ",
- cap.getName(), updateRes.right().value());
- return Either.right(updateRes.right().value());
- }
- }
- }
- } else {
- originCapabilities = originResource.getCapabilities();
- }
- instCapabilties.put(currentCompInstance, originCapabilities);
- }
- if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty())
- instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
- if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty())
- instArtifacts.put(resourceInstanceId, originResource.getArtifacts());
- if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty())
- instAttributes.put(resourceInstanceId, originResource.getAttributes());
- if (originResource.getResourceType() != ResourceTypeEnum.CVFC) {
- ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource,
- originResource, currentCompInstance, yamlName, instProperties, allDataTypes.left().value());
- if (addPropertiesValueToRiRes.getStatus() != 200) {
- return Either.right(addPropertiesValueToRiRes);
- }
- } else {
- ResponseFormat addInputValueToRiRes = addInputsValuesToRi(uploadComponentInstanceInfo, resource,
- originResource, currentCompInstance, yamlName, instInputs, allDataTypes.left().value());
- if (addInputValueToRiRes.getStatus() != 200) {
- return Either.right(addInputValueToRiRes);
- }
- }
+ addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations);
+ associateResourceInstances(yamlName, resource, relations);
+ handleSubstitutionMappings(resource, uploadResInstancesMap);
+ log.debug("************* in create relations, getResource start");
+ Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
+ log.debug("************* in create relations, getResource end");
+ if (eitherGetResource.isRight()) {
+ throw new ComponentException(componentsUtils.getResponseFormatByResource(
+ componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource));
}
+ return eitherGetResource.left().value();
+ }
- Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
- .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
- if (addPropToInst.isRight()) {
- log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(),
- addPropToInst.right().value());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(
- componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName);
- return Either.right(responseFormat);
- }
- if (instInputs != null && !instInputs.isEmpty()) {
- Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
- .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
- if (addInputToInst.isRight()) {
- log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(),
- addInputToInst.right().value());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(
- componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName);
- return Either.right(responseFormat);
- }
- }
- StorageOperationStatus addArtToInst = toscaOperationFacade
- .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource.getUniqueId(), user);
- if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
- log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
- ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
- return Either.right(responseFormat);
+ private Resource getResourceAfterCreateRelations(Resource resource) {
+ ComponentParametersView parametersView = getComponentFilterAfterCreateRelations();
+ Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
+ .getToscaElement(resource.getUniqueId(), parametersView);
+
+ if (eitherGetResource.isRight()) {
+ throwComponentExceptionByResource(eitherGetResource.right().value(),resource);
}
+ return eitherGetResource.left().value();
+ }
- addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource.getUniqueId(), user);
+ private void associateResourceInstances(String yamlName, Resource resource, List<RequirementCapabilityRelDef> relations) {
+ StorageOperationStatus addArtToInst;
+ addArtToInst = toscaOperationFacade.associateResourceInstances(resource.getUniqueId(), relations);
if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
- log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
- ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
- return Either.right(responseFormat);
+ log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(),
+ addArtToInst);
+ throw new ComponentException(componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
}
+ }
+
+ private ComponentParametersView getComponentFilterAfterCreateRelations() {
+ ComponentParametersView parametersView = new ComponentParametersView();
+ parametersView.disableAll();
+ parametersView.setIgnoreComponentInstances(false);
+ parametersView.setIgnoreComponentInstancesProperties(false);
+ parametersView.setIgnoreCapabilities(false);
+ parametersView.setIgnoreRequirements(false);
+ parametersView.setIgnoreGroups(false);
+ return parametersView;
+ }
- addArtToInst = toscaOperationFacade.associateCalculatedCapReq(instCapabilties, instRequirements,
+ private void associateInstAttributeToComponentToInstances(String yamlName, Resource resource, Map<String, List<PropertyDefinition>> instAttributes) {
+ StorageOperationStatus addArtToInst;
+ addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes,
resource.getUniqueId());
if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
- log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(),
+ log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
addArtToInst);
- ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
- return Either.right(responseFormat);
+ throw new ComponentException(componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
}
+ }
- addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes,
+ private void associateOrAddCalculatedCapReq(String yamlName, Resource resource, Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
+ StorageOperationStatus addArtToInst;
+ addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements,
resource.getUniqueId());
if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
- log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
+ log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(),
addArtToInst);
- ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
- return Either.right(responseFormat);
+ throw new ComponentException(componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
}
+ }
- ComponentParametersView parametersView = new ComponentParametersView();
- parametersView.disableAll();
- parametersView.setIgnoreComponentInstances(false);
- parametersView.setIgnoreComponentInstancesProperties(false);
- parametersView.setIgnoreCapabilities(false);
- parametersView.setIgnoreRequirements(false);
+ private void associateArtifactsToInstances(String yamlName, Resource resource, Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
+ StorageOperationStatus addArtToInst;
- Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
- .getToscaElement(resource.getUniqueId(), parametersView);
+ addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource.getUniqueId());
+ if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
+ log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
+ throw new ComponentException(componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
+ }
+ }
- if (eitherGetResource.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
- componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
+ private void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource, Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
+ StorageOperationStatus addArtToInst = toscaOperationFacade
+ .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource.getUniqueId(), user);
+ if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
+ log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
+ throw new ComponentException(componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
+ }
+ }
- return Either.right(responseFormat);
+ private void associateComponentInstanceInputsToComponent(String yamlName, Resource resource, Map<String, List<ComponentInstanceInput>> instInputs) {
+ if (MapUtils.isNotEmpty(instInputs)) {
+ Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
+ .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
+ if (addInputToInst.isRight()) {
+ log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(),
+ addInputToInst.right().value());
+ throw new ComponentException(componentsUtils.getResponseFormat(
+ componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
+ }
+ }
+ }
+ private void associateComponentInstancePropertiesToComponent(String yamlName, Resource resource, Map<String, List<ComponentInstanceProperty>> instProperties) {
+ Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
+ .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
+ if (addPropToInst.isRight()) {
+ log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(),
+ addPropToInst.right().value());
+ throw new ComponentException(componentsUtils.getResponseFormat(
+ componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
}
+ }
- resource = eitherGetResource.left().value();
+ private void handleSubstitutionMappings(Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
+ if (resource.getResourceType() == ResourceTypeEnum.CVFC) {
+ Either<Resource, StorageOperationStatus> getResourceRes = toscaOperationFacade.getToscaFullElement(resource.getUniqueId());
+ if (getResourceRes.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
+ componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
+ throw new ComponentException(responseFormat);
+ }
+ getResourceRes = updateCalculatedCapReqWithSubstitutionMappings(getResourceRes.left().value(),
+ uploadResInstancesMap);
+ if (getResourceRes.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
+ componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
+ throw new ComponentException(responseFormat);
+ }
+ }
+ }
+ private void addRelationsToRI(String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) {
for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
ComponentInstance currentCompInstance = null;
@@ -2810,75 +2272,132 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
if (currentCompInstance == null) {
- log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(),
+ log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
resource.getUniqueId());
BeEcompErrorManager.getInstance().logInternalDataError(
- "component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ",
+ COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
resource.getUniqueId(), ErrorSeverity.ERROR);
ResponseFormat responseFormat = componentsUtils
.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
- return Either.right(responseFormat);
+ throw new ComponentException(responseFormat);
}
ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
if (addRelationToRiRes.getStatus() != 200) {
- return Either.right(addRelationToRiRes);
+ throw new ComponentException(addRelationToRiRes);
}
}
+ }
- addArtToInst = toscaOperationFacade.associateResourceInstances(resource.getUniqueId(), relations);
- if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
- log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(),
- addArtToInst);
+ private void processComponentInstance(String yamlName, Resource resource, List<ComponentInstance> componentInstancesList, Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes, Map<String, List<ComponentInstanceProperty>> instProperties, Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements, Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts, Map<String, Map<String, ArtifactDefinition>> instArtifacts, Map<String, List<PropertyDefinition>> instAttributes, Map<String, Resource> originCompMap, Map<String, List<ComponentInstanceInput>> instInputs, UploadComponentInstanceInfo uploadComponentInstanceInfo) {
+ Optional<ComponentInstance> currentCompInstanceOpt = componentInstancesList.stream()
+ .filter(i->i.getName().equals(uploadComponentInstanceInfo.getName()))
+ .findFirst();
+ if (!currentCompInstanceOpt.isPresent()) {
+ 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);
ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
- return Either.right(responseFormat);
+ .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+ throw new ComponentException(responseFormat);
}
-
- if (resource.getResourceType() == ResourceTypeEnum.CVFC) {
- eitherGetResource = toscaOperationFacade.getToscaFullElement(resource.getUniqueId());
- if (eitherGetResource.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
- componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
- return Either.right(responseFormat);
+ ComponentInstance currentCompInstance = currentCompInstanceOpt.get();
+ String resourceInstanceId = currentCompInstance.getUniqueId();
+ Resource originResource = getOriginResource(yamlName, originCompMap, currentCompInstance);
+ if (isNotEmpty(originResource.getRequirements())) {
+ instRequirements.put(currentCompInstance, originResource.getRequirements());
+ }
+ if (isNotEmpty(originResource.getCapabilities())) {
+ processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo,
+ currentCompInstance, originResource);
+ }
+ if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty()) {
+ instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
+ }
+ if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty()) {
+ instArtifacts.put(resourceInstanceId, originResource.getArtifacts());
+ }
+ if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty()) {
+ instAttributes.put(resourceInstanceId, originResource.getAttributes());
+ }
+ if (originResource.getResourceType() != ResourceTypeEnum.CVFC) {
+ ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource,
+ originResource, currentCompInstance, instProperties, allDataTypes.left().value());
+ if (addPropertiesValueToRiRes.getStatus() != 200) {
+ throw new ComponentException(addPropertiesValueToRiRes);
}
- eitherGetResource = updateCalculatedCapReqWithSubstitutionMappings(eitherGetResource.left().value(),
- uploadResInstancesMap);
- if (eitherGetResource.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
- componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
- return Either.right(responseFormat);
+ } else {
+ addInputsValuesToRi(uploadComponentInstanceInfo, resource,
+ originResource, currentCompInstance, instInputs, allDataTypes.left().value());
+ }
+ }
+
+ private Resource getOriginResource(String yamlName, Map<String, Resource> originCompMap, ComponentInstance currentCompInstance) {
+ Resource originResource;
+ if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
+ Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade
+ .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);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(
+ componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName);
+ throw new ComponentException(responseFormat);
}
+ originResource = getOriginResourceRes.left().value();
+ originCompMap.put(originResource.getUniqueId(), originResource);
+ } else {
+ originResource = originCompMap.get(currentCompInstance.getComponentUid());
}
+ return originResource;
+ }
- log.debug("************* in create relations, getResource start");
- eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
- log.debug("************* in create relations, getResource end");
- if (eitherGetResource.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
- componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
- return Either.right(responseFormat);
+ private void processComponentInstanceCapabilities(Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes, Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance, Resource originResource) {
+ Map<String, List<CapabilityDefinition>> originCapabilities;
+ if (isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) {
+ originCapabilities = new HashMap<>();
+ Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>();
+ originResource.getCapabilities().forEach((k,v) -> addCapabilities(originCapabilities, k, v));
+ uploadComponentInstanceInfo.getCapabilities().values().forEach(l-> addCapabilitiesProperties(newPropertiesMap, l));
+ updateCapabilityPropertiesValues(allDataTypes, originCapabilities, newPropertiesMap);
+ } else {
+ originCapabilities = originResource.getCapabilities();
}
- return Either.left(eitherGetResource.left().value());
+ instCapabilties.put(currentCompInstance, originCapabilities);
+ }
+
+ private void updateCapabilityPropertiesValues(Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes, Map<String, List<CapabilityDefinition>> originCapabilities, Map<String, Map<String, UploadPropInfo>> newPropertiesMap) {
+ originCapabilities.values().stream()
+ .flatMap(Collection::stream)
+ .filter(c -> newPropertiesMap.containsKey(c.getName()))
+ .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()), allDataTypes.left().value()));
}
- private Either<Boolean, ResponseFormat> updatePropertyValues(List<ComponentInstanceProperty> properties,
- Map<String, UploadPropInfo> newProperties, Map<String, DataTypeDefinition> allDataTypes) {
- for (ComponentInstanceProperty property : properties) {
- Either<String, StorageOperationStatus> updateRes = updatePropertyValue(property,
- newProperties.get(property.getName()), allDataTypes);
- if (updateRes.isRight()) {
- log.debug("Failed to update capability property {} . Status is {}. ", property.getName(),
- updateRes.right().value());
- return Either.right(componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(updateRes.right().value())));
+ private void addCapabilitiesProperties(Map<String, Map<String, UploadPropInfo>> newPropertiesMap, List<UploadCapInfo> capabilities) {
+ for (UploadCapInfo capability : capabilities) {
+ if (isNotEmpty(capability.getProperties())) {
+ newPropertiesMap.put(capability.getName(), capability.getProperties().stream()
+ .collect(toMap(UploadInfo::getName, p -> p)));
}
}
- return Either.left(true);
}
- private Either<String, StorageOperationStatus> updatePropertyValue(ComponentInstanceProperty property,
- UploadPropInfo propertyInfo, Map<String, DataTypeDefinition> allDataTypes) {
+ private void addCapabilities(Map<String, List<CapabilityDefinition>> originCapabilities, String type, List<CapabilityDefinition> capabilities) {
+ List<CapabilityDefinition> list = capabilities.stream().map(CapabilityDefinition::new)
+ .collect(toList());
+ originCapabilities.put(type, list);
+ }
+
+ private void updatePropertyValues(List<ComponentInstanceProperty> properties, Map<String, UploadPropInfo> newProperties,
+ Map<String, DataTypeDefinition> allDataTypes) {
+ properties.forEach(p->updatePropertyValue(p, newProperties.get(p.getName()), allDataTypes));
+ }
+
+ private String updatePropertyValue(ComponentInstanceProperty property, UploadPropInfo propertyInfo,
+ Map<String, DataTypeDefinition> allDataTypes) {
String value = null;
List<GetInputValueDataDefinition> getInputs = null;
boolean isValidate = true;
@@ -2886,10 +2405,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
getInputs = propertyInfo.getGet_input();
isValidate = getInputs == null || getInputs.isEmpty();
if (isValidate) {
- value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), property.getType());
- } else
- value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(),
- ToscaTagNamesEnum.GET_INPUT.getElementName());
+ value = getPropertyJsonStringValue(propertyInfo.getValue(), property.getType());
+ } else {
+ value = getPropertyJsonStringValue(propertyInfo.getValue(),
+ TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
+ }
}
property.setValue(value);
return validatePropValueBeforeCreate(property, value, isValidate, null, allDataTypes);
@@ -2911,7 +2431,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (updateRes == null) {
fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap,
updatedInstCapabilities, updatedInstRequirements);
- status = toscaOperationFacade.associateCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements,
+ status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements,
resource.getUniqueId());
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
log.debug(
@@ -2944,7 +2464,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
Set<String> updatedReqNames = new HashSet<>();
- if (MapUtils.isNotEmpty(requirementsNamesToUpdate)) {
+ if (isNotEmpty(requirementsNamesToUpdate)) {
for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements().entrySet()) {
updatedRequirements.put(requirements.getKey(),
requirements.getValue().stream()
@@ -2955,10 +2475,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
r.setName(requirementsNamesToUpdate.get(r.getName()));
updatedReqNames.add(r.getName());
return r;
- }).collect(Collectors.toList()));
+ }).collect(toList()));
}
}
- if (MapUtils.isNotEmpty(updatedRequirements)) {
+ if (isNotEmpty(updatedRequirements)) {
updatedInstRequirements.put(instance, updatedRequirements);
}
}
@@ -2968,7 +2488,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
Set<String> updatedCapNames = new HashSet<>();
- if (MapUtils.isNotEmpty(capabilitiesNamesToUpdate)) {
+ if (isNotEmpty(capabilitiesNamesToUpdate)) {
for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities().entrySet()) {
updatedCapabilities.put(requirements.getKey(),
requirements.getValue().stream()
@@ -2979,10 +2499,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
c.setName(capabilitiesNamesToUpdate.get(c.getName()));
updatedCapNames.add(c.getName());
return c;
- }).collect(Collectors.toList()));
+ }).collect(toList()));
}
}
- if (MapUtils.isNotEmpty(updatedCapabilities)) {
+ if (isNotEmpty(updatedCapabilities)) {
updatedInstCapabilties.put(instance, updatedCapabilities);
}
}
@@ -2991,13 +2511,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
- UploadComponentInstanceInfo uploadComponentInstanceInfo = nodesInfoValue;
-
ComponentInstance currentCompInstance = null;
for (ComponentInstance compInstance : componentInstancesList) {
- if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
+ if (compInstance.getName().equals(nodesInfoValue.getName())) {
currentCompInstance = compInstance;
break;
}
@@ -3005,18 +2523,17 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
if (currentCompInstance == null) {
- log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(),
+ log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(),
resource.getUniqueId());
BeEcompErrorManager.getInstance().logInternalDataError(
- "component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ",
+ COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE,
resource.getUniqueId(), ErrorSeverity.ERROR);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE,
+ return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE,
yamlName);
- return responseFormat;
}
String resourceInstanceId = currentCompInstance.getUniqueId();
- Map<String, List<UploadReqInfo>> regMap = uploadComponentInstanceInfo.getRequirements();
+ Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
if (regMap != null) {
Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
@@ -3032,7 +2549,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
regCapRelDef.setFromNode(resourceInstanceId);
log.debug("try to find available requirement {} ", regName);
Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName,
- yamlName, uploadComponentInstanceInfo, currentCompInstance,
+ yamlName, nodesInfoValue, currentCompInstance,
uploadRegInfo.getCapabilityName());
if (eitherReqStatus.isRight()) {
log.debug("failed to find available requirement {} status is {}", regName,
@@ -3043,8 +2560,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
RequirementDefinition validReq = eitherReqStatus.left().value();
List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef
.getRelationships();
- if (reqAndRelationshipPairList == null)
+ if (reqAndRelationshipPairList == null) {
reqAndRelationshipPairList = new ArrayList<>();
+ }
RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
reqAndRelationshipPair.setRequirement(regName);
reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
@@ -3065,16 +2583,18 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
log.debug("The component instance with name {} not found on resource {} ",
uploadRegInfo.getNode(), resource.getUniqueId());
BeEcompErrorManager.getInstance().logInternalDataError(
- "component instance with name " + uploadRegInfo.getNode() + " in resource {} ",
+ COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE,
resource.getUniqueId(), ErrorSeverity.ERROR);
- ResponseFormat responseFormat = componentsUtils
+ return componentsUtils
.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
- return responseFormat;
}
regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
log.debug("try to find aviable Capability req name is {} ", validReq.getName());
CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq,
currentCapCompInstance, uploadRegInfo);
+ reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
+ reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
+ reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
if (aviableCapForRel == null) {
log.debug("aviable capability was not found. req name is {} component instance is {}",
validReq.getName(), currentCapCompInstance.getUniqueId());
@@ -3082,13 +2602,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
"aviable capability was not found. req name is " + validReq.getName()
+ " component instance is " + currentCapCompInstance.getUniqueId(),
resource.getUniqueId(), ErrorSeverity.ERROR);
- ResponseFormat responseFormat = componentsUtils
+ return componentsUtils
.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
- return responseFormat;
}
- reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
- reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
- reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
capReqRel.setRelation(reqAndRelationshipPair);
reqAndRelationshipPairList.add(capReqRel);
@@ -3097,134 +2613,129 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
}
} else if (resource.getResourceType() != ResourceTypeEnum.CVFC) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
- return responseFormat;
+ return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
}
return componentsUtils.getResponseFormat(ActionStatus.OK);
}
- private ResponseFormat addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
- Resource resource, Resource originResource, ComponentInstance currentCompInstance, String yamlName,
- Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) {
+ private void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
+ Resource resource, Resource originResource, ComponentInstance currentCompInstance,
+ Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) {
Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
- if (propMap != null && propMap.size() > 0) {
- Map<String, InputDefinition> currPropertiesMap = new HashMap<String, InputDefinition>();
+ if (MapUtils.isNotEmpty(propMap)) {
+ Map<String, InputDefinition> currPropertiesMap = new HashMap<>();
+ List<ComponentInstanceInput> instPropList = new ArrayList<>();
- List<InputDefinition> listFromMap = originResource.getInputs();
- if (listFromMap == null || listFromMap.isEmpty()) {
+ if (CollectionUtils.isEmpty( originResource.getInputs())) {
log.debug("failed to find properties ");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
- return responseFormat;
+ throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND));
}
- for (InputDefinition prop : listFromMap) {
- String propName = prop.getName();
- if (!currPropertiesMap.containsKey(propName)) {
- currPropertiesMap.put(propName, prop);
- }
- }
- List<ComponentInstanceInput> instPropList = new ArrayList<>();
+ originResource.getInputs().forEach(p->addInput(currPropertiesMap, p));
for (List<UploadPropInfo> propertyList : propMap.values()) {
+ processProperty(resource, currentCompInstance, allDataTypes, currPropertiesMap, instPropList, propertyList);
+ }
+ currPropertiesMap.values().forEach(p->instPropList.add(new ComponentInstanceInput(p)));
+ instInputs.put(currentCompInstance.getUniqueId(), instPropList);
+ }
+ }
- UploadPropInfo propertyInfo = propertyList.get(0);
- String propName = propertyInfo.getName();
- if (!currPropertiesMap.containsKey(propName)) {
- log.debug("failed to find property {} ", propName);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
- propName);
- return responseFormat;
- }
- InputDefinition curPropertyDef = currPropertiesMap.get(propName);
- ComponentInstanceInput property = null;
-
- String value = null;
- List<GetInputValueDataDefinition> getInputs = null;
- boolean isValidate = true;
- if (propertyInfo.getValue() != null) {
- getInputs = propertyInfo.getGet_input();
- isValidate = getInputs == null || getInputs.isEmpty();
- if (isValidate) {
- value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(),
- curPropertyDef.getType());
- } else
- value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(),
- ToscaTagNamesEnum.GET_INPUT.getElementName());
- }
- String innerType = null;
- property = new ComponentInstanceInput(curPropertyDef, value, null);
+ private void processProperty(Resource resource, ComponentInstance currentCompInstance, Map<String, DataTypeDefinition> allDataTypes, Map<String, InputDefinition> currPropertiesMap, List<ComponentInstanceInput> instPropList, List<UploadPropInfo> propertyList) {
+ UploadPropInfo propertyInfo = propertyList.get(0);
+ String propName = propertyInfo.getName();
+ if (!currPropertiesMap.containsKey(propName)) {
+ log.debug("failed to find property {} ", propName);
+ throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
+ propName));
+ }
+ InputDefinition curPropertyDef = currPropertiesMap.get(propName);
+ ComponentInstanceInput property = null;
- Either<String, StorageOperationStatus> validatevalueEiter = validatePropValueBeforeCreate(property,
- value, isValidate, innerType, allDataTypes);
- if (validatevalueEiter.isRight()) {
- return componentsUtils.getResponseFormat(
- componentsUtils.convertFromStorageResponse(validatevalueEiter.right().value()));
- }
+ String value = null;
+ List<GetInputValueDataDefinition> getInputs = null;
+ boolean isValidate = true;
+ if (propertyInfo.getValue() != null) {
+ getInputs = propertyInfo.getGet_input();
+ isValidate = getInputs == null || getInputs.isEmpty();
+ if (isValidate) {
+ value = getPropertyJsonStringValue(propertyInfo.getValue(),
+ curPropertyDef.getType());
+ } else {
+ value = getPropertyJsonStringValue(propertyInfo.getValue(),
+ TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
+ }
+ }
+ String innerType = null;
+ property = new ComponentInstanceInput(curPropertyDef, value, null);
- property.setValue(validatevalueEiter.left().value());
+ String validPropertyVAlue = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes);
- if (getInputs != null && !getInputs.isEmpty()) {
- List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
- for (GetInputValueDataDefinition getInput : getInputs) {
- List<InputDefinition> inputs = resource.getInputs();
- if (inputs == null || inputs.isEmpty()) {
- log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ",
- property, currentCompInstance.getUniqueId());
- return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- }
+ property.setValue(validPropertyVAlue);
- Optional<InputDefinition> optional = inputs.stream()
- .filter(p -> p.getName().equals(getInput.getInputName())).findAny();
- if (!optional.isPresent()) {
- log.debug("Failed to find input {} ", getInput.getInputName());
- // @@TODO error message
- return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- }
- InputDefinition input = optional.get();
- getInput.setInputId(input.getUniqueId());
- getInputValues.add(getInput);
+ if (isNotEmpty(getInputs)) {
+ List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
+ for (GetInputValueDataDefinition getInput : getInputs) {
+ List<InputDefinition> inputs = resource.getInputs();
+ if (CollectionUtils.isEmpty(inputs)) {
+ log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ",
+ property, currentCompInstance.getUniqueId());
+ throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
- GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
- if (getInputIndex != null) {
- optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName()))
- .findAny();
- if (!optional.isPresent()) {
- log.debug("Failed to find input {} ", getInputIndex.getInputName());
- // @@TODO error message
- return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- }
- InputDefinition inputIndex = optional.get();
- getInputIndex.setInputId(inputIndex.getUniqueId());
- getInputValues.add(getInputIndex);
- }
- }
- property.setGetInputValues(getInputValues);
+ Optional<InputDefinition> optional = inputs.stream()
+ .filter(p -> p.getName().equals(getInput.getInputName())).findAny();
+ if (!optional.isPresent()) {
+ log.debug("Failed to find input {} ", getInput.getInputName());
+ // @@TODO error message
+ throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
- instPropList.add(property);
- // delete overriden property
- currPropertiesMap.remove(property.getName());
+ InputDefinition input = optional.get();
+ getInput.setInputId(input.getUniqueId());
+ getInputValues.add(getInput);
+
+ GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
+ processGetInput(getInputValues, inputs, getInputIndex);
}
- // add rest of properties
- if (!currPropertiesMap.isEmpty()) {
- for (InputDefinition value : currPropertiesMap.values()) {
- instPropList.add(new ComponentInstanceInput(value));
- }
+ property.setGetInputValues(getInputValues);
+ }
+ instPropList.add(property);
+ // delete overriden property
+ currPropertiesMap.remove(property.getName());
+ }
+
+ private void processGetInput(List<GetInputValueDataDefinition> getInputValues, List<InputDefinition> inputs, GetInputValueDataDefinition getInputIndex) {
+ Optional<InputDefinition> optional;
+ if (getInputIndex != null) {
+ optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName()))
+ .findAny();
+ if (!optional.isPresent()) {
+ log.debug("Failed to find input {} ", getInputIndex.getInputName());
+ // @@TODO error message
+ throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
- instInputs.put(currentCompInstance.getUniqueId(), instPropList);
+ InputDefinition inputIndex = optional.get();
+ getInputIndex.setInputId(inputIndex.getUniqueId());
+ getInputValues.add(getInputIndex);
+ }
+ }
+
+ private void addInput(Map<String, InputDefinition> currPropertiesMap, InputDefinition prop) {
+ String propName = prop.getName();
+ if (!currPropertiesMap.containsKey(propName)) {
+ currPropertiesMap.put(propName, prop);
}
- return componentsUtils.getResponseFormat(ActionStatus.OK);
}
private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
- Resource resource, Resource originResource, ComponentInstance currentCompInstance, String yamlName,
+ Resource resource, Resource originResource, ComponentInstance currentCompInstance,
Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) {
Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
- Map<String, PropertyDefinition> currPropertiesMap = new HashMap<String, PropertyDefinition>();
+ Map<String, PropertyDefinition> currPropertiesMap = new HashMap<>();
List<PropertyDefinition> listFromMap = originResource.getProperties();
if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) {
log.debug("failed to find properties ");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
- return responseFormat;
+ return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
}
if (listFromMap == null || listFromMap.isEmpty()) {
return componentsUtils.getResponseFormat(ActionStatus.OK);
@@ -3243,9 +2754,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
String propName = propertyInfo.getName();
if (!currPropertiesMap.containsKey(propName)) {
log.debug("failed to find property {} ", propName);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
+ return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
propName);
- return responseFormat;
}
PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
ComponentInstanceProperty property = null;
@@ -3257,56 +2767,38 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
getInputs = propertyInfo.getGet_input();
isValidate = getInputs == null || getInputs.isEmpty();
if (isValidate) {
- value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(),
+ value = getPropertyJsonStringValue(propertyInfo.getValue(),
curPropertyDef.getType());
- } else
- value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(),
- ToscaTagNamesEnum.GET_INPUT.getElementName());
+ } else {
+ value = getPropertyJsonStringValue(propertyInfo.getValue(),
+ TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
+ }
}
String innerType = null;
property = new ComponentInstanceProperty(curPropertyDef, value, null);
- Either<String, StorageOperationStatus> validatevalueEiter = validatePropValueBeforeCreate(property,
- value, isValidate, innerType, allDataTypes);
- if (validatevalueEiter.isRight()) {
- return componentsUtils.getResponseFormat(
- componentsUtils.convertFromStorageResponse(validatevalueEiter.right().value()));
- }
-
- property.setValue(validatevalueEiter.left().value());
+ String validatePropValue = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes);
+ property.setValue(validatePropValue);
if (getInputs != null && !getInputs.isEmpty()) {
List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
for (GetInputValueDataDefinition getInput : getInputs) {
List<InputDefinition> inputs = resource.getInputs();
if (inputs == null || inputs.isEmpty()) {
- log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ",
- property, currentCompInstance.getUniqueId());
- return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- }
-
- Optional<InputDefinition> optional = inputs.stream()
- .filter(p -> p.getName().equals(getInput.getInputName())).findAny();
- if (!optional.isPresent()) {
- log.debug("Failed to find input {} ", getInput.getInputName());
- // @@TODO error message
- return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ log.debug("Failed to add property {} to instance. Inputs list is empty ", property);
+ rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
+ .stream()
+ .map(GetInputValueDataDefinition::getInputName)
+ .collect(toList()).toString());
}
- InputDefinition input = optional.get();
+ InputDefinition input = findInputByName(inputs, getInput);
getInput.setInputId(input.getUniqueId());
getInputValues.add(getInput);
GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
if (getInputIndex != null) {
- optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName()))
- .findAny();
- if (!optional.isPresent()) {
- log.debug("Failed to find input {} ", getInputIndex.getInputName());
- // @@TODO error message
- return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- }
- InputDefinition inputIndex = optional.get();
- getInputIndex.setInputId(inputIndex.getUniqueId());
+ input = findInputByName(inputs, getInputIndex);
+ getInputIndex.setInputId(input.getUniqueId());
getInputValues.add(getInputIndex);
}
@@ -3337,7 +2829,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
// by
// capability
// type
- return findAviableCapability(validReq, currentCapCompInstance);
+ return findAvailableCapability(validReq, currentCapCompInstance);
}
return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo);
}
@@ -3356,8 +2848,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
cap = capByName.get();
- if (cap.getMaxOccurrences() != null
- && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
+ if (isBoundedByOccurrences(cap)) {
String leftOccurrences = cap.getLeftOccurrences();
int left = Integer.parseInt(leftOccurrences);
if (left > 0) {
@@ -3370,36 +2861,31 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return cap;
}
- private CapabilityDefinition findAviableCapability(RequirementDefinition validReq,
- ComponentInstance currentCapCompInstance) {
- CapabilityDefinition aviableCapForRel = null;
- Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
+ private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance instance) {
+ Map<String, List<CapabilityDefinition>> capMap = instance.getCapabilities();
if (capMap.containsKey(validReq.getCapability())) {
List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
for (CapabilityDefinition cap : capList) {
- if (cap.getMaxOccurrences() != null
- && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
- String leftOccurrences = cap.getLeftOccurrences();
- if (leftOccurrences == null) {
- leftOccurrences = cap.getMaxOccurrences();
- }
+ if (isBoundedByOccurrences(cap)) {
+ String leftOccurrences = cap.getLeftOccurrences() != null ?
+ cap.getLeftOccurrences() : cap.getMaxOccurrences();
int left = Integer.parseInt(leftOccurrences);
if (left > 0) {
--left;
cap.setLeftOccurrences(String.valueOf(left));
- aviableCapForRel = cap;
- break;
- } else {
- continue;
+ return cap;
}
} else {
- aviableCapForRel = cap;
- break;
+ return cap;
}
}
}
- return aviableCapForRel;
+ return null;
+ }
+
+ private boolean isBoundedByOccurrences(CapabilityDefinition cap) {
+ return cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES);
}
private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName,
@@ -3471,140 +2957,26 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(validRegDef);
}
- @SuppressWarnings("unchecked")
- public Either<ParsedToscaYamlInfo, ResponseFormat> parseResourceInfoFromYaml(String yamlFileName, Resource resource,
- String resourceYml, Map<String, String> createdNodesToscaResourceNames,
- Map<String, NodeTypeInfo> nodeTypesInfo, String nodeName) {
-
- Map<String, Object> mappedToscaTemplate;
- if (nodeTypesInfo != null && nodeName != null && nodeTypesInfo.containsKey(nodeName)) {
- mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
- } else {
- try {
- // DE154502 Fail if duplicate key found in file
- mappedToscaTemplate = ImportUtils.loadYamlAsStrictMap(resourceYml);
-
- } catch (ParserException e) {
- log.error("Failed to load yaml file {}", yamlFileName, e);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.TOSCA_PARSE_ERROR,
- yamlFileName, e.getMessage());
- return Either.right(responseFormat);
- }
- }
- Either<Object, ResultStatusEnum> toscaElementEither = ImportUtils.findToscaElement(mappedToscaTemplate,
- ToscaTagNamesEnum.TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL);
- if (toscaElementEither.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
- return Either.right(responseFormat);
- }
-
- Either<Map<String, InputDefinition>, ResponseFormat> createInputsEither = createInputsFromYaml(yamlFileName,
- mappedToscaTemplate, resource);
- if (createInputsEither.isRight()) {
- ResponseFormat responseFormat = createInputsEither.right().value();
- return Either.right(responseFormat);
- }
-
- Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> uploadResInstancesEither = createResourcesInstanceInfoFromYaml(
- yamlFileName, mappedToscaTemplate, resource, createdNodesToscaResourceNames);
- if (uploadResInstancesEither.isRight()) {
- ResponseFormat responseFormat = uploadResInstancesEither.right().value();
- return Either.right(responseFormat);
- }
-
- Either<Map<String, GroupDefinition>, ResponseFormat> createGroupsFromYaml = createGroupsFromYaml(yamlFileName,
- mappedToscaTemplate, resource);
- if (createGroupsFromYaml.isRight()) {
- ResponseFormat responseFormat = createGroupsFromYaml.right().value();
- return Either.right(responseFormat);
- }
-
- ParsedToscaYamlInfo parsedToscaYamlInfo = new ParsedToscaYamlInfo();
- parsedToscaYamlInfo.setInputs(createInputsEither.left().value());
- parsedToscaYamlInfo.setInstances(uploadResInstancesEither.left().value());
- parsedToscaYamlInfo.setGroups(createGroupsFromYaml.left().value());
-
- return Either.left(parsedToscaYamlInfo);
- }
-
- private Either<Resource, ResponseFormat> createResourceInstances(User user, String yamlName, Resource resource,
- Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, boolean inTransaction, boolean needLock,
- Map<String, Resource> nodeNamespaceMap) {
+ private Resource createResourceInstances(String yamlName, Resource resource,
+ Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
+ Map<String, Resource> nodeNamespaceMap) {
Either<Resource, ResponseFormat> eitherResource = null;
log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
- if (uploadResInstancesMap == null || uploadResInstancesMap.isEmpty()) {
+ if (isEmpty(uploadResInstancesMap)) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
-
- return Either.right(responseFormat);
-
+ throw new ComponentException(responseFormat);
}
- Map<String, Resource> existingnodeTypeMap = new HashMap<>();
- if (nodeNamespaceMap != null && !nodeNamespaceMap.isEmpty()) {
- nodeNamespaceMap.entrySet().stream()
- .forEach(x -> existingnodeTypeMap.put(x.getValue().getToscaResourceName(), x.getValue()));
+ Map<String, Resource> existingNodeTypeMap = new HashMap<>();
+ if (MapUtils.isNotEmpty(nodeNamespaceMap)) {
+ nodeNamespaceMap.forEach((k, v) -> existingNodeTypeMap.put(v.getToscaResourceName(), v));
}
-
- Iterator<Entry<String, UploadComponentInstanceInfo>> nodesInfoValue = uploadResInstancesMap.entrySet()
- .iterator();
Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
- while (nodesInfoValue.hasNext()) {
- log.debug("*************Going to create resource instances {}", yamlName);
- Entry<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoEntry = nodesInfoValue.next();
- UploadComponentInstanceInfo uploadComponentInstanceInfo = uploadComponentInstanceInfoEntry.getValue();
-
- // updating type if the type is node type name - we need to take the
- // updated name
- log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName());
- if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
- uploadComponentInstanceInfo
- .setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
- }
-
- eitherResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo,
- existingnodeTypeMap);
- if (eitherResource.isRight()) {
- return eitherResource;
- }
- Resource refResource = eitherResource.left().value();
-
- ComponentInstance componentInstance = new ComponentInstance();
-
- componentInstance.setComponentUid(refResource.getUniqueId());
-
- ComponentTypeEnum containerComponentType = resource.getComponentType();
- NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
-
- if (containerNodeType.equals(NodeTypeEnum.Resource)
- && MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities())
- && MapUtils.isNotEmpty(refResource.getCapabilities())) {
- setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
- Either<Map<String, List<CapabilityDefinition>>, ResponseFormat> getValidComponentInstanceCapabilitiesRes = getValidComponentInstanceCapabilities(
- refResource.getUniqueId(), refResource.getCapabilities(),
- uploadComponentInstanceInfo.getCapabilities());
- if (getValidComponentInstanceCapabilitiesRes.isRight()) {
- return Either.right(getValidComponentInstanceCapabilitiesRes.right().value());
- } else {
- componentInstance.setCapabilities(getValidComponentInstanceCapabilitiesRes.left().value());
- }
- }
- if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
- log.debug(
- "createResourceInstances - not found lates version for resource instance with name {} and type ",
- uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
- yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
- return Either.right(responseFormat);
- }
- Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
- componentInstance.setName(uploadComponentInstanceInfo.getName());
- componentInstance.setIcon(origResource.getIcon());
-
- resourcesInstancesMap.put(componentInstance, origResource);
-
- }
- if (MapUtils.isNotEmpty(resourcesInstancesMap)) {
+ uploadResInstancesMap
+ .values()
+ .forEach(i->createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap, existingNodeTypeMap, resourcesInstancesMap));
+ if (isNotEmpty(resourcesInstancesMap)) {
StorageOperationStatus status = toscaOperationFacade.associateComponentInstancesToComponent(resource,
resourcesInstancesMap, false);
if (status != null && status != StorageOperationStatus.OK) {
@@ -3612,41 +2984,77 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
ResponseFormat responseFormat = componentsUtils
.getResponseFormat(componentsUtils.convertFromStorageResponse(status));
eitherResource = Either.right(responseFormat);
- return eitherResource;
+ throw new ComponentException(eitherResource.right().value());
}
-
}
-
log.debug("*************Going to get resource {}", resource.getUniqueId());
- ComponentParametersView parametersView = new ComponentParametersView();
- parametersView.disableAll();
- parametersView.setIgnoreComponentInstances(false);
- parametersView.setIgnoreUsers(false);
- parametersView.setIgnoreInputs(false); // inputs are read when creating
- // property values on instances
- Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade
- .getToscaElement(resource.getUniqueId(), parametersView);
+ Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
+ .getToscaElement(resource.getUniqueId(), getComponentWithInstancesFilter());
log.debug("*************finished to get resource {}", resource.getUniqueId());
- if (eitherGerResource.isRight()) {
+ if (eitherGetResource.isRight()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
- componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
-
- return Either.right(responseFormat);
-
+ componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
+ throw new ComponentException(responseFormat);
}
-
- if (eitherGerResource.left().value().getComponentInstances() == null
- || eitherGerResource.left().value().getComponentInstances().isEmpty()) {
-
- log.debug("Error when create resource inctanse from csar. ComponentInstances list empty");
+ if (CollectionUtils.isEmpty(eitherGetResource.left().value().getComponentInstances())) {
+ log.debug("Error when create resource instance from csar. ComponentInstances list empty");
BeEcompErrorManager.getInstance().logBeDaoSystemError(
- "Error when create resource inctanse from csar. ComponentInstances list empty");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
- return Either.right(responseFormat);
+ "Error when create resource instance from csar. ComponentInstances list empty");
+ throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
+ }
+ return eitherGetResource.left().value();
+ }
+ private void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName,
+ Resource resource, Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingnodeTypeMap, Map<ComponentInstance, Resource> resourcesInstancesMap) {
+ Either<Resource, ResponseFormat> eitherResource;
+ log.debug("*************Going to create resource instances {}", yamlName);
+ // updating type if the type is node type name - we need to take the
+ // updated name
+ log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName());
+ if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
+ uploadComponentInstanceInfo
+ .setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
+ }
+ Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo,
+ existingnodeTypeMap);
+
+ ComponentInstance componentInstance = new ComponentInstance();
+ componentInstance.setComponentUid(refResource.getUniqueId());
+ ComponentTypeEnum containerComponentType = resource.getComponentType();
+ NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
+ if (containerNodeType.equals(NodeTypeEnum.Resource)
+ && isNotEmpty(uploadComponentInstanceInfo.getCapabilities())
+ && isNotEmpty(refResource.getCapabilities())) {
+ setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
+ Map<String, List<CapabilityDefinition>> validComponentInstanceCapabilities = getValidComponentInstanceCapabilities(
+ refResource.getUniqueId(), refResource.getCapabilities(),
+ uploadComponentInstanceInfo.getCapabilities());
+ componentInstance.setCapabilities(validComponentInstanceCapabilities);
+ }
+ if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
+ log.debug(
+ "createResourceInstances - not found lates version for resource instance with name {} and type ",
+ uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
+ yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
+ throw new ComponentException(responseFormat);
}
+ Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
+ componentInstance.setName(uploadComponentInstanceInfo.getName());
+ componentInstance.setIcon(origResource.getIcon());
+ resourcesInstancesMap.put(componentInstance, origResource);
+ }
- return Either.left(eitherGerResource.left().value());
+ private ComponentParametersView getComponentWithInstancesFilter() {
+ ComponentParametersView parametersView = new ComponentParametersView();
+ parametersView.disableAll();
+ parametersView.setIgnoreComponentInstances(false);
+ parametersView.setIgnoreInputs(false);
+ // inputs are read when creating
+ // property values on instances
+ parametersView.setIgnoreUsers(false);
+ return parametersView;
}
private void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities,
@@ -3664,18 +3072,17 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
c.setType(cap.getType());
});
}
- ;
});
}
}
- private Either<Resource, ResponseFormat> validateResourceInstanceBeforeCreate(String yamlName,
- UploadComponentInstanceInfo uploadComponentInstanceInfo, Map<String, Resource> nodeNamespaceMap) {
- log.debug(
- "validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type before create",
+ private Resource validateResourceInstanceBeforeCreate(String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo,
+ Map<String, Resource> nodeNamespaceMap) {
+
+ log.debug("validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type before create",
uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
- Resource refResource = null;
+ Resource refResource;
if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType());
} else {
@@ -3687,7 +3094,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(
componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
- return Either.right(responseFormat);
+ throw new ComponentException(responseFormat);
}
refResource = findResourceEither.left().value();
nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
@@ -3699,542 +3106,18 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
refResource.getName(), componentState);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE,
refResource.getComponentType().getValue(), refResource.getName(), componentState);
- return Either.right(responseFormat);
+ throw new ComponentException(responseFormat);
}
if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) {
log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", refResource.getResourceType());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
- return Either.right(responseFormat);
- }
- return Either.left(refResource);
- }
-
- private Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> createResourcesInstanceInfoFromYaml(
- String yamlFileName, Map<String, Object> toscaJson, Resource resource,
- Map<String, String> createdNodesToscaResourceNames) {
- Map<String, UploadComponentInstanceInfo> moduleComponentInstances = new HashMap<String, UploadComponentInstanceInfo>();
- Map<String, Object> substitutionMappings = null;
- Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> result = Either.left(moduleComponentInstances);
- Either<Map<String, Object>, ResultStatusEnum> eitherNodesTemlates = ImportUtils
- .findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.NODE_TEMPLATES);
- Either<Map<String, Object>, ResultStatusEnum> eitherSubstitutionMappings = ImportUtils
- .findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS);
- if (eitherSubstitutionMappings.isLeft()) {
- substitutionMappings = eitherSubstitutionMappings.left().value();
- }
- if (eitherNodesTemlates.isLeft()) {
- Map<String, Object> jsonNodeTemplates = eitherNodesTemlates.left().value();
-
- Iterator<Entry<String, Object>> nodesNameValue = jsonNodeTemplates.entrySet().iterator();
- while (nodesNameValue.hasNext()) {
- Entry<String, Object> nodeNameValue = nodesNameValue.next();
- Either<UploadComponentInstanceInfo, ResponseFormat> eitherNode = createModuleComponentInstanceInfo(
- nodeNameValue, substitutionMappings, createdNodesToscaResourceNames);
- if (eitherNode.isRight()) {
- log.info("error when creating node template:{}, for resource:{}", nodeNameValue.getKey(),
- resource.getName());
- return Either.right(eitherNode.right().value());
- } else {
- UploadComponentInstanceInfo uploadComponentInstanceInfo = eitherNode.left().value();
- moduleComponentInstances.put(nodeNameValue.getKey(), uploadComponentInstanceInfo);
- }
-
- }
-
- }
- if (moduleComponentInstances.isEmpty()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE,
- yamlFileName);
- return Either.right(responseFormat);
- }
-
- return result;
- }
-
- @SuppressWarnings("unchecked")
- private Either<UploadComponentInstanceInfo, ResponseFormat> createModuleComponentInstanceInfo(
- Entry<String, Object> nodeTemplateJsonEntry, Map<String, Object> substitutionMappings,
- Map<String, String> createdNodesToscaResourceNames) {
-
- UploadComponentInstanceInfo nodeTemplateInfo = new UploadComponentInstanceInfo();
- Either<UploadComponentInstanceInfo, ResponseFormat> result = Either.left(nodeTemplateInfo);
- nodeTemplateInfo.setName(nodeTemplateJsonEntry.getKey());
- try {
- if (nodeTemplateJsonEntry.getValue() instanceof String) {
- String nodeTemplateJsonString = (String) nodeTemplateJsonEntry.getValue();
- nodeTemplateInfo.setType(nodeTemplateJsonString);
- } else if (nodeTemplateJsonEntry.getValue() instanceof Map) {
- Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) nodeTemplateJsonEntry.getValue();
- // Type
- if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
- String toscaResourceType = (String) nodeTemplateJsonMap
- .get(ToscaTagNamesEnum.TYPE.getElementName());
- if (createdNodesToscaResourceNames.containsKey(toscaResourceType)) {
- toscaResourceType = createdNodesToscaResourceNames.get(toscaResourceType);
- }
- nodeTemplateInfo.setType(toscaResourceType);
- }
-
- if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.REQUIREMENTS.getElementName())) {
- Either<Map<String, List<UploadReqInfo>>, ResponseFormat> regResponse = createReqModuleFromYaml(
- nodeTemplateInfo, nodeTemplateJsonMap);
- if (regResponse.isRight())
- return Either.right(regResponse.right().value());
- if (regResponse.left().value().size() > 0) {
- nodeTemplateInfo.setRequirements(regResponse.left().value());
- }
- }
-
- if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITIES.getElementName())) {
- Either<Map<String, List<UploadCapInfo>>, ResponseFormat> eitherCapRes = createCapModuleFromYaml(
- nodeTemplateInfo, nodeTemplateJsonMap);
- if (eitherCapRes.isRight())
- return Either.right(eitherCapRes.right().value());
- if (eitherCapRes.left().value().size() > 0) {
- nodeTemplateInfo.setCapabilities(eitherCapRes.left().value());
- }
- }
- if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
- Either<Map<String, List<UploadPropInfo>>, ResponseFormat> regResponse = createPropModuleFromYaml(
- nodeTemplateJsonMap);
- if (regResponse.isRight())
- return Either.right(regResponse.right().value());
- if (regResponse.left().value().size() > 0) {
- nodeTemplateInfo.setProperties(regResponse.left().value());
- }
- }
- if (substitutionMappings != null) {
- if (substitutionMappings.containsKey(ToscaTagNamesEnum.CAPABILITIES.getElementName())) {
- Either<Map<String, String>, ResponseFormat> getCapNamesToUpdateRes = getNamesToUpdate(
- nodeTemplateInfo, (Map<String, List<String>>) substitutionMappings
- .get(ToscaTagNamesEnum.CAPABILITIES.getElementName()));
- if (getCapNamesToUpdateRes.isRight())
- return Either.right(getCapNamesToUpdateRes.right().value());
- if (getCapNamesToUpdateRes.left().value().size() > 0) {
- nodeTemplateInfo.setCapabilitiesNamesToUpdate(getCapNamesToUpdateRes.left().value());
- }
- }
- if (substitutionMappings.containsKey(ToscaTagNamesEnum.REQUIREMENTS.getElementName())) {
- Either<Map<String, String>, ResponseFormat> getReqNamesToUpdateRes = getNamesToUpdate(
- nodeTemplateInfo, (Map<String, List<String>>) substitutionMappings
- .get(ToscaTagNamesEnum.REQUIREMENTS.getElementName()));
- if (getReqNamesToUpdateRes.isRight())
- return Either.right(getReqNamesToUpdateRes.right().value());
- if (getReqNamesToUpdateRes.left().value().size() > 0) {
- nodeTemplateInfo.setRequirementsNamesToUpdate(getReqNamesToUpdateRes.left().value());
- }
- }
- }
- } else {
-
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
-
- }
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create capability");
- log.debug("error when creating capability, message:{}", e.getMessage(), e);
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
- }
-
- return result;
- }
-
- private Either<Map<String, String>, ResponseFormat> getNamesToUpdate(UploadComponentInstanceInfo nodeTemplateInfo,
- Map<String, List<String>> elements) {
- Either<Map<String, String>, ResponseFormat> response;
- try {
- Map<String, String> namesToUpdate = elements.entrySet().stream()
- .filter(e -> e.getValue().get(0).equalsIgnoreCase(nodeTemplateInfo.getName()))
- .collect(Collectors.toMap(e -> e.getValue().get(1), e -> e.getKey()));
- response = Either.left(namesToUpdate);
- } catch (Exception e) {
- log.debug("The exception occurred upon adding names to update for instance {}: ", nodeTemplateInfo.getName(), e);
- response = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ throw new ComponentException(responseFormat);
}
- return response;
+ return refResource;
}
- @SuppressWarnings("unchecked")
- private Either<Map<String, List<UploadPropInfo>>, ResponseFormat> createPropModuleFromYaml(
- Map<String, Object> nodeTemplateJsonMap) {
- Map<String, List<UploadPropInfo>> moduleProp = new HashMap<String, List<UploadPropInfo>>();
- Either<Map<String, List<UploadPropInfo>>, ResponseFormat> response = Either.left(moduleProp);
- Either<Map<String, Object>, ResultStatusEnum> toscaProperties = ImportUtils
- .findFirstToscaMapElement(nodeTemplateJsonMap, ToscaTagNamesEnum.PROPERTIES);
- if (toscaProperties.isLeft()) {
- Map<String, Object> jsonProperties = toscaProperties.left().value();
- for (Entry<String, Object> jsonPropObj : jsonProperties.entrySet()) {
- // Property
- String propName = jsonPropObj.getKey();
- Object propValue = jsonPropObj.getValue();
-
- if (valueContainsPattern(STR_REPLACE_PATTERN, propValue)) {
- log.trace("Ignore property value {}.", propName);
- continue;
- }
-
- if (valueContainsPattern(TOKEN_PATTERN, propValue)) {
- log.trace("Ignore property value {}.", propName);
- continue;
- }
- if (valueContainsPattern(GET_PROPERTY_PATTERN, propValue)) {
- log.trace("Ignore property value {}.", propName);
- continue;
- }
-
- if (valueContainsPattern(CONCAT_PATTERN, propValue)) {
- log.trace("Ignore property value {}.", propName);
- continue;
- }
-
- if (valueContainsPattern(GET_ATTRIBUTE_PATTERN, propValue)) {
- log.trace("Ignore property value {}.", propName);
- continue;
- }
-
- UploadPropInfo propertyDef = new UploadPropInfo();
- propertyDef.setValue(propValue);
- propertyDef.setName(propName);
- if (propValue instanceof Map) {
- if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
- propertyDef.setType(((Map<String, Object>) propValue)
- .get(ToscaTagNamesEnum.TYPE.getElementName()).toString());
- }
-
- if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())
- || ImportUtils.getPropertyJsonStringValue(propValue, ToscaPropertyType.MAP.getType())
- .contains(ToscaTagNamesEnum.GET_INPUT.getElementName())) {
- createGetInputModuleFromMap(propName, (Map<String, Object>) propValue, propertyDef);
- }
-
- if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
- propertyDef.setDescription(((Map<String, Object>) propValue)
- .get(ToscaTagNamesEnum.DESCRIPTION.getElementName()).toString());
- }
- if (((Map<String, Object>) propValue)
- .containsKey(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName())) {
- propertyDef.setValue(((Map<String, Object>) propValue)
- .get(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName()));
- }
- if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.IS_PASSWORD.getElementName())) {
- propertyDef.setPassword(Boolean.getBoolean(((Map<String, Object>) propValue)
- .get(ToscaTagNamesEnum.IS_PASSWORD.getElementName()).toString()));
- } else {
- propertyDef.setValue(propValue);
- }
- } else if (propValue instanceof List) {
- List<Object> propValueList = (List<Object>) propValue;
-
- createInputPropList(propertyDef, propValueList);
- propertyDef.setValue(propValue);
- }
-
- if (moduleProp.containsKey(propName)) {
- moduleProp.get(propName).add(propertyDef);
- } else {
- List<UploadPropInfo> list = new ArrayList<UploadPropInfo>();
- list.add(propertyDef);
- moduleProp.put(propName, list);
- }
- }
- }
- return response;
- }
-
- @SuppressWarnings("unchecked")
- private void createInputPropList(UploadPropInfo propertyDef, List<Object> propValueList) {
- for (Object objValue : propValueList) {
-
- if (objValue instanceof Map) {
- Map<String, Object> objMap = (Map<String, Object>) objValue;
- if (objMap.containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName()))
- createGetInputModuleFromMap(propertyDef.getName(), objMap, propertyDef);
- else {
- Set<String> keys = objMap.keySet();
- for (String key : keys) {
- Object value = objMap.get(key);
- if (value instanceof Map) {
- createGetInputModuleFromMap(key, (Map<String, Object>) value, propertyDef);
-
- } else if (value instanceof List) {
- List<Object> propSubValueList = (List<Object>) value;
-
- createInputPropList(propertyDef, propSubValueList);
- }
-
- }
- }
-
- } else if (objValue instanceof List) {
- List<Object> propSubValueList = (List<Object>) objValue;
-
- createInputPropList(propertyDef, propSubValueList);
-
- }
-
- }
- }
-
- @SuppressWarnings("unchecked")
- private void createGetInputModuleFromMap(String propName, Map<String, Object> propValue,
- UploadPropInfo propertyDef) {
-
- if (propValue.containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) {
- Object getInput = propValue.get(ToscaTagNamesEnum.GET_INPUT.getElementName());
- GetInputValueDataDefinition getInputInfo = new GetInputValueDataDefinition();
- List<GetInputValueDataDefinition> getInputs = propertyDef.getGet_input();
- if (getInputs == null) {
- getInputs = new ArrayList<GetInputValueDataDefinition>();
- }
- if (getInput instanceof String) {
-
- getInputInfo.setInputName((String) getInput);
- getInputInfo.setPropName(propName);
-
- } else if (getInput instanceof List) {
- List<Object> getInputList = (List<Object>) getInput;
- getInputInfo.setPropName(propName);
- getInputInfo.setInputName((String) getInputList.get(0));
- if (getInputList.size() > 1) {
- Object indexObj = getInputList.get(1);
- if (indexObj instanceof Integer) {
- getInputInfo.setIndexValue((Integer) indexObj);
- } else if (indexObj instanceof Float) {
- int index = ((Float) indexObj).intValue();
- getInputInfo.setIndexValue(index);
- } else if (indexObj instanceof Map && ((Map<String, Object>) indexObj)
- .containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) {
- Object index = ((Map<String, Object>) indexObj)
- .get(ToscaTagNamesEnum.GET_INPUT.getElementName());
- GetInputValueDataDefinition getInputInfoIndex = new GetInputValueDataDefinition();
- getInputInfoIndex.setInputName((String) index);
- getInputInfoIndex.setPropName(propName);
- getInputInfo.setGetInputIndex(getInputInfoIndex);
- }
- getInputInfo.setList(true);
- }
-
- }
- getInputs.add(getInputInfo);
- propertyDef.setGet_input(getInputs);
- propertyDef.setValue(propValue);
- } else {
- Set<String> keys = propValue.keySet();
- for (String key : keys) {
- Object value = propValue.get(key);
- if (value instanceof Map) {
- createGetInputModuleFromMap(key, (Map<String, Object>) value, propertyDef);
-
- } else if (value instanceof List) {
- List<Object> valueList = (List<Object>) value;
- for (Object o : valueList) {
- if (o instanceof Map) {
- createGetInputModuleFromMap(key, (Map<String, Object>) o, propertyDef);
-
- }
- }
-
- }
-
- }
-
- }
- }
-
-
- private boolean valueContainsPattern(Pattern pattern, Object propValue) {
-
- log.debug("valueContainsToken value is {}", propValue);
- boolean result = false;
- if (propValue != null) {
- log.trace("valueContainspattern value is {}", propValue.getClass());
- Matcher matcher = pattern.matcher(propValue.toString());
- result = matcher.find();
- }
-
- return result;
-
- }
-
- @SuppressWarnings("unchecked")
- private Either<Map<String, List<UploadReqInfo>>, ResponseFormat> createReqModuleFromYaml(
- UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
- Map<String, List<UploadReqInfo>> moduleRequirements = new HashMap<String, List<UploadReqInfo>>();
- Either<Map<String, List<UploadReqInfo>>, ResponseFormat> response = Either.left(moduleRequirements);
- Either<List<Object>, ResultStatusEnum> requirementsListRes = ImportUtils
- .findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.REQUIREMENTS);
-
- if (requirementsListRes.isLeft()) {
- for (Object jsonReqObj : requirementsListRes.left().value()) {
- String reqName = ((Map<String, Object>) jsonReqObj).keySet().iterator().next();
- Object reqJson = ((Map<String, Object>) jsonReqObj).get(reqName);
- Either<UploadReqInfo, ResponseFormat> eitherCap = addModuleNodeTemplateReq(nodeTemplateInfo,
- moduleRequirements, reqJson, reqName);
- if (eitherCap.isRight()) {
- return Either.right(eitherCap.right().value());
- }
- }
- } else {
- Either<Map<String, Object>, ResultStatusEnum> requirementsMapRes = ImportUtils
- .findFirstToscaMapElement(nodeTemplateJsonMap, ToscaTagNamesEnum.REQUIREMENTS);
- if (requirementsMapRes.isLeft()) {
- for (Map.Entry<String, Object> entry : requirementsMapRes.left().value().entrySet()) {
- String reqName = entry.getKey();
- Object reqJson = entry.getValue();
- Either<UploadReqInfo, ResponseFormat> eitherCap = addModuleNodeTemplateReq(nodeTemplateInfo,
- moduleRequirements, reqJson, reqName);
- if (eitherCap.isRight()) {
- return Either.right(eitherCap.right().value());
- }
- }
- }
- }
- return response;
- }
-
- private Either<UploadReqInfo, ResponseFormat> addModuleNodeTemplateReq(UploadComponentInstanceInfo nodeTemplateInfo,
- Map<String, List<UploadReqInfo>> moduleRequirements, Object requirementJson, String requirementName) {
-
- Either<UploadReqInfo, ResponseFormat> eitherRequirement = createModuleNodeTemplateReg(requirementJson);
- if (eitherRequirement.isRight()) {
- log.info("error when creating Requirement:{}, for node:{}", requirementName, nodeTemplateInfo);
- return Either.right(eitherRequirement.right().value());
- } else {
- UploadReqInfo requirementDef = eitherRequirement.left().value();
- requirementDef.setName(requirementName);
- if (moduleRequirements.containsKey(requirementName)) {
- moduleRequirements.get(requirementName).add(requirementDef);
- } else {
- List<UploadReqInfo> list = new ArrayList<UploadReqInfo>();
- list.add(requirementDef);
- moduleRequirements.put(requirementName, list);
- }
- }
- return Either.left(eitherRequirement.left().value());
- }
-
- @SuppressWarnings("unchecked")
- private Either<Map<String, List<UploadCapInfo>>, ResponseFormat> createCapModuleFromYaml(
- UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
- Map<String, List<UploadCapInfo>> moduleCap = new HashMap<>();
- Either<Map<String, List<UploadCapInfo>>, ResponseFormat> response = Either.left(moduleCap);
- Either<List<Object>, ResultStatusEnum> capabilitiesListRes = ImportUtils
- .findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.CAPABILITIES);
- if (capabilitiesListRes.isLeft()) {
- for (Object jsonCapObj : capabilitiesListRes.left().value()) {
- String key = ((Map<String, Object>) jsonCapObj).keySet().iterator().next();
- Object capJson = ((Map<String, Object>) jsonCapObj).get(key);
- Either<UploadCapInfo, ResponseFormat> eitherCap = addModuleNodeTemplateCap(nodeTemplateInfo, moduleCap,
- capJson, key);
- if (eitherCap.isRight()) {
- return Either.right(eitherCap.right().value());
- }
- }
- } else {
- Either<Map<String, Object>, ResultStatusEnum> capabilitiesMapRes = ImportUtils
- .findFirstToscaMapElement(nodeTemplateJsonMap, ToscaTagNamesEnum.CAPABILITIES);
- if (capabilitiesMapRes.isLeft()) {
- for (Map.Entry<String, Object> entry : capabilitiesMapRes.left().value().entrySet()) {
- String capName = entry.getKey();
- Object capJson = entry.getValue();
- Either<UploadCapInfo, ResponseFormat> eitherCap = addModuleNodeTemplateCap(nodeTemplateInfo,
- moduleCap, capJson, capName);
- if (eitherCap.isRight()) {
- return Either.right(eitherCap.right().value());
- }
- }
- }
- }
- return response;
- }
-
- private Either<UploadCapInfo, ResponseFormat> addModuleNodeTemplateCap(UploadComponentInstanceInfo nodeTemplateInfo,
- Map<String, List<UploadCapInfo>> moduleCap, Object capJson, String key) {
-
- Either<UploadCapInfo, ResponseFormat> eitherCap = createModuleNodeTemplateCap(capJson);
- if (eitherCap.isRight()) {
- log.info("error when creating Capability:{}, for node:{}", key, nodeTemplateInfo);
- return Either.right(eitherCap.right().value());
- } else {
- UploadCapInfo capabilityDef = eitherCap.left().value();
- capabilityDef.setKey(key);
- if (moduleCap.containsKey(key)) {
- moduleCap.get(key).add(capabilityDef);
- } else {
- List<UploadCapInfo> list = new ArrayList<UploadCapInfo>();
- list.add(capabilityDef);
- moduleCap.put(key, list);
- }
- }
- return Either.left(eitherCap.left().value());
- }
-
- @SuppressWarnings("unchecked")
- private Either<UploadCapInfo, ResponseFormat> createModuleNodeTemplateCap(Object capObject) {
- UploadCapInfo capTemplateInfo = new UploadCapInfo();
- Either<UploadCapInfo, ResponseFormat> result = Either.left(capTemplateInfo);
-
- if (capObject instanceof String) {
- String nodeTemplateJsonString = (String) capObject;
- capTemplateInfo.setNode(nodeTemplateJsonString);
- } else if (capObject instanceof Map) {
- Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) capObject;
- // Type
- if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) {
- capTemplateInfo.setNode((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.NODE.getElementName()));
- }
- if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
- capTemplateInfo.setType((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName()));
- }
- if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())) {
- Either<List<Object>, ResultStatusEnum> validSourceTypesRes = ImportUtils
- .findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.VALID_SOURCE_TYPES);
- if (validSourceTypesRes.isLeft()) {
- capTemplateInfo.setValidSourceTypes(validSourceTypesRes.left().value().stream()
- .map(o -> o.toString()).collect(Collectors.toList()));
- }
- }
- if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
- Either<Map<String, List<UploadPropInfo>>, ResponseFormat> regResponse = createPropModuleFromYaml(
- nodeTemplateJsonMap);
- if (regResponse.isRight())
- return Either.right(regResponse.right().value());
- if (!regResponse.left().value().isEmpty()) {
- List<UploadPropInfo> properties = new ArrayList<UploadPropInfo>();
- regResponse.left().value().values().forEach(list -> properties.addAll(list));
- if (!properties.isEmpty())
- capTemplateInfo.setProperties(properties);
- }
- }
- }
- return result;
- }
-
- @SuppressWarnings("unchecked")
- private Either<UploadReqInfo, ResponseFormat> createModuleNodeTemplateReg(Object regObject) {
-
- UploadReqInfo regTemplateInfo = new UploadReqInfo();
- Either<UploadReqInfo, ResponseFormat> result = Either.left(regTemplateInfo);
-
- if (regObject instanceof String) {
- String nodeTemplateJsonString = (String) regObject;
- regTemplateInfo.setNode(nodeTemplateJsonString);
- } else if (regObject instanceof Map) {
- Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) regObject;
- // Type
- if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) {
- regTemplateInfo.setNode((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.NODE.getElementName()));
- }
- // US740820 Relate RIs according to capability name
- if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITY.getElementName())) {
- regTemplateInfo.setCapabilityName(
- (String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.CAPABILITY.getElementName()));
- }
- }
- return result;
- }
public Either<Resource, ResponseFormat> propagateStateToCertified(User user, Resource resource,
LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock,
@@ -4264,12 +3147,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
} finally {
if (result == null || result.isRight()) {
BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
- if (inTransaction == false) {
- log.debug("operation failed. do rollback");
+ if (!inTransaction) {
titanDao.rollback();
}
- } else if (inTransaction == false) {
- log.debug("operation success. do commit");
+ } else if (!inTransaction) {
titanDao.commit();
}
}
@@ -4277,17 +3158,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
private Either<Resource, ResponseFormat> nodeFullCertification(String uniqueId, User user,
LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
- Either<Resource, ResponseFormat> result = lifecycleBusinessLogic.changeState(uniqueId, user,
- LifeCycleTransitionEnum.CERTIFICATION_REQUEST, lifecycleChangeInfo, inTransaction, needLock);
- if (result.isLeft()) {
- result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.START_CERTIFICATION,
- lifecycleChangeInfo, inTransaction, needLock);
- }
- if (result.isLeft()) {
- result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY,
- lifecycleChangeInfo, inTransaction, needLock);
- }
- return result;
+ return lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY,
+ lifecycleChangeInfo, inTransaction, needLock);
}
private Either<Resource, ResponseFormat> nodeForceCertification(Resource resource, User user,
@@ -4296,93 +3168,83 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
needLock);
}
-
- public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResourceByImport(
+ public ImmutablePair<Resource, ActionStatus> createOrUpdateResourceByImport(
Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock,
CsarInfo csarInfo, String nodeName, boolean isNested) {
- // check if resource already exist
- Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade
- .getLatestByName(resource.getName());
- Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> result = null;
-
- // create
- if (latestByName.isRight() && latestByName.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
-
- Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade
- .getLatestByToscaResourceName(resource.getToscaResourceName());
- if (csarInfo != null && csarInfo.isUpdate() && nodeName != null && latestByToscaName.isRight()
- && latestByToscaName.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
- latestByToscaName = toscaOperationFacade
- .getLatestByToscaResourceName(buildNestedToscaResourceName(resource.getResourceType().name(),
- csarInfo.getVfResourceName(), nodeName).getRight());
- // update
- if (latestByToscaName.isLeft()) {
- log.debug("validate derived before update");
- Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(
- latestByToscaName.left().value(), resource,
- ValidationUtils.hasBeenCertified(latestByToscaName.left().value().getVersion()));
- if (eitherValidation.isRight()) {
- result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
- } else {
- result = updateExistingResourceByImport(resource, latestByToscaName.left().value(), user,
- isNormative, needLock, isNested);
- }
- }
- }
- if (result == null && latestByToscaName.isRight()
- && latestByToscaName.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
- result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
- } else if (result == null) {
- StorageOperationStatus status = latestByName.right().value();
+ ImmutablePair<Resource, ActionStatus> result = null;
+ // check if resource already exists (search by tosca name = type)
+ boolean isNestedResource = isNestedResourceUpdate(csarInfo, nodeName);
+ Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade
+ .getLatestByToscaResourceName(resource.getToscaResourceName());
+
+ if (latestByToscaName.isLeft()) {
+ 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());
- log.debug("resource already exist {}. status={}", resource.getName(), status);
+ log.debug("resource already exist new name={} old name={} same type={}", resource.getName(),
+ foundResource.getName(), resource.getToscaResourceName());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
- result = Either.right(responseFormat);
+ throwComponentException(responseFormat);
}
-
- }
-
- // update
- else if (latestByName.isLeft()) {
- result = updateExistingResourceByImport(resource, latestByName.left().value(), user, isNormative, needLock,
- isNested);
- }
-
- // error
- else {
- StorageOperationStatus status = latestByName.right().value();
+ result = updateExistingResourceByImport(resource, foundResource, user, isNormative, needLock, isNested);
+ } else if (isNotFound(latestByToscaName)) {
+ if (isNestedResource) {
+ result = createOrUpdateNestedResource(resource, user, isNormative, isInTransaction, needLock, csarInfo, isNested, nodeName);
+ } else {
+ result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
+ }
+ } else {
+ StorageOperationStatus status = latestByToscaName.right().value();
log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
- componentsUtils.convertFromStorageResponse(latestByName.right().value()), resource);
+ componentsUtils.convertFromStorageResponse(latestByToscaName.right().value()), resource);
componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
- result = Either.right(responseFormat);
+ throwComponentException(responseFormat);
}
return result;
+ }
+ private boolean isNestedResourceUpdate(CsarInfo csarInfo, String nodeName) {
+ return csarInfo != null && csarInfo.isUpdate() && nodeName != null;
}
- private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResourceByImport(Resource resource,
- User user, boolean isNormative, boolean isInTransaction, CsarInfo csarInfo) {
+ private ImmutablePair<Resource, ActionStatus> createOrUpdateNestedResource(Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock, CsarInfo csarInfo, boolean isNested, String nodeName) {
+ Either<Component, StorageOperationStatus> latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(buildNestedToscaResourceName(
+ resource.getResourceType().name(), csarInfo.getVfResourceName(), nodeName).getRight());
+ if (latestByToscaName.isLeft()) {
+ Resource nestedResource = (Resource) latestByToscaName.left().value();
+ log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
+ Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(nestedResource, resource,
+ ValidationUtils.hasBeenCertified(nestedResource.getVersion()));
+ if (eitherValidation.isRight()) {
+ return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
+ }
+ return updateExistingResourceByImport(resource, nestedResource, user, isNormative, needLock, isNested);
+ } else {
+ return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
+ }
+ }
+
+ private boolean isNotFound(Either<Resource, StorageOperationStatus> getResourceEither) {
+ return getResourceEither.isRight() && getResourceEither.right().value() == StorageOperationStatus.NOT_FOUND;
+ }
+
+ private ImmutablePair<Resource, ActionStatus> createResourceByImport(Resource resource,
+ User user, boolean isNormative, boolean isInTransaction, CsarInfo csarInfo) {
log.debug("resource with name {} does not exist. create new resource", resource.getName());
- Either<Resource, ResponseFormat> response = validateResourceBeforeCreate(resource, user,
+ validateResourceBeforeCreate(resource, user,
AuditingActionEnum.IMPORT_RESOURCE, isInTransaction, csarInfo);
- if (response.isRight()) {
- return Either.right(response.right().value());
- }
- Either<Resource, ResponseFormat> createResponse = createResourceByDao(resource, user,
+ Resource createdResource = createResourceByDao(resource, user,
AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction);
- if (createResponse.isRight()) {
- return Either.right(createResponse.right().value());
- } else {
- ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createResponse.left().value(),
- ActionStatus.CREATED);
- ASDCKpiApi.countImportResourcesKPI();
- return Either.left(resourcePair);
-
- }
+ ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createdResource,
+ ActionStatus.CREATED);
+ ASDCKpiApi.countImportResourcesKPI();
+ return resourcePair;
}
public boolean isResourceExist(String resourceName) {
@@ -4390,53 +3252,20 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return latestByName.isLeft();
}
- private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> updateExistingResourceByImport(
+ private ImmutablePair<Resource, ActionStatus> updateExistingResourceByImport(
Resource newResource, Resource oldResource, User user, 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());
- Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> result = null;
+ ImmutablePair<Resource, ActionStatus> resourcePair = null;
try {
- if (needLock) {
- Either<Boolean, ResponseFormat> lockResult = lockComponent(lockedResourceId, oldResource,
- "Update Resource by Import");
- if (lockResult.isRight()) {
- return Either.right(lockResult.right().value());
- }
- }
-
- Either<Resource, ResponseFormat> prepareResourceForUpdate = prepareResourceForUpdate(oldResource, user,
- inTransaction, false);
- if (prepareResourceForUpdate.isRight()) {
- ResponseFormat responseFormat = prepareResourceForUpdate.right().value();
- log.info("resource {} cannot be updated. reason={}", lockedResourceId,
- responseFormat.getFormattedMessage());
- componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
- ResourceAuditData.newBuilder()
- .state(oldResource.getLifecycleState().name())
- .version(oldResource.getVersion())
- .build());
- result = Either.right(prepareResourceForUpdate.right().value());
- return result;
- }
- oldResource = prepareResourceForUpdate.left().value();
-
+ lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import");
+ oldResource = prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false);
mergeOldResourceMetadataWithNew(oldResource, newResource);
- Either<Boolean, ResponseFormat> validateFieldsResponse = validateResourceFieldsBeforeUpdate(oldResource,
- newResource, inTransaction, isNested);
- if (validateFieldsResponse.isRight()) {
- result = Either.right(validateFieldsResponse.right().value());
- return result;
- }
-
- validateFieldsResponse = validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), newResource,
- AuditingActionEnum.IMPORT_RESOURCE, inTransaction);
- if (validateFieldsResponse.isRight()) {
- return Either.right(validateFieldsResponse.right().value());
- }
-
+ validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested);
+ validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), newResource, AuditingActionEnum.IMPORT_RESOURCE, inTransaction);
// contact info normalization
newResource.setContactId(newResource.getContactId().toLowerCase());
// non-updatable fields
@@ -4468,9 +3297,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (newResource.getDerivedFromGenericVersion() == null || newResource.getDerivedFromGenericVersion().isEmpty()) {
newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion());
}
- // TODO rhalili: handle artifacts here (delete from old resource and
// add for new)
- // TODO rbetzer: remove after migration - in case of resources
// created without tosca artifacts - add the placeholders
if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts().isEmpty()) {
setToscaArtifactsPlaceHolders(newResource, user);
@@ -4483,31 +3310,29 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
componentsUtils.convertFromStorageResponse(overrideResource.right().value()), newResource);
componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE);
- result = Either.right(responseFormat);
- return result;
+ throwComponentException(responseFormat);
}
log.debug("Resource updated successfully!!!");
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
- ResourceAuditData.newBuilder()
- .state(oldResource.getLifecycleState().name()).version(oldResource.getVersion()).build());
-
+ ResourceVersionInfo.newBuilder()
+ .state(oldResource.getLifecycleState()
+ .name())
+ .version(oldResource.getVersion())
+ .build());
- ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(overrideResource.left().value(),
+ resourcePair = new ImmutablePair<>(overrideResource.left().value(),
ActionStatus.OK);
- result = Either.left(resourcePair);
- return result;
+ return resourcePair;
} finally {
- if (result == null || result.isRight()) {
+ if (resourcePair == null) {
BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
- log.debug("operation failed. do rollback");
titanDao.rollback();
- } else if (inTransaction == false) {
- log.debug("operation success. do commit");
+ } else if (!inTransaction) {
titanDao.commit();
}
- if (needLock == true) {
+ if (needLock) {
log.debug("unlock resource {}", lockedResourceId);
graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
}
@@ -4552,45 +3377,37 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
}
- private Either<Resource, ResponseFormat> prepareResourceForUpdate(Resource latestResource, User user,
- boolean inTransaction, boolean needLock) {
+ private Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user,
+ boolean inTransaction, boolean needLock) {
- Either<Resource, ResponseFormat> result = Either.left(latestResource);
- // check if user can edit resource
- if (!ComponentValidationUtils.canWorkOnResource(latestResource, user.getUserId())) {
+ if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) {
// checkout
- Either<Resource, ResponseFormat> changeState = lifecycleBusinessLogic.changeState(
- latestResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
- new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock);
- result = changeState;
+ return lifecycleBusinessLogic.changeState(
+ oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
+ new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock)
+ .left()
+ .on(response -> failOnChangeState(response, user, oldResource, newResource));
}
-
- return result;
+ return oldResource;
}
- public Either<Resource, ResponseFormat> validateResourceBeforeCreate(Resource resource, User user,
- AuditingActionEnum actionEnum, boolean inTransaction, CsarInfo csarInfo) {
-
- Either<Boolean, ResponseFormat> eitherValidation = validateResourceFieldsBeforeCreate(user, resource,
- actionEnum, inTransaction);
- if (eitherValidation.isRight()) {
- return Either.right(eitherValidation.right().value());
- }
+ 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());
+ throw new ComponentException(response);
+ }
- eitherValidation = validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum,
- inTransaction);
- if (eitherValidation.isRight()) {
- return Either.right(eitherValidation.right().value());
- }
- eitherValidation = validateLifecycleTypesCreate(user, resource, actionEnum);
- if (eitherValidation.isRight()) {
- return Either.right(eitherValidation.right().value());
- }
- eitherValidation = validateResourceType(user, resource, actionEnum);
- if (eitherValidation.isRight()) {
- return Either.right(eitherValidation.right().value());
- }
+ public Resource validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction, CsarInfo csarInfo) {
+ validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
+ validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
+ validateLifecycleTypesCreate(user, resource, actionEnum);
+ validateResourceType(user, resource, actionEnum);
resource.setCreatorUserId(user.getUserId());
resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
resource.setContactId(resource.getContactId().toLowerCase());
@@ -4611,7 +3428,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
resource.setInvariantUUID(invariantUUID);
- return Either.left(resource);
+ return resource;
}
private Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource,
@@ -4702,20 +3519,21 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (eitherCapTypeFound.isRight()) {
if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
- "Create Resource - validateCapabilityTypesCreate", "Capability Type", type);
+ CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", type);
log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type,
resource.getName());
BeEcompErrorManager.getInstance()
- .logBeDaoSystemError("Create Resource - validateCapabilityTypesCreate");
+ .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
}
log.debug("Trying to get capability type {} failed with error: {}", type,
eitherCapTypeFound.right().value().name());
ResponseFormat errorResponse = null;
- if (type != null)
+ if (type != null) {
errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
- else
+ } else {
errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE,
validationObjects);
+ }
eitherResult = Either.right(errorResponse);
componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
}
@@ -4731,11 +3549,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (eitherCapTypeFound.isRight()) {
if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
- "Create Resource - validateCapabilityTypesCreate", "Capability Type", typeEntry.getKey());
+ 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 - validateCapabilityTypesCreate");
+ .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
}
log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(),
eitherCapTypeFound.right().value().name());
@@ -4749,7 +3567,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
for (CapabilityDefinition capDef : typeEntry.getValue()) {
List<ComponentInstanceProperty> properties = capDef.getProperties();
if (properties == null || properties.isEmpty()) {
- properties = new ArrayList<ComponentInstanceProperty>();
+ properties = new ArrayList<>();
for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
properties.add(newProp);
@@ -4775,50 +3593,53 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return eitherResult;
}
- public Either<Resource, ResponseFormat> createResourceByDao(Resource resource, User user,
- AuditingActionEnum actionEnum, boolean isNormative, boolean inTransaction) {
+ public Resource createResourceByDao(Resource resource, User user,
+ AuditingActionEnum actionEnum, boolean isNormative, boolean inTransaction) {
// create resource
// lock new resource name in order to avoid creation resource with same
// name
- if (inTransaction == false) {
+ Resource createdResource = null;
+ if (!inTransaction) {
Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
- "Create Resource");
+ CREATE_RESOURCE);
if (lockResult.isRight()) {
ResponseFormat responseFormat = lockResult.right().value();
componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
- return Either.right(responseFormat);
+ throw new ComponentException(responseFormat);
}
log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
}
try {
if (resource.deriveFromGeneric()) {
- Either<Resource, ResponseFormat> genericResourceEither = handleResourceGenericType(resource);
- if (genericResourceEither.isRight())
- return genericResourceEither;
+ handleResourceGenericType(resource);
}
-
- Either<Resource, ResponseFormat> respStatus = createResourceTransaction(resource, user, isNormative,
- inTransaction);
- if (respStatus.isLeft()) {
- componentsUtils.auditResource(componentsUtils.getResponseFormat(ActionStatus.CREATED), user,
- respStatus.left().value(), actionEnum);
- ASDCKpiApi.countCreatedResourcesKPI();
- } else
- componentsUtils.auditResource(respStatus.right().value(), user, resource, actionEnum);
- return respStatus;
-
- } finally {
- if (inTransaction == false) {
+ createdResource = createResourceTransaction(resource, user, isNormative
+ );
+ componentsUtils.auditResource(componentsUtils.getResponseFormat(ActionStatus.CREATED), user,
+ createdResource, actionEnum);
+ ASDCKpiApi.countCreatedResourcesKPI();
+ } catch(ComponentException e) {
+ ResponseFormat responseFormat = 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()));
+ componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+ throw e;
+ }
+ finally {
+ if (!inTransaction) {
graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
NodeTypeEnum.Resource);
}
}
+ return createdResource;
}
- private Either<Resource, ResponseFormat> createResourceTransaction(Resource resource, User user,
- boolean isNormative, boolean inTransaction) {
+ private Resource createResourceTransaction(Resource resource, User user,
+ boolean isNormative) {
// validate resource name uniqueness
log.debug("validate resource name");
Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(
@@ -4828,41 +3649,37 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
eitherValidation.right().value());
ResponseFormat errorResponse = componentsUtils
.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
- return Either.right(errorResponse);
+ throw new ComponentException(errorResponse);
}
if (eitherValidation.left().value()) {
log.debug("resource with name: {}, already exists", resource.getName());
ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
- return Either.right(errorResponse);
+ throw new ComponentException(errorResponse);
}
log.debug("send resource {} to dao for create", resource.getName());
createArtifactsPlaceHolderData(resource, user);
-
- //
-
// enrich object
if (!isNormative) {
log.debug("enrich resource with creator, version and state");
resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
resource.setVersion(INITIAL_VERSION);
resource.setHighestVersion(true);
- if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC)
+ if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC) {
resource.setAbstract(false);
+ }
}
+ return toscaOperationFacade.createToscaComponent(resource)
+ .left()
+ .on(r->throwComponentExceptionByResource(r, resource));
+ }
- Either<Resource, StorageOperationStatus> createToscaElement = toscaOperationFacade
- .createToscaComponent(resource);
- if (createToscaElement.isLeft()) {
- return Either.left(createToscaElement.left().value());
- }
-
+ private Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) {
ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
- componentsUtils.convertFromStorageResponse(createToscaElement.right().value()), resource);
-
- return Either.right(responseFormat);
+ componentsUtils.convertFromStorageResponse(status), resource);
+ throw new ComponentException(responseFormat);
}
private void createArtifactsPlaceHolderData(Resource resource, User user) {
@@ -4882,47 +3699,49 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Resource resource = (Resource) component;
Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
if (artifactMap == null) {
- artifactMap = new HashMap<String, ArtifactDefinition>();
+ artifactMap = new HashMap<>();
}
Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
.getConfiguration().getDeploymentResourceArtifacts();
if (deploymentResourceArtifacts != null) {
- Iterator<Entry<String, Object>> iterator = deploymentResourceArtifacts.entrySet().iterator();
- while (iterator.hasNext()) {
- Entry<String, Object> currEntry = iterator.next();
- boolean shouldCreateArtifact = true;
- Map<String, Object> artifactDetails = (Map<String, Object>) currEntry.getValue();
- Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
- if (object != null) {
- List<String> artifactTypes = (List<String>) object;
- if (!artifactTypes.contains(resource.getResourceType().name())) {
- shouldCreateArtifact = false;
- continue;
- }
- } else {
- log.info("resource types for artifact placeholder {} were not defined. default is all resources",
- currEntry.getKey());
- }
- if (shouldCreateArtifact) {
- if (artifactsBusinessLogic != null) {
- ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
- resource.getUniqueId(), currEntry.getKey(), (Map<String, Object>) currEntry.getValue(),
- user, ArtifactGroupTypeEnum.DEPLOYMENT);
- if (artifactDefinition != null
- && !artifactMap.containsKey(artifactDefinition.getArtifactLabel()))
- artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
- }
+ Map<String, ArtifactDefinition> finalArtifactMap = artifactMap;
+ deploymentResourceArtifacts.forEach((k, v)->processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k,v));
+ }
+ resource.setDeploymentArtifacts(artifactMap);
+ }
+
+ private void processDeploymentResourceArtifacts(User user, Resource resource, Map<String, ArtifactDefinition> artifactMap, String k, Object v) {
+ boolean shouldCreateArtifact = true;
+ Map<String, Object> artifactDetails = (Map<String, Object>) v;
+ Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
+ if (object != null) {
+ List<String> artifactTypes = (List<String>) object;
+ if (!artifactTypes.contains(resource.getResourceType().name())) {
+ shouldCreateArtifact = false;
+ return;
+ }
+ } else {
+ log.info("resource types for artifact placeholder {} were not defined. default is all resources",
+ k);
+ }
+ if (shouldCreateArtifact) {
+ if (artifactsBusinessLogic != null) {
+ ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
+ resource.getUniqueId(), k, (Map<String, Object>) v,
+ user, ArtifactGroupTypeEnum.DEPLOYMENT);
+ if (artifactDefinition != null
+ && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
+ artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
}
}
}
- resource.setDeploymentArtifacts(artifactMap);
}
@SuppressWarnings("unchecked")
private void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
if (artifactMap == null) {
- artifactMap = new HashMap<String, ArtifactDefinition>();
+ artifactMap = new HashMap<>();
}
String resourceUniqueId = resource.getUniqueId();
List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration()
@@ -4935,25 +3754,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
boolean isCreateArtifact = true;
if (exludeResourceCategory != null) {
String category = categories.get(0).getName();
- for (String exlude : exludeResourceCategory) {
- if (exlude.equalsIgnoreCase(category)) {
- isCreateArtifact = false;
- break;
- }
- }
-
+ isCreateArtifact = exludeResourceCategory.stream().noneMatch(e->e.equalsIgnoreCase(category));
}
if (isCreateArtifact && exludeResourceType != null) {
String resourceType = resource.getResourceType().name();
- for (String type : exludeResourceType) {
- if (type.equalsIgnoreCase(resourceType)) {
- isCreateArtifact = false;
- break;
- }
- }
-
+ isCreateArtifact = exludeResourceType.stream().noneMatch(e->e.equalsIgnoreCase(resourceType));
}
-
if (informationalResourceArtifacts != null && isCreateArtifact) {
Set<String> keys = informationalResourceArtifacts.keySet();
for (String informationalResourceArtifactName : keys) {
@@ -4978,10 +3784,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
*/
public ResponseFormat deleteResource(String resourceId, User user) {
ResponseFormat responseFormat;
- Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Delete Resource", false);
- if (eitherCreator.isRight()) {
- return eitherCreator.right().value();
- }
+ validateUserExists(user, DELETE_RESOURCE, false);
Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId);
if (resourceStatus.isRight()) {
@@ -4995,7 +3798,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
StorageOperationStatus result = StorageOperationStatus.OK;
Either<Boolean, ResponseFormat> lockResult = lockComponent(resourceId, resource, "Mark resource to delete");
if (lockResult.isRight()) {
- result = StorageOperationStatus.GENERAL_ERROR;
return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
}
@@ -5012,10 +3814,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
} finally {
if (result == null || !result.equals(StorageOperationStatus.OK)) {
- log.warn("operation failed. do rollback");
titanDao.rollback();
} else {
- log.debug("operation success. do commit");
titanDao.commit();
}
graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
@@ -5025,11 +3825,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
- Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Delete Resource", false);
- if (eitherCreator.isRight()) {
- return eitherCreator.right().value();
- }
-
+ validateUserExists(user, DELETE_RESOURCE, false);
Resource resource = null;
StorageOperationStatus result = StorageOperationStatus.OK;
try {
@@ -5046,18 +3842,16 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
} finally {
if (result == null || !result.equals(StorageOperationStatus.OK)) {
- log.warn("operation failed. do rollback");
titanDao.rollback();
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resourceName);
} else {
- log.debug("operation success. do commit");
titanDao.commit();
}
}
if (resource != null) {
Either<Boolean, ResponseFormat> lockResult = lockComponent(resource.getUniqueId(), resource,
- "Delete Resource");
+ DELETE_RESOURCE);
if (lockResult.isRight()) {
result = StorageOperationStatus.GENERAL_ERROR;
return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
@@ -5072,10 +3866,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
} finally {
if (result == null || !result.equals(StorageOperationStatus.OK)) {
- log.warn("operation failed. do rollback");
titanDao.rollback();
} else {
- log.debug("operation success. do commit");
titanDao.commit();
}
graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource);
@@ -5087,10 +3879,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
public Either<Resource, ResponseFormat> getResource(String resourceId, User user) {
if (user != null) {
- Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Create Resource", false);
- if (eitherCreator.isRight()) {
- return Either.right(eitherCreator.right().value());
- }
+ validateUserExists(user, CREATE_RESOURCE, false);
}
Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId);
@@ -5110,10 +3899,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion,
String userId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Resource By Name And Version", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "get Resource By Name And Version", false);
Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade
.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion);
@@ -5132,15 +3918,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
* @param inTransaction TODO
* @param resourceIdToUpdate - the resource identifier
* @param newResource
- * @return Either<Resource, responseFormat>
+ * @return Either<Resource , responseFormat>
*/
- public Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource,
- Resource currentResource, User user, boolean inTransaction) {
+ public Resource updateResourceMetadata(String resourceIdToUpdate, Resource newResource,
+ Resource currentResource, User user, boolean inTransaction) {
- Either<User, ResponseFormat> resp = validateUserExists(user.getUserId(), "update Resource Metadata", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(user.getUserId(), "update Resource Metadata", false);
log.debug("Get resource with id {}", resourceIdToUpdate);
boolean needToUnlock = false;
@@ -5151,7 +3934,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade
.getToscaElement(resourceIdToUpdate);
if (storageStatus.isRight()) {
- return Either.right(componentsUtils.getResponseFormatByResource(
+ throw new ComponentException(componentsUtils.getResponseFormatByResource(
componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
}
@@ -5160,7 +3943,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
// verify that resource is checked-out and the user is the last
// updater
if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
}
// lock resource
@@ -5172,7 +3955,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult);
ResponseFormat responseFormat = componentsUtils
.getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
- return Either.right(responseFormat);
+ throw new ComponentException(responseFormat);
}
needToUnlock = true;
@@ -5185,118 +3968,42 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
// This code is not called from import resources, because of root
// VF "derivedFrom" should be null (or ignored)
if (ModelConverter.isAtomicComponent(currentResource)) {
- Either<Boolean, ResponseFormat> derivedFromNotEmptyEither = validateDerivedFromNotEmpty(null,
- newResource, null);
- if (derivedFromNotEmptyEither.isRight()) {
- log.debug("for updated resource {}, derived from field is empty", newResource.getName());
- return Either.right(derivedFromNotEmptyEither.right().value());
- }
-
- derivedFromNotEmptyEither = validateDerivedFromNotEmpty(null, currentResource, null);
- if (derivedFromNotEmptyEither.isRight()) {
- log.debug("for current resource {}, derived from field is empty", currentResource.getName());
- return Either.right(derivedFromNotEmptyEither.right().value());
- }
+ validateDerivedFromNotEmpty(null, newResource, null);
+ validateDerivedFromNotEmpty(null, currentResource, null);
} else {
newResource.setDerivedFrom(null);
}
- Either<Boolean, ResponseFormat> validateAndUpdateInterfacesEither = validateAndUpdateInterfaces(resourceIdToUpdate, newResource);
- if (validateAndUpdateInterfacesEither.isRight()) {
- log.error("failed to validate and update Interfaces !!!");
- rollbackNeeded = true;
- return Either.right(validateAndUpdateInterfacesEither.right().value());
- }
-
Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource,
user, currentResource, false, true);
if (dataModelResponse.isRight()) {
log.debug("failed to update resource metadata!!!");
rollbackNeeded = true;
- return Either.right(dataModelResponse.right().value());
+ throw new ComponentException(dataModelResponse.right().value());
}
log.debug("Resource metadata updated successfully!!!");
rollbackNeeded = false;
- return Either.left(dataModelResponse.left().value());
+ return dataModelResponse.left().value();
- } finally {
+ } catch (ComponentException|StorageException e){
+ rollback(inTransaction, newResource, null, null);
+ throw e;
+ }
+ finally {
if (!inTransaction) {
- if (rollbackNeeded) {
- titanDao.rollback();
- } else {
- titanDao.commit();
- }
+ titanDao.commit();
}
-
if (needToUnlock) {
graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
}
}
}
- private Either<List<GroupDefinition>, Boolean> updateComponentGroupName(String replacePattern, String with,
- List<GroupDefinition> oldGroup) {
- if (oldGroup == null || with == null || replacePattern == null || with.isEmpty() || replacePattern.isEmpty()) {
- if (log.isInfoEnabled())
- log.info("cannot update group name , invalid args -> replacePattern:{} , with:{} , oldGroup:{}",
- replacePattern, with, oldGroup == null ? null : " < size : " + oldGroup.size() + " >");
- return Either.right(false);
- }
- List<GroupDefinition> list = oldGroup.stream().map(group -> new GroupDefinition(group))
- .collect(Collectors.toList());
- for (GroupDefinition group : list) {
- if (group != null && group.isSamePrefix(replacePattern)) {
- String prefix = group.getName().substring(0, replacePattern.length());
- String newGroupName = group.getName().replaceFirst(prefix, with);
- group.setName(newGroupName);
- }
- }
- return Either.left(list);
- }
-
- private boolean isComponentNameChanged(Resource newResource, Resource oldResource) {
- if (newResource != null && oldResource != null) { // TODO - must protect
- // all chain against
- // null , use
- // optional
- String futureName = newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
- String oldName = oldResource.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
- return !oldName.equals(futureName);
- }
- return false;
- }
-
private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource,
User user, Resource currentResource, boolean shouldLock, boolean inTransaction) {
- // region -> Update groups name for newResource
- if (isComponentNameChanged(currentResource, newResource)) {
- String replacePattern = Optional.ofNullable( // get currentResource
- // name from
- // metadata
- Optional.ofNullable(
- Optional.ofNullable(currentResource).orElse(null).getComponentMetadataDefinition())
- .orElse(null).getMetadataDataDefinition())
- .orElse(null).getName();
- String with = Optional.ofNullable( // get newResource name from
- // metadata
- Optional.ofNullable(Optional.ofNullable(newResource).orElse(null).getComponentMetadataDefinition())
- .orElse(null).getMetadataDataDefinition())
- .orElse(null).getName();
- if (with != null && replacePattern != null) {
- Either<List<GroupDefinition>, Boolean> result = updateComponentGroupName(replacePattern, with,
- currentResource.getGroups());
- if (result.isLeft())
- newResource.setGroups((List<GroupDefinition>) result.left().value());
- }
- }
- // endregion
-
- Either<Boolean, ResponseFormat> validateResourceFields = validateResourceFieldsBeforeUpdate(currentResource,
- newResource, inTransaction, false);
- if (validateResourceFields.isRight()) {
- return Either.right(validateResourceFields.right().value());
- }
+ updateVfModuleGroupsNames(currentResource, newResource);
+ validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction, false);
// Setting last updater and uniqueId
newResource.setContactId(newResource.getContactId().toLowerCase());
newResource.setLastUpdaterUserId(user.getUserId());
@@ -5306,7 +4013,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
newResource.setCreationDate(currentResource.getCreationDate());
Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource,
- newResource, user.getUserId(), shouldLock, inTransaction);
+ newResource, user.getUserId(), inTransaction);
if (processUpdateOfDerivedFrom.isRight()) {
log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate);
@@ -5314,13 +4021,13 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
log.debug("send resource {} to dao for update", newResource.getUniqueId());
- if (newResource != null && newResource.getGroups() != null) {
+ if (isNotEmpty(newResource.getGroups())) {
for (GroupDefinition group : newResource.getGroups()) {
- if (newResource.getComponentMetadataDefinition() != null
- && newResource.getComponentMetadataDefinition().getMetadataDataDefinition() != null)
+ if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) {
groupBusinessLogic.validateAndUpdateGroupMetadata(
newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId(),
- user, ComponentTypeEnum.RESOURCE_INSTANCE, group, true, false);
+ user, newResource.getComponentType(), group, true, false);
+ }
}
}
Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade
@@ -5337,92 +4044,77 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(dataModelResponse.left().value());
}
+
+ 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());
+ newResource.setGroups(updatedGroups);
+ }
+ }
+
+ private GroupDefinition getUpdatedGroup(GroupDefinition currGroup, String replacePattern, String with) {
+ GroupDefinition updatedGroup = new GroupDefinition(currGroup);
+ if(updatedGroup.isSamePrefix(replacePattern) && updatedGroup.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)){
+ String prefix = updatedGroup.getName().substring(0, replacePattern.length());
+ String newGroupName = updatedGroup.getName().replaceFirst(prefix, with);
+ updatedGroup.setName(newGroupName);
+ }
+ return updatedGroup;
+ }
/**
* validateResourceFieldsBeforeCreate
*
- * @param user - modifier data (userId)
- * @return Either<Boolean, ErrorResponse>
+ * @param user - modifier data (userId)
+ * @return Either<Boolean , ErrorResponse>
*/
private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, Resource resource,
AuditingActionEnum actionEnum, boolean inTransaction) {
- Either<Boolean, ResponseFormat> componentsFieldsValidation = validateComponentFieldsBeforeCreate(user, resource,
- actionEnum);
- if (componentsFieldsValidation.isRight()) {
- return componentsFieldsValidation;
- }
-
-
+ validateComponentFieldsBeforeCreate(user, resource, actionEnum);
// validate category
log.debug("validate category");
- Either<Boolean, ResponseFormat> eitherValidation = validateCategory(user, resource, actionEnum, inTransaction);
- if (eitherValidation.isRight()) {
- return eitherValidation;
- }
-
+ validateCategory(user, resource, actionEnum, inTransaction);
// validate vendor name & release & model number
log.debug("validate vendor name");
- eitherValidation = validateVendorName(user, resource, actionEnum);
- if (eitherValidation.isRight()) {
- return eitherValidation;
- }
-
+ validateVendorName(user, resource, actionEnum);
log.debug("validate vendor release");
- eitherValidation = validateVendorReleaseName(user, resource, actionEnum);
- if (eitherValidation.isRight()) {
- return eitherValidation;
- }
-
+ validateVendorReleaseName(user, resource, actionEnum);
log.debug("validate resource vendor model number");
- eitherValidation = validateResourceVendorModelNumber(user, resource, actionEnum);
- if (eitherValidation.isRight()) {
- return eitherValidation;
- }
-
-
+ validateResourceVendorModelNumber(user, resource, actionEnum);
// validate cost
log.debug("validate cost");
- eitherValidation = validateCost(user, resource, actionEnum);
- if (eitherValidation.isRight()) {
- return eitherValidation;
- }
-
+ validateCost(resource);
// validate licenseType
log.debug("validate licenseType");
- eitherValidation = validateLicenseType(user, resource, actionEnum);
- if (eitherValidation.isRight()) {
- return eitherValidation;
- }
-
+ validateLicenseType(user, resource, actionEnum);
// validate template (derived from)
log.debug("validate derived from");
if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
resource.setDerivedFrom(null);
}
- eitherValidation = validateDerivedFromExist(user, resource, actionEnum);
- if (eitherValidation.isRight()) {
- return Either.right(eitherValidation.right().value());
- }
-
+ validateDerivedFromExist(user, resource, actionEnum);
// warn about non-updatable fields
checkComponentFieldsForOverrideAttempt(resource);
String currentCreatorFullName = resource.getCreatorFullName();
if (currentCreatorFullName != null) {
- log.warn("Resource Creator fullname is automatically set and cannot be updated");
+ log.debug("Resource Creator fullname is automatically set and cannot be updated");
}
String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
if (currentLastUpdaterFullName != null) {
- log.warn("Resource LastUpdater fullname is automatically set and cannot be updated");
+ log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
}
Long currentLastUpdateDate = resource.getLastUpdateDate();
if (currentLastUpdateDate != null) {
- log.warn("Resource last update date is automatically set and cannot be updated");
+ log.debug("Resource last update date is automatically set and cannot be updated");
}
Boolean currentAbstract = resource.isAbstract();
if (currentAbstract != null) {
- log.warn("Resource abstract is automatically set and cannot be updated");
+ log.debug("Resource abstract is automatically set and cannot be updated");
}
return Either.left(true);
@@ -5433,159 +4125,96 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
*
* @param currentResource - Resource object to validate
* @param isNested
- * @return Either<Boolean, ErrorResponse>
*/
- private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeUpdate(Resource currentResource,
- Resource updateInfoResource, boolean inTransaction, boolean isNested) {
-
- boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
-
- // validate resource name
- log.debug("validate resource name before update");
- Either<Boolean, ResponseFormat> eitherValidation = validateResourceName(currentResource, updateInfoResource,
- hasBeenCertified, isNested);
- if (eitherValidation.isRight()) {
- return eitherValidation;
- }
-
- // validate description
- log.debug("validate description before update");
- eitherValidation = validateDescriptionAndCleanup(null, updateInfoResource, null);
- if (eitherValidation.isRight()) {
- return eitherValidation;
- }
-
- log.debug("validate icon before update");
- eitherValidation = validateIcon(currentResource, updateInfoResource, hasBeenCertified);
- if (eitherValidation.isRight()) {
- return eitherValidation;
- }
-
- log.debug("validate tags before update");
- eitherValidation = validateTagsListAndRemoveDuplicates(null, updateInfoResource, null);
- if (eitherValidation.isRight()) {
- return eitherValidation;
- }
-
- log.debug("validate vendor name before update");
- eitherValidation = validateVendorName(currentResource, updateInfoResource, hasBeenCertified);
- if (eitherValidation.isRight()) {
- return eitherValidation;
- }
-
- log.debug("validate resource vendor model number before update");
- eitherValidation = validateResourceVendorModelNumber(currentResource, updateInfoResource);
- if (eitherValidation.isRight()) {
- return eitherValidation;
- }
-
- log.debug("validate vendor release before update");
- eitherValidation = validateVendorReleaseName(null, updateInfoResource, null);
- if (eitherValidation.isRight()) {
- return eitherValidation;
- }
-
- log.debug("validate contact info before update");
- eitherValidation = validateContactId(null, updateInfoResource, null);
- if (eitherValidation.isRight()) {
- return eitherValidation;
- }
-
- log.debug("validate derived before update");
- eitherValidation = validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified);
- if (eitherValidation.isRight()) {
- return eitherValidation;
- }
-
- log.debug("validate category before update");
- eitherValidation = validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction);
- if (eitherValidation.isRight()) {
- return eitherValidation;
- }
+ private void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource,
+ boolean inTransaction, boolean isNested) {
+ validateFields(currentResource, updateInfoResource, inTransaction, isNested);
+ warnNonEditableFields(currentResource, updateInfoResource);
+ }
- // warn about non-updatable fields
+ private void warnNonEditableFields(Resource currentResource, Resource updateInfoResource) {
String currentResourceVersion = currentResource.getVersion();
String updatedResourceVersion = updateInfoResource.getVersion();
if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) {
- log.warn("Resource version is automatically set and cannot be updated");
+ log.debug("Resource version is automatically set and cannot be updated");
}
String currentCreatorUserId = currentResource.getCreatorUserId();
String updatedCreatorUserId = updateInfoResource.getCreatorUserId();
if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) {
- log.warn("Resource Creator UserId is automatically set and cannot be updated");
+ log.debug("Resource Creator UserId is automatically set and cannot be updated");
}
String currentCreatorFullName = currentResource.getCreatorFullName();
String updatedCreatorFullName = updateInfoResource.getCreatorFullName();
if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) {
- log.warn("Resource Creator fullname is automatically set and cannot be updated");
+ log.debug("Resource Creator fullname is automatically set and cannot be updated");
}
String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId();
String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId();
if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) {
- log.warn("Resource LastUpdater userId is automatically set and cannot be updated");
+ log.debug("Resource LastUpdater userId is automatically set and cannot be updated");
}
String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName();
String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName();
if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) {
- log.warn("Resource LastUpdater fullname is automatically set and cannot be updated");
+ log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
}
Long currentCreationDate = currentResource.getCreationDate();
Long updatedCreationDate = updateInfoResource.getCreationDate();
if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) {
- log.warn("Resource Creation date is automatically set and cannot be updated");
+ log.debug("Resource Creation date is automatically set and cannot be updated");
}
Long currentLastUpdateDate = currentResource.getLastUpdateDate();
Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate();
if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) {
- log.warn("Resource last update date is automatically set and cannot be updated");
+ log.debug("Resource last update date is automatically set and cannot be updated");
}
LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState();
LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState();
if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) {
- log.warn("Resource lifecycle state date is automatically set and cannot be updated");
+ log.debug("Resource lifecycle state date is automatically set and cannot be updated");
}
Boolean currentAbstract = currentResource.isAbstract();
Boolean updatedAbstract = updateInfoResource.isAbstract();
if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) {
- log.warn("Resource abstract is automatically set and cannot be updated");
+ log.debug("Resource abstract is automatically set and cannot be updated");
}
Boolean currentHighestVersion = currentResource.isHighestVersion();
Boolean updatedHighestVersion = updateInfoResource.isHighestVersion();
if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) {
- log.warn("Resource highest version is automatically set and cannot be updated");
+ log.debug("Resource highest version is automatically set and cannot be updated");
}
String currentUuid = currentResource.getUUID();
String updatedUuid = updateInfoResource.getUUID();
if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) {
- log.warn("Resource UUID is automatically set and cannot be updated");
+ log.debug("Resource UUID is automatically set and cannot be updated");
}
ResourceTypeEnum currentResourceType = currentResource.getResourceType();
ResourceTypeEnum updatedResourceType = updateInfoResource.getResourceType();
if ((updatedResourceType != null) && (!updatedResourceType.equals(currentResourceType))) {
- log.warn("Resource Type cannot be updated");
+ log.debug("Resource Type cannot be updated");
}
updateInfoResource.setResourceType(currentResource.getResourceType());
@@ -5594,44 +4223,59 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
String updatedInvariantUuid = updateInfoResource.getInvariantUUID();
if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
- log.warn("Resource invariant UUID is automatically set and cannot be updated");
+ log.debug("Resource invariant UUID is automatically set and cannot be updated");
updateInfoResource.setInvariantUUID(currentInvariantUuid);
}
- return Either.left(true);
+ }
+
+ private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) {
+ boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
+ log.debug("validate resource name before update");
+ validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested);
+ log.debug("validate description before update");
+ validateDescriptionAndCleanup(null, updateInfoResource, null);
+ log.debug("validate icon before update");
+ validateIcon(currentResource, updateInfoResource, hasBeenCertified);
+ log.debug("validate tags before update");
+ validateTagsListAndRemoveDuplicates(null, updateInfoResource, null);
+ log.debug("validate vendor name before update");
+ validateVendorName(null, updateInfoResource, null);
+ log.debug("validate resource vendor model number before update");
+ validateResourceVendorModelNumber(currentResource, updateInfoResource);
+ log.debug("validate vendor release before update");
+ validateVendorReleaseName(null, updateInfoResource, null);
+ log.debug("validate contact info before update");
+ validateContactId(null, updateInfoResource, null);
+ log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
+ validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified);
+ log.debug("validate category before update");
+ validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction);
}
private boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) {
String resourceNameUpdated = updateInfoResource.getName();
String resourceNameCurrent = currentResource.getName();
- if (resourceNameCurrent.equals(resourceNameUpdated))
+ if (resourceNameCurrent.equals(resourceNameUpdated)) {
return true;
+ }
// In case of CVFC type we should support the case of old VF with CVFC
// instances that were created without the "Cvfc" suffix
return currentResource.getResourceType().equals(ResourceTypeEnum.CVFC) &&
- resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent));
+ resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent));
}
private String addCvfcSuffixToResourceName(String resourceName) {
return resourceName + "Cvfc";
}
- private Either<Boolean, ResponseFormat> validateResourceName(Resource currentResource, Resource updateInfoResource,
- boolean hasBeenCertified, boolean isNested) {
+ private void validateResourceName(Resource currentResource, Resource updateInfoResource,
+ boolean hasBeenCertified, boolean isNested) {
String resourceNameUpdated = updateInfoResource.getName();
if (!isResourceNameEquals(currentResource, updateInfoResource)) {
if (isNested || !hasBeenCertified) {
- Either<Boolean, ResponseFormat> validateResourceNameResponse = validateComponentName(null,
- updateInfoResource, null);
- if (validateResourceNameResponse.isRight()) {
- ResponseFormat errorResponse = validateResourceNameResponse.right().value();
- return Either.right(errorResponse);
- }
- validateResourceNameResponse = validateResourceNameExists(updateInfoResource);
- if (validateResourceNameResponse.isRight()) {
- ResponseFormat errorResponse = validateResourceNameResponse.right().value();
- return Either.right(errorResponse);
- }
+ validateComponentName(null, updateInfoResource, null);
+ validateResourceNameUniqueness(updateInfoResource);
currentResource.setName(resourceNameUpdated);
currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
@@ -5639,82 +4283,35 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
} else {
log.info("Resource name: {}, cannot be updated once the resource has been certified once.",
resourceNameUpdated);
- ResponseFormat errorResponse = componentsUtils
- .getResponseFormat(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
- return Either.right(errorResponse);
+ throw new ComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
}
}
- return Either.left(true);
}
- private Either<Boolean, ResponseFormat> validateIcon(Resource currentResource, Resource updateInfoResource,
- boolean hasBeenCertified) {
+ private void validateIcon(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
String iconUpdated = updateInfoResource.getIcon();
String iconCurrent = currentResource.getIcon();
if (!iconCurrent.equals(iconUpdated)) {
if (!hasBeenCertified) {
- Either<Boolean, ResponseFormat> validateIcon = validateIcon(null, updateInfoResource, null);
- if (validateIcon.isRight()) {
- ResponseFormat errorResponse = validateIcon.right().value();
- return Either.right(errorResponse);
- }
+ validateIcon(null, updateInfoResource, null);
} else {
log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated);
- ResponseFormat errorResponse = componentsUtils
- .getResponseFormat(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
- return Either.right(errorResponse);
+ throw new ComponentException(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
}
}
- return Either.left(true);
}
- private Either<Boolean, ResponseFormat> validateVendorName(Resource currentResource, Resource updateInfoResource,
- boolean hasBeenCertified) {
- String vendorNameUpdated = updateInfoResource.getVendorName();
- String vendorNameCurrent = currentResource.getVendorName();
- if (!vendorNameCurrent.equals(vendorNameUpdated)) {
- if(updateInfoResource.getResourceType().equals(ResourceTypeEnum.VF) && hasBeenCertified ){
- log.info("Vendor name {} cannot be updated once the resource has been certified once.",
- vendorNameUpdated);
- ResponseFormat errorResponse = componentsUtils
- .getResponseFormat(ActionStatus.RESOURCE_VENDOR_NAME_CANNOT_BE_CHANGED);
- return Either.right(errorResponse);
-
- }
- else {
- Either<Boolean, ResponseFormat> validateVendorName = validateVendorName(null, updateInfoResource, null);
- if (validateVendorName.isRight()) {
- ResponseFormat errorResponse = validateVendorName.right().value();
- return Either.right(errorResponse);
- }
- }
- }
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(Resource currentResource,
- Resource updateInfoResource) {
+ private void validateResourceVendorModelNumber(Resource currentResource, Resource updateInfoResource) {
String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber();
String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber();
if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) {
- Either<Boolean, ResponseFormat> validateResourceVendorModelNumber = validateResourceVendorModelNumber(null,
- updateInfoResource, null);
- if (validateResourceVendorModelNumber.isRight()) {
- ResponseFormat errorResponse = validateResourceVendorModelNumber.right().value();
- return Either.right(errorResponse);
- }
+ validateResourceVendorModelNumber(null, updateInfoResource, null);
}
- return Either.left(true);
}
private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource,
boolean hasBeenCertified, boolean inTransaction) {
- Either<Boolean, ResponseFormat> validateCategoryName = validateCategory(null, updateInfoResource, null,
- inTransaction);
- if (validateCategoryName.isRight()) {
- ResponseFormat errorResponse = validateCategoryName.right().value();
- return Either.right(errorResponse);
- }
+ validateCategory(null, updateInfoResource, null, inTransaction);
if (hasBeenCertified) {
CategoryDefinition currentCategory = currentResource.getCategories().get(0);
SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories().get(0);
@@ -5748,11 +4345,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (!derivedFromCurrent.equals(derivedFromUpdated)) {
if (!hasBeenCertified) {
- Either<Boolean, ResponseFormat> validateDerivedFromExistsEither = validateDerivedFromExist(null,
- updateInfoResource, null);
- if (validateDerivedFromExistsEither.isRight()) {
- return validateDerivedFromExistsEither;
- }
+ validateDerivedFromExist(null, updateInfoResource, null);
} else {
Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
currentResource, updateInfoResource, null);
@@ -5790,11 +4383,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (!derivedFromCurrent.equals(derivedFromUpdated)) {
if (!hasBeenCertified) {
- Either<Boolean, ResponseFormat> validateDerivedFromExistsEither = validateDerivedFromExist(null,
- updateInfoResource, null);
- if (validateDerivedFromExistsEither.isRight()) {
- return validateDerivedFromExistsEither;
- }
+ validateDerivedFromExist(null, updateInfoResource, null);
} else {
Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
currentResource, updateInfoResource, null);
@@ -5808,16 +4397,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(true);
}
- private Either<Boolean, ResponseFormat> validateDerivedFromExist(User user, Resource resource,
- AuditingActionEnum actionEnum) {
-
+ private void validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) {
if (resource.getDerivedFrom() == null || resource.getDerivedFrom().isEmpty()) {
- return Either.left(true);
+ return;
}
-
-
String templateName = resource.getDerivedFrom().get(0);
-
Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
.validateToscaResourceNameExists(templateName);
if (dataModelResponse.isRight()) {
@@ -5828,16 +4412,13 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
log.trace("audit before sending response");
componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
- return Either.right(responseFormat);
+ throw new ComponentException(componentsUtils.convertFromStorageResponse(storageStatus));
} else if (!dataModelResponse.left().value()) {
log.info("resource template with name: {}, does not exists", templateName);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
-
- return Either.right(responseFormat);
-
+ throw new ComponentException(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
}
- return Either.left(true);
}
// Tal G for extending inheritance US815447
@@ -5872,8 +4453,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(true);
}
- public Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty(User user, Resource resource,
- AuditingActionEnum actionEnum) {
+ 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())) {
@@ -5882,230 +4462,194 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
.getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
- return Either.right(responseFormat);
+ throw new ComponentException(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
}
- return Either.left(true);
}
- private Either<Boolean, ResponseFormat> validateResourceNameExists(Resource resource) {
+ private void validateResourceNameUniqueness(Resource resource) {
Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade
.validateComponentNameExists(resource.getName(), resource.getResourceType(),
resource.getComponentType());
- if (resourceOperationResponse.isLeft()) {
- if (!resourceOperationResponse.left().value()) {
- return Either.left(false);
- } else {
- log.debug("resource with name: {}, already exists", resource.getName());
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(
- ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(),
- resource.getName());
- return Either.right(errorResponse);
- }
+ if (resourceOperationResponse.isLeft() && resourceOperationResponse.left().value()) {
+ log.debug("resource with name: {}, already exists", resource.getName());
+ throw new ComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(),
+ resource.getName());
+ } else if(resourceOperationResponse.isRight()){
+ log.debug("error while validateResourceNameExists for resource: {}", resource.getName());
+ throw new StorageException(resourceOperationResponse.right().value());
}
- log.debug("error while validateResourceNameExists for resource: {}", resource.getName());
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(
- componentsUtils.convertFromStorageResponse(resourceOperationResponse.right().value()));
- return Either.right(errorResponse);
}
- private Either<Boolean, ResponseFormat> validateCategory(User user, Resource resource,
- AuditingActionEnum actionEnum, boolean inTransaction) {
+ private void validateCategory(User user, Resource resource,
+ AuditingActionEnum actionEnum, boolean inTransaction) {
List<CategoryDefinition> categories = resource.getCategories();
- if (categories == null || categories.size() == 0) {
- log.debug("Resource category is empty");
+ if (CollectionUtils.isEmpty(categories)) {
+ log.debug(CATEGORY_IS_EMPTY);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
ComponentTypeEnum.RESOURCE.getValue());
componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
- return Either.right(responseFormat);
+ throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
+ ComponentTypeEnum.RESOURCE.getValue());
}
if (categories.size() > 1) {
log.debug("Must be only one category for resource");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(
- ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.RESOURCE.getValue());
- return Either.right(responseFormat);
+ throw new ComponentException(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.RESOURCE.getValue());
}
CategoryDefinition category = categories.get(0);
List<SubCategoryDefinition> subcategories = category.getSubcategories();
- if (subcategories == null || subcategories.size() == 0) {
+ if (CollectionUtils.isEmpty(subcategories)) {
log.debug("Missinig subcategory for resource");
- ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
- return Either.right(responseFormat);
+ throw new ComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
}
if (subcategories.size() > 1) {
log.debug("Must be only one sub category for resource");
- ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
- return Either.right(responseFormat);
+ throw new ComponentException(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
}
SubCategoryDefinition subcategory = subcategories.get(0);
if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
- log.debug("Resource category is empty");
+ log.debug(CATEGORY_IS_EMPTY);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
ComponentTypeEnum.RESOURCE.getValue());
componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
- return Either.right(responseFormat);
+ throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
+ ComponentTypeEnum.RESOURCE.getValue());
}
if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
- log.debug("Resource category is empty");
+ log.debug(CATEGORY_IS_EMPTY);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(
ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
- return Either.right(responseFormat);
- }
-
- Either<Boolean, ResponseFormat> validateCategory = validateCategoryListed(category, subcategory, inTransaction);
- if (validateCategory.isRight()) {
- ResponseFormat responseFormat = validateCategory.right().value();
- componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
- return Either.right(responseFormat);
+ throw new ComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
}
- return Either.left(true);
+ validateCategoryListed(category, subcategory, user, resource, actionEnum, inTransaction);
}
- private Either<Boolean, ResponseFormat> validateCategoryListed(CategoryDefinition category,
- SubCategoryDefinition subcategory, boolean inTransaction) {
+ private void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory,
+ User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
+ ResponseFormat responseFormat;
if (category != null && subcategory != null) {
log.debug("validating resource category {} against valid categories list", category);
Either<List<CategoryDefinition>, ActionStatus> categories = elementDao
.getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
if (categories.isRight()) {
log.debug("failed to retrive resource categories from Titan");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(categories.right().value());
- return Either.right(responseFormat);
+ responseFormat = componentsUtils.getResponseFormat(categories.right().value());
+ componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+ throw new ComponentException(categories.right().value());
}
List<CategoryDefinition> categoryList = categories.left().value();
- for (CategoryDefinition cat : categoryList) {
- if (cat.getName().equals(category.getName())) {
- for (SubCategoryDefinition subcat : cat.getSubcategories()) {
- if (subcat.getName().equals(subcategory.getName())) {
- return Either.left(true);
- }
- }
- log.debug(
- "SubCategory {} is not part of resource category group. Resource subcategory valid values are {}",
- subcategory, cat.getSubcategories());
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY,
- ComponentTypeEnum.RESOURCE.getValue()));
- }
+ Optional<CategoryDefinition> foundCategory = categoryList.stream()
+ .filter(cat -> cat.getName().equals(category.getName()))
+ .findFirst();
+ if(!foundCategory.isPresent()){
+ log.debug("Category {} is not part of resource category group. Resource category valid values are {}",
+ category, categoryList);
+ failOnInvalidCategory(user, resource, actionEnum);
+ }
+ Optional<SubCategoryDefinition> foundSubcategory = foundCategory.get()
+ .getSubcategories()
+ .stream()
+ .filter(subcat -> subcat.getName().equals(subcategory.getName()))
+ .findFirst();
+ if(!foundSubcategory.isPresent()){
+ log.debug("SubCategory {} is not part of resource category group. Resource subcategory valid values are {}",
+ subcategory, foundCategory.get().getSubcategories());
+ failOnInvalidCategory(user, resource, actionEnum);
}
- log.debug("Category {} is not part of resource category group. Resource category valid values are {}",
- category, categoryList);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY,
- ComponentTypeEnum.RESOURCE.getValue()));
}
- return Either.left(false);
}
- public Either<Boolean, ResponseFormat> validateVendorReleaseName(User user, Resource resource,
- AuditingActionEnum actionEnum) {
- String vendorRelease = resource.getVendorRelease();
+ private void failOnInvalidCategory(User user, Resource resource, AuditingActionEnum actionEnum) {
+ ResponseFormat responseFormat;
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY,
+ ComponentTypeEnum.RESOURCE.getValue());
+ componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+ throw new ComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY,
+ ComponentTypeEnum.RESOURCE.getValue());
+ }
+ public void validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) {
+ String vendorRelease = resource.getVendorRelease();
log.debug("validate vendor relese name");
if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) {
log.info("vendor relese name is missing.");
ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
- return Either.right(errorResponse);
+ throw new ComponentException(ActionStatus.MISSING_VENDOR_RELEASE);
}
- Either<Boolean, ResponseFormat> validateVendorReleaseResponse = validateVendorReleaseName(vendorRelease);
- if (validateVendorReleaseResponse.isRight()) {
- ResponseFormat responseFormat = validateVendorReleaseResponse.right().value();
- componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
- }
- return validateVendorReleaseResponse;
+ validateVendorReleaseName(vendorRelease, user, resource, actionEnum);
}
- public Either<Boolean, ResponseFormat> validateVendorReleaseName(String vendorRelease) {
+ public void validateVendorReleaseName(String vendorRelease, User user, Resource resource, AuditingActionEnum actionEnum) {
if (vendorRelease != null) {
if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
log.info("vendor release exceds limit.");
ResponseFormat errorResponse = componentsUtils.getResponseFormat(
ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
- return Either.right(errorResponse);
+ componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
+ throw new ComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
}
if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
log.info("vendor release is not valid.");
ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
- return Either.right(errorResponse);
+ componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
+ throw new ComponentException(ActionStatus.INVALID_VENDOR_RELEASE);
}
- return Either.left(true);
}
- return Either.left(false);
-
}
- private Either<Boolean, ResponseFormat> validateVendorName(User user, Resource resource,
- AuditingActionEnum actionEnum) {
+ private void validateVendorName(User user, Resource resource,
+ AuditingActionEnum actionEnum) {
String vendorName = resource.getVendorName();
if (!ValidationUtils.validateStringNotEmpty(vendorName)) {
log.info("vendor name is missing.");
ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME);
componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
- return Either.right(errorResponse);
- }
-
- Either<Boolean, ResponseFormat> validateVendorNameResponse = validateVendorName(vendorName);
- if (validateVendorNameResponse.isRight()) {
- ResponseFormat responseFormat = validateVendorNameResponse.right().value();
- componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+ throw new ComponentException(ActionStatus.MISSING_VENDOR_NAME);
}
- return validateVendorNameResponse;
-
- }
-
- private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(User user, Resource resource,
- AuditingActionEnum actionEnum) {
- String resourceVendorModelNumber = resource.getResourceVendorModelNumber();
- Either<Boolean, ResponseFormat> validateResourceVendorModelNumber = validateResourceVendorModelNumber(
- resourceVendorModelNumber);
- if (validateResourceVendorModelNumber.isRight()) {
- ResponseFormat responseFormat = validateResourceVendorModelNumber.right().value();
- componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
- }
- return validateResourceVendorModelNumber;
-
+ validateVendorName(vendorName, user, resource, actionEnum);
}
- private Either<Boolean, ResponseFormat> validateVendorName(String vendorName) {
+ private void validateVendorName(String vendorName, User user, Resource resource,
+ AuditingActionEnum actionEnum) {
if (vendorName != null) {
if (!ValidationUtils.validateVendorNameLength(vendorName)) {
log.info("vendor name exceds limit.");
ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
"" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
- return Either.right(errorResponse);
+ componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
+ throw new ComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
+ "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
}
if (!ValidationUtils.validateVendorName(vendorName)) {
log.info("vendor name is not valid.");
ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
- return Either.right(errorResponse);
+ componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
+ throw new ComponentException(ActionStatus.INVALID_VENDOR_NAME);
}
- return Either.left(true);
-
}
- return Either.left(false);
-
}
- private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(String resourceVendorModelNumber) {
- if (StringUtils.isEmpty(resourceVendorModelNumber)) {
- return Either.left(true);
- } else {
+ private void validateResourceVendorModelNumber(User user, Resource resource, AuditingActionEnum actionEnum) {
+ String resourceVendorModelNumber = resource.getResourceVendorModelNumber();
+ if (StringUtils.isNotEmpty(resourceVendorModelNumber)) {
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);
- return Either.right(errorResponse);
+ componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
+ throw new ComponentException(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
+ "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
}
// resource vendor model number is currently validated as vendor
// name
@@ -6113,49 +4657,45 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
log.info("resource vendor model number is not valid.");
ResponseFormat errorResponse = componentsUtils
.getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
- return Either.right(errorResponse);
+ componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
+ throw new ComponentException(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
}
- return Either.left(true);
}
}
- private Either<Boolean, ResponseFormat> validateCost(User user, Resource resource, AuditingActionEnum actionEnum) {
+ private void validateCost(Resource resource) {
String cost = resource.getCost();
if (cost != null) {
-
if (!ValidationUtils.validateCost(cost)) {
log.debug("resource cost is invalid.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- return Either.right(errorResponse);
+ throw new ComponentException(ActionStatus.INVALID_CONTENT);
}
}
- return Either.left(true);
}
- private Either<Boolean, ResponseFormat> validateLicenseType(User user, Resource resource,
- AuditingActionEnum actionEnum) {
+ private void validateLicenseType(User user, Resource resource,
+ AuditingActionEnum actionEnum) {
log.debug("validate licenseType");
String licenseType = resource.getLicenseType();
if (licenseType != null) {
List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration()
.getLicenseTypes();
if (!licenseTypes.contains(licenseType)) {
- log.debug("License type {} isn't configured");
+ log.debug("License type {} isn't configured", licenseType);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
if (actionEnum != null) {
// In update case, no audit is required
componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
}
- return Either.right(responseFormat);
+ throw new ComponentException(ActionStatus.INVALID_CONTENT);
}
}
- return Either.left(true);
}
private Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom(Resource currentResource,
- Resource updatedResource, String userId, boolean shouldLock, boolean inTransaction) {
- Either<Operation, ResponseFormat> deleteArtifactByInterface = null;
+ Resource updatedResource, String userId, boolean inTransaction) {
+ Either<Operation, ResponseFormat> deleteArtifactByInterface;
if (updatedResource.getDerivedFrom() != null) {
log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId());
log.debug("1. Removing interface artifacts from graph");
@@ -6206,8 +4746,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (findPropertiesOfNode.isRight()
&& !findPropertiesOfNode.right().value().equals(StorageOperationStatus.OK)) {
log.debug("Failed to remove all properties of resource");
- if (!inTransaction)
+ if (!inTransaction) {
titanDao.rollback();
+ }
return Either.right(componentsUtils.getResponseFormat(
componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right().value())));
}
@@ -6216,8 +4757,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
log.debug("Derived from wasn't changed during update");
}
- if (!inTransaction)
- titanDao.commit();
+ if (inTransaction) {
+ return Either.left(true);
+ }
+ titanDao.commit();
return Either.left(true);
}
@@ -6245,57 +4788,74 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
log.debug("validate resource properties default values");
Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
List<PropertyDefinition> properties = resource.getProperties();
+ if (properties != null) {
+ eitherResult = iterateOverProperties(properties);
+ }
+ return eitherResult;
+ }
+
+ public Either<Boolean, ResponseFormat> iterateOverProperties(List<PropertyDefinition> properties){
+ Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
String type = null;
String innerType = null;
- if (properties != null) {
- for (PropertyDefinition property : properties) {
- if (!propertyOperation.isPropertyTypeValid(property)) {
- log.info("Invalid type for property");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(
- ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
- eitherResult = Either.right(responseFormat);
- break;
- }
+ for (PropertyDefinition property : properties) {
+ if (!propertyOperation.isPropertyTypeValid(property)) {
+ log.info("Invalid type for property {}", property);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(
+ ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
+ eitherResult = Either.right(responseFormat);
+ break;
+ }
- Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(
- applicationDataTypeCache);
- if (allDataTypes.isRight()) {
- return Either.right(allDataTypes.right().value());
- }
+ Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(
+ applicationDataTypeCache);
+ if (allDataTypes.isRight()) {
+ return Either.right(allDataTypes.right().value());
+ }
- type = property.getType();
- if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
- ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation
- .isPropertyInnerTypeValid(property, allDataTypes.left().value());
- innerType = propertyInnerTypeValid.getLeft();
- if (!propertyInnerTypeValid.getRight().booleanValue()) {
- log.info("Invalid inner type for property");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(
- ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
- eitherResult = Either.right(responseFormat);
- break;
- }
- }
+ type = property.getType();
- if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes.left().value())) {
- log.info("Invalid default value for property");
- ResponseFormat responseFormat;
- if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE,
- property.getName(), type, innerType, property.getDefaultValue());
- } else {
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE,
- property.getName(), type, property.getDefaultValue());
- }
- eitherResult = Either.right(responseFormat);
+ if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
+ ResponseFormat responseFormat = validateMapOrListPropertyType(property, innerType, allDataTypes.left().value());
+ if(responseFormat != null) {
break;
-
}
}
+ eitherResult = validateDefaultPropertyValue(property, allDataTypes.left().value(), type, innerType);
}
return eitherResult;
}
+ private Either<Boolean,ResponseFormat> validateDefaultPropertyValue(PropertyDefinition property, Map<String, DataTypeDefinition> allDataTypes, String type, String innerType) {
+ if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes)) {
+ log.info("Invalid default value for property {}", property);
+ ResponseFormat responseFormat;
+ if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE,
+ property.getName(), type, innerType, property.getDefaultValue());
+ } else {
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE,
+ property.getName(), type, property.getDefaultValue());
+ }
+ return Either.right(responseFormat);
+
+ }
+ return Either.left(true);
+ }
+
+ private ResponseFormat validateMapOrListPropertyType(PropertyDefinition property, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
+ ResponseFormat responseFormat = null;
+ ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation
+ .isPropertyInnerTypeValid(property, allDataTypes);
+ innerType = propertyInnerTypeValid.getLeft();
+ if (!propertyInnerTypeValid.getRight().booleanValue()) {
+ log.info("Invalid inner type for property {}", property);
+ responseFormat = componentsUtils.getResponseFormat(
+ ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
+ }
+ return responseFormat;
+ }
+
@Override
public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
return deleteMarkedComponents(ComponentTypeEnum.RESOURCE);
@@ -6314,205 +4874,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return componentTypeForResponse;
}
- private Either<Map<String, GroupDefinition>, ResponseFormat> createGroupsFromYaml(String yamlFileName,
- Map<String, Object> toscaJson, Resource resource) {
-
- Map<String, GroupDefinition> groups = new HashMap<String, GroupDefinition>();
- Either<Map<String, GroupDefinition>, ResponseFormat> result = Either.left(groups);
-
- Either<Map<String, Object>, ResultStatusEnum> eitherNodesTemlates = ImportUtils
- .findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.GROUPS);
- if (eitherNodesTemlates.isLeft()) {
- Map<String, Object> jsonNodeTemplates = eitherNodesTemlates.left().value();
-
- if (jsonNodeTemplates != null && false == jsonNodeTemplates.isEmpty()) {
- Iterator<Entry<String, Object>> nodesNameValue = jsonNodeTemplates.entrySet().iterator();
- while (nodesNameValue.hasNext()) {
- Entry<String, Object> groupNameValue = nodesNameValue.next();
-
- String groupName = groupNameValue.getKey();
- Either<GroupDefinition, ResponseFormat> eitherNode = createGroupInfo(groupName,
- groupNameValue.getValue());
- if (eitherNode.isRight()) {
- String message = "Failed when creating group: " + groupNameValue.getKey() + " for resource:"
- + resource.getName();
- BeEcompErrorManager.getInstance().logInternalFlowError("ImportResource", message,
- ErrorSeverity.INFO);
- return Either.right(eitherNode.right().value());
- } else {
- GroupDefinition groupDefinition = eitherNode.left().value();
- groups.put(groupName, groupDefinition);
- }
- }
- }
- }
-
- return result;
- }
-
- private Either<Map<String, InputDefinition>, ResponseFormat> createInputsFromYaml(String yamlFileName,
- Map<String, Object> toscaJson, Resource resource) {
-
- Either<Map<String, InputDefinition>, ResultStatusEnum> inputs = ImportUtils.getInputs(toscaJson);
- if (inputs.isRight()) {
- String message = "Failed when creating inputs: for resource:" + resource.getName();
- BeEcompErrorManager.getInstance().logInternalFlowError("ImportResource", message, ErrorSeverity.INFO);
- Map<String, InputDefinition> resultMap = new HashMap<>();
- return Either.left(resultMap);
-
- }
-
- Either<Map<String, InputDefinition>, ResponseFormat> result = Either.left(inputs.left().value());
-
- return result;
- }
-
- @SuppressWarnings("unchecked")
- private Either<GroupDefinition, ResponseFormat> createGroupInfo(String groupName, Object groupTemplateJson) {
-
- GroupDefinition groupInfo = new GroupDefinition();
- groupInfo.setName(groupName);
- Either<GroupDefinition, ResponseFormat> result = Either.left(groupInfo);
-
- try {
- if (groupTemplateJson != null && groupTemplateJson instanceof Map) {
- Map<String, Object> groupTemplateJsonMap = (Map<String, Object>) groupTemplateJson;
- String groupType = (String) groupTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName());
- if (!StringUtils.isEmpty(groupType)) {
- groupInfo.setType(groupType);
- } else {
- log.debug("The 'type' member is not found under group {}", groupName);
- return Either
- .right(componentsUtils.getResponseFormat(ActionStatus.GROUP_MISSING_GROUP_TYPE, groupName));
- }
-
- if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
- groupInfo.setDescription(
- (String) groupTemplateJsonMap.get(ToscaTagNamesEnum.DESCRIPTION.getElementName()));
- }
-
- if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.MEMBERS.getElementName())) {
- Object members = groupTemplateJsonMap.get(ToscaTagNamesEnum.MEMBERS.getElementName());
- if (members != null) {
- if (members instanceof List) {
- Map<String, String> membersLoaded = new HashMap<>();
- List<?> membersAsList = (List<?>) members;
- for (Object member : membersAsList) {
- membersLoaded.put(member.toString(), "");
- }
- groupInfo.setMembers(membersLoaded);
- } else {
- log.debug("The 'members' member is not of type list under group {}", groupName);
- return Either
- .right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
- }
- }
- }
-
- if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
- Object properties = groupTemplateJsonMap.get(ToscaTagNamesEnum.PROPERTIES.getElementName());
-
- Either<List<GroupProperty>, ResponseFormat> regResponse = createPropertiesValueModuleFromYaml(
- properties, groupName, groupType);
- if (regResponse.isRight())
- return Either.right(regResponse.right().value());
- if (regResponse.left().value().size() > 0) {
- groupInfo.convertFromGroupProperties(regResponse.left().value());
- }
- }
-
- } else {
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
- }
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create group");
- log.debug("error when creating group, message:{}", e.getMessage(), e);
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
- }
-
- return result;
- }
-
- @SuppressWarnings("unchecked")
- private Either<List<GroupProperty>, ResponseFormat> createPropertiesValueModuleFromYaml(Object properties,
- String groupName, String groupType) {
-
- List<GroupProperty> result = new ArrayList<>();
-
- if (properties == null) {
- return Either.left(result);
- }
-
- Either<GroupTypeDefinition, StorageOperationStatus> groupTypeRes = groupTypeOperation
- .getLatestGroupTypeByType(groupType, true);
-
- if (groupTypeRes.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, groupType));
- }
-
- Map<String, PropertyDefinition> gtProperties = new HashMap<>();
- GroupTypeDefinition groupTypeDefinition = groupTypeRes.left().value();
-
- List<PropertyDefinition> propertiesDef = groupTypeDefinition.getProperties();
-
- if (propertiesDef != null) {
- gtProperties = propertiesDef.stream().collect(Collectors.toMap(p -> p.getName(), p -> p));
- }
-
- if (properties != null) {
-
- if (properties instanceof Map) {
-
- Map<String, Object> props = (Map<String, Object>) properties;
- for (Entry<String, Object> entry : props.entrySet()) {
-
- String propName = entry.getKey();
- Object value = entry.getValue();
-
- PropertyDefinition gtDefinition = gtProperties.get(propName);
- if (gtDefinition == null) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_PROPERTY_NOT_FOUND,
- propName, groupName, groupType));
- }
-
- ToscaPropertyType type = ToscaPropertyType.isValidType(gtDefinition.getType());
-
- String convertedValue = null;
- if (value != null) {
- if (type == null || value instanceof Map || value instanceof List) {
- convertedValue = gson.toJson(value);
- } else {
- convertedValue = value.toString();
- }
- }
-
- GroupProperty groupProperty = new GroupProperty();
- groupProperty.setValue(convertedValue);
- groupProperty.setName(propName);
-
- log.trace("After building group property {}", groupProperty);
-
- result.add(groupProperty);
- }
-
- }
-
- }
-
- return Either.left(result);
- }
-
public Either<Resource, ResponseFormat> getLatestResourceFromCsarUuid(String csarUuid, User user) {
-
// validate user
if (user != null) {
- Either<User, ResponseFormat> userValidation = validateUserExists(user, "Get resource from csar UUID",
+ validateUserExists(user, "Get resource from csar UUID",
false);
- if (userValidation.isRight()) {
- return Either.right(userValidation.right().value());
- }
}
-
// get resource from csar uuid
Either<Resource, StorageOperationStatus> either = toscaOperationFacade
.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, "");
@@ -6527,91 +4894,92 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
@Override
public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(
- String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) {
+ String componentId, String userId) {
return null;
}
- private Either<Map<String, List<CapabilityDefinition>>, ResponseFormat> getValidComponentInstanceCapabilities(
+ private Map<String, List<CapabilityDefinition>> getValidComponentInstanceCapabilities(
String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities,
Map<String, List<UploadCapInfo>> uploadedCapabilities) {
- ResponseFormat responseFormat;
+
Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
+ uploadedCapabilities.forEach((k,v)->addValidComponentInstanceCapabilities(k,v,resourceId,defaultCapabilities,validCapabilitiesMap));
+ return validCapabilitiesMap;
+ }
+
+ private void addValidComponentInstanceCapabilities(String key, List<UploadCapInfo> capabilities, String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities, Map<String, List<CapabilityDefinition>> validCapabilitiesMap){
+ String capabilityType = capabilities.get(0).getType();
+ if (defaultCapabilities.containsKey(capabilityType)) {
+ CapabilityDefinition defaultCapability = getCapability(resourceId, defaultCapabilities, capabilityType);
+ validateCapabilityProperties(capabilities, resourceId, defaultCapability);
+ List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
+ validCapabilityList.add(defaultCapability);
+ validCapabilitiesMap.put(key, validCapabilityList);
+ } else {
+ throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType));
+ }
+ }
- for (Entry<String, List<UploadCapInfo>> uploadedCapabilitiesEntry : uploadedCapabilities.entrySet()) {
- String capabilityType = uploadedCapabilitiesEntry.getValue().get(0).getType();
- if (!defaultCapabilities.containsKey(capabilityType)) {
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE,
- capabilityType);
- return Either.right(responseFormat);
- } else {
- CapabilityDefinition defaultCapability;
- if (CollectionUtils.isNotEmpty(defaultCapabilities.get(capabilityType).get(0).getProperties())) {
- defaultCapability = defaultCapabilities.get(capabilityType).get(0);
- } else {
- Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade
- .getToscaFullElement(resourceId);
- if (getFullComponentRes.isRight()) {
- log.debug("Failed to get full component {}. Status is {}. ", resourceId,
- getFullComponentRes.right().value());
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND,
- resourceId);
- return Either.right(responseFormat);
- }
- defaultCapability = getFullComponentRes.left().value().getCapabilities().get(capabilityType).get(0);
- }
- if (CollectionUtils.isEmpty(defaultCapability.getProperties())
- && CollectionUtils.isNotEmpty(uploadedCapabilitiesEntry.getValue().get(0).getProperties())) {
- log.debug("Failed to validate capability {} of component {}. Property list is empty. ",
- defaultCapability.getName(), resourceId);
- log.debug(
- "Failed to update capability property values. Property list of fetched capability {} is empty. ",
- defaultCapability.getName());
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, resourceId);
- return Either.right(responseFormat);
- }
- if (CollectionUtils.isNotEmpty(defaultCapability.getProperties())
- && CollectionUtils.isNotEmpty(uploadedCapabilitiesEntry.getValue().get(0).getProperties())) {
- Either<Boolean, String> validationRes = validateUniquenessUpdateUploadedComponentInstanceCapability(
- defaultCapability, uploadedCapabilitiesEntry.getValue().get(0));
- if (validationRes.isRight()) {
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS,
- validationRes.right().value());
- return Either.right(responseFormat);
- }
- }
- List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
- validCapabilityList.add(defaultCapability);
- validCapabilitiesMap.put(uploadedCapabilitiesEntry.getKey(), validCapabilityList);
+ private void validateCapabilityProperties(List<UploadCapInfo> capabilities, String resourceId, CapabilityDefinition defaultCapability) {
+ if (CollectionUtils.isEmpty(defaultCapability.getProperties())
+ && isNotEmpty(capabilities.get(0).getProperties())) {
+ log.debug("Failed to validate capability {} of component {}. Property list is empty. ",
+ defaultCapability.getName(), resourceId);
+ log.debug(
+ "Failed to update capability property values. Property list of fetched capability {} is empty. ",
+ defaultCapability.getName());
+ throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, resourceId));
+ } else if (isNotEmpty(capabilities.get(0).getProperties())) {
+ validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, capabilities.get(0));
+ }
+ }
+
+ private CapabilityDefinition getCapability(String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities, String capabilityType) {
+ CapabilityDefinition defaultCapability;
+ if (isNotEmpty(defaultCapabilities.get(capabilityType).get(0).getProperties())) {
+ defaultCapability = defaultCapabilities.get(capabilityType).get(0);
+ } else {
+ Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade
+ .getToscaFullElement(resourceId);
+ if (getFullComponentRes.isRight()) {
+ log.debug("Failed to get full component {}. Status is {}. ", resourceId,
+ getFullComponentRes.right().value());
+ throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND,
+ resourceId));
}
+ defaultCapability = getFullComponentRes.left().value().getCapabilities().get(capabilityType).get(0);
}
- return Either.left(validCapabilitiesMap);
+ return defaultCapability;
}
- private Either<Boolean, String> validateUniquenessUpdateUploadedComponentInstanceCapability(
+ private void validateUniquenessUpdateUploadedComponentInstanceCapability(
CapabilityDefinition defaultCapability, UploadCapInfo uploadedCapability) {
List<ComponentInstanceProperty> validProperties = new ArrayList<>();
Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties().stream()
- .collect(Collectors.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();
String propertyType = property.getType();
ComponentInstanceProperty validProperty;
- if (defaultProperties.containsKey(propertyName)) {
- if (propertyType != null && !defaultProperties.get(propertyName).getType().equals(propertyType)) {
- return Either.right(propertyName);
- }
+ if (defaultProperties.containsKey(propertyName) && propertTypeEqualsTo(defaultProperties, propertyName, propertyType)) {
+ throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS,
+ propertyName));
}
validProperty = new ComponentInstanceProperty();
validProperty.setName(propertyName);
- if (property.getValue() != null)
+ if (property.getValue() != null) {
validProperty.setValue(property.getValue().toString());
+ }
validProperty.setDescription(property.getDescription());
validProperty.setPassword(property.isPassword());
validProperties.add(validProperty);
}
defaultCapability.setProperties(validProperties);
- return Either.left(true);
+ }
+
+ private boolean propertTypeEqualsTo(Map<String, PropertyDefinition> defaultProperties, String propertyName, String propertyType) {
+ return propertyType != null && !defaultProperties.get(propertyName).getType().equals(propertyType);
}
private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(
@@ -6623,7 +4991,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either
.left(nodeTypeArtifactsToHandle);
- ;
try {
// add all found Csar artifacts to list to upload
List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
@@ -6684,12 +5051,15 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
}
if (responseWrapper.isEmpty()) {
- if (!artifactsToUpload.isEmpty())
+ if (!artifactsToUpload.isEmpty()) {
nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
- if (!artifactsToUpdate.isEmpty())
+ }
+ if (!artifactsToUpdate.isEmpty()) {
nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
- if (!artifactsToDelete.isEmpty())
+ }
+ if (!artifactsToDelete.isEmpty()) {
nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
+ }
}
if (!responseWrapper.isEmpty()) {
nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
@@ -6702,7 +5072,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return nodeTypeArtifactsToHandleRes;
}
- private ImmutablePair<String, String> buildNestedToscaResourceName(String nodeResourceType, String vfResourceName,
+ ImmutablePair<String, String> buildNestedToscaResourceName(String nodeResourceType, String vfResourceName,
String nodeTypeFullName) {
String actualType;
String actualVfName;
@@ -6743,11 +5113,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
this.cacheManagerOperation = cacheManagerOperation;
}
- ///////////////////////////////////////// DataModel
- ///////////////////////////////////////// refactoring/////////////////////////////////////////////
@Override
- public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId,
- List<String> dataParamsToReturn) {
+ public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId, List<String> dataParamsToReturn) {
ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
Either<Resource, StorageOperationStatus> resourceResultEither = toscaOperationFacade.getToscaElement(resourceId,
@@ -6765,7 +5132,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
Resource resource = resourceResultEither.left().value();
- UiComponentDataTransfer dataTransfer = UiComponentDataConverter.getUiDataTransferFromResourceByParams(resource,
+ UiComponentDataTransfer dataTransfer = uiComponentDataConverter.getUiDataTransferFromResourceByParams(resource,
dataParamsToReturn);
return Either.left(dataTransfer);
}
@@ -6786,65 +5153,4 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
}
- private Either<Boolean, ResponseFormat> validateAndUpdateInterfaces(String resourceId, Resource resourceUpdate) {
- Either<Resource, StorageOperationStatus> resourceStorageOperationStatusEither =
- toscaOperationFacade.getToscaElement(resourceId);
- if (resourceStorageOperationStatusEither.isRight()) {
- StorageOperationStatus errorStatus = resourceStorageOperationStatusEither.right().value();
- log.error("Failed to fetch resource information by resource id {}, error {}", resourceId, errorStatus);
- return Either.right(componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
- }
-
- Resource storedResource = resourceStorageOperationStatusEither.left().value();
- Map<String, InterfaceDefinition> storedResourceInterfaces = storedResource.getInterfaces();
-
- if(!storedResource.getName().equals(resourceUpdate.getName()) ) {
- Collection<InterfaceDefinition> interfaceDefinitionListFromToscaName = InterfaceUtils
- .getInterfaceDefinitionListFromToscaName(storedResource.getInterfaces().values(),
- storedResource.getName());
-
- for (InterfaceDefinition interfaceDefinition : storedResourceInterfaces.values()) {
- Either<InterfaceDefinition, ResponseFormat> updateInterfaceDefinitionEither = updateInterfaceDefinition(resourceUpdate,
- interfaceDefinition,
- interfaceDefinitionListFromToscaName);
- if(updateInterfaceDefinitionEither.isRight()) {
- return Either.right(updateInterfaceDefinitionEither.right().value());
- }
- }
- }
-
- return Either.left(Boolean.TRUE);
- }
-
- private Either<InterfaceDefinition, ResponseFormat > updateInterfaceDefinition(Resource resourceUpdate,
- InterfaceDefinition interfaceDefinition,
- Collection<InterfaceDefinition> interfaceDefinitionListFromToscaName) {
- interfaceDefinitionListFromToscaName.forEach(interfaceDefinitionFromList -> {
- if(interfaceDefinitionFromList.getToscaResourceName().equals(interfaceDefinition
- .getToscaResourceName())) {
- log.info("Going to Update interface definition toscaResourceName {} to {}",
- interfaceDefinitionFromList.getToscaResourceName(),
- InterfaceUtils.createInterfaceToscaResourceName(resourceUpdate.getName()));
- interfaceDefinition.setToscaResourceName(InterfaceUtils
- .createInterfaceToscaResourceName(resourceUpdate.getName()));
- }
- } );
- try {
- Either<InterfaceDefinition, StorageOperationStatus> interfaceUpdate = interfaceOperation
- .updateInterface(resourceUpdate.getUniqueId(), interfaceDefinition);
- if (interfaceUpdate.isRight()) {
- log.error("Failed to Update interface {}. Response is {}. ", resourceUpdate.getName(), interfaceUpdate.right().value());
- titanDao.rollback();
- return Either.right(componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(interfaceUpdate.right().value(), ComponentTypeEnum.RESOURCE)));
- }
- } catch (Exception e) {
- log.error("Exception occurred during update interface toscaResourceName : {}", e.getMessage(), e);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
-
- return Either.left( interfaceDefinition);
-
- }
} \ No newline at end of file
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 6d6d80b840..42858f4d57 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
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,30 +20,17 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.ArrayList;
-import java.util.Arrays;
-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.Set;
-import java.util.function.Function;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
-
-import javax.servlet.ServletContext;
-
+import fj.data.Either;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.auditing.api.AuditEventFactory;
import org.openecomp.sdc.be.auditing.impl.AuditingManager;
import org.openecomp.sdc.be.auditing.impl.resourceadmin.AuditImportResourceAdminEventFactory;
+import org.openecomp.sdc.be.components.csar.CsarInfo;
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
import org.openecomp.sdc.be.components.impl.ImportUtils.Constants;
import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
-import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
+import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
@@ -54,17 +41,7 @@ import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.CapabilityDefinition;
-import org.openecomp.sdc.be.model.ComponentInstanceProperty;
-import org.openecomp.sdc.be.model.CsarInfo;
-import org.openecomp.sdc.be.model.InterfaceDefinition;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.model.RequirementDefinition;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.UploadResourceInfo;
-import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
@@ -73,18 +50,24 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
-import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
+import org.openecomp.sdc.be.utils.TypeUtils;
+import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.ThreadLocalsHolder;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import org.yaml.snakeyaml.Yaml;
-import fj.data.Either;
+import javax.servlet.ServletContext;
+import java.util.*;
+import java.util.Map.Entry;
+import java.util.function.Function;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
@Component("resourceImportManager")
public class ResourceImportManager {
@@ -103,7 +86,7 @@ public class ResourceImportManager {
@Autowired
protected ComponentsUtils componentsUtils;
- public final static Pattern PROPERTY_NAME_PATTERN_IGNORE_LENGTH = Pattern
+ public static final Pattern PROPERTY_NAME_PATTERN_IGNORE_LENGTH = Pattern
.compile("[\\w\\-\\_\\d\\:]+");
@Autowired
protected CapabilityTypeOperation capabilityTypeOperation;
@@ -112,7 +95,7 @@ public class ResourceImportManager {
private ResponseFormatManager responseFormatManager;
- private static final Logger log = LoggerFactory.getLogger(ResourceImportManager.class);
+ private static final Logger log = Logger.getLogger(ResourceImportManager.class);
public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) {
this.toscaOperationFacade = toscaOperationFacade;
@@ -137,7 +120,7 @@ public class ResourceImportManager {
}
public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> importCertifiedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, Function<Resource, Either<Boolean, ResponseFormat>> validationFunction,
- LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean isInTransaction, boolean createNewVersion, boolean needLock, Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, String nodeName, boolean isNested) {
+ LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean isInTransaction, boolean createNewVersion, boolean needLock, Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, String nodeName, boolean isNested) {
Resource resource = new Resource();
ImmutablePair<Resource, ActionStatus> responsePair = new ImmutablePair<>(resource, ActionStatus.CREATED);
Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> response = Either.left(responsePair);
@@ -165,38 +148,39 @@ public class ResourceImportManager {
return Either.right(componentsUtils.getResponseFormatByResource(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, resource));
}
}
-
- response = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, true, isInTransaction, needLock, csarInfo, nodeName, isNested);
+ resource = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, true, isInTransaction, needLock, csarInfo, nodeName, isNested).left;
Either<Resource, ResponseFormat> changeStateResponse;
- if (response.isLeft()) {
- resource = response.left().value().left;
-
- if(nodeTypeArtifactsToHandle !=null && !nodeTypeArtifactsToHandle.isEmpty()){
- Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes =
- resourceBusinessLogic.handleNodeTypeArtifacts(resource, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, creator, isInTransaction, false);
- if(handleNodeTypeArtifactsRes.isRight()){
- return Either.right(handleNodeTypeArtifactsRes.right().value());
- }
- }
- latestCertifiedResourceId = getLatestCertifiedResourceId(resource);
- changeStateResponse = resourceBusinessLogic.propagateStateToCertified(creator, resource, lifecycleChangeInfo, isInTransaction, needLock, forceCertificationAllowed);
- if (changeStateResponse.isRight()) {
- response = Either.right(changeStateResponse.right().value());
- } else {
- responsePair = new ImmutablePair<>(changeStateResponse.left().value(), response.left().value().right);
- response = Either.left(responsePair);
+
+ if (nodeTypeArtifactsToHandle != null && !nodeTypeArtifactsToHandle.isEmpty()) {
+ Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes =
+ resourceBusinessLogic.handleNodeTypeArtifacts(resource, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, creator, isInTransaction, false);
+ if (handleNodeTypeArtifactsRes.isRight()) {
+ return Either.right(handleNodeTypeArtifactsRes.right().value());
}
}
- } else {
+ latestCertifiedResourceId = getLatestCertifiedResourceId(resource);
+ changeStateResponse = resourceBusinessLogic.propagateStateToCertified(creator, resource, lifecycleChangeInfo, isInTransaction, needLock, forceCertificationAllowed);
+ if (changeStateResponse.isRight()) {
+ response = Either.right(changeStateResponse.right().value());
+ }
+ else {
+ responsePair = new ImmutablePair<>(changeStateResponse.left().value(), response.left()
+ .value().right);
+ response = Either.left(responsePair);
+ }
+ }
+ else {
ResponseFormat validationErrorResponse = isValidResource.right().value();
auditErrorImport(resourceMetaData, creator, validationErrorResponse, true);
response = Either.right(validationErrorResponse);
}
- } catch (RuntimeException e) {
- ResponseFormat exceptionResponse = handleImportResourceExecption(resourceMetaData, creator, true, e);
+ }
+ catch (RuntimeException e) {
+ ResponseFormat exceptionResponse = handleImportResourceException(resourceMetaData, creator, true, e, null);
response = Either.right(exceptionResponse);
- } finally {
+ }
+ finally {
if (latestCertifiedResourceId != null && needLock) {
log.debug("unlock resource {}", latestCertifiedResourceId);
graphLockOperation.unlockComponent(latestCertifiedResourceId, NodeTypeEnum.Resource);
@@ -217,7 +201,8 @@ public class ResourceImportManager {
}
}
return allVersions.get(String.valueOf(latestCertifiedVersion));
- } else {
+ }
+ else {
return null;
}
}
@@ -244,7 +229,7 @@ public class ResourceImportManager {
public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> importUserDefinedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction) {
Resource resource = new Resource();
- ImmutablePair<Resource, ActionStatus> responsePair = new ImmutablePair<Resource, ActionStatus>(resource, ActionStatus.CREATED);
+ ImmutablePair<Resource, ActionStatus> responsePair = new ImmutablePair<>(resource, ActionStatus.CREATED);
Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> response = Either.left(responsePair);
try {
@@ -265,26 +250,27 @@ public class ResourceImportManager {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
}
- Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty = resourceBusinessLogic.validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
- if (validateDerivedFromNotEmpty.isRight()) {
- return Either.right(validateDerivedFromNotEmpty.right().value());
- }
-
+ resourceBusinessLogic.validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
Either<Boolean, ResponseFormat> validatePropertiesTypes = resourceBusinessLogic.validatePropertiesDefaultValues(resource);
if (validatePropertiesTypes.isLeft()) {
- response = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, false, isInTransaction, true, null, null, false);
- } else {
+ response = Either.left(resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, false, isInTransaction, true, null, null, false));
+ }
+ else {
ResponseFormat validationErrorResponse = validatePropertiesTypes.right().value();
auditErrorImport(resourceMetaData, creator, validationErrorResponse, false);
response = Either.right(validationErrorResponse);
}
- } catch (RuntimeException e) {
- ResponseFormat exceptionResponse = handleImportResourceExecption(resourceMetaData, creator, false, e);
- response = Either.right(exceptionResponse);
}
-
+ catch (ComponentException e) {
+ ResponseFormat responseFormat = e.getResponseFormat() != null?
+ e.getResponseFormat() : getResponseFormatManager().getResponseFormat(e.getActionStatus(), e.getParams());
+ response = Either.right(handleImportResourceException(resourceMetaData, creator, false, e, responseFormat));
+ }
+ catch (RuntimeException e) {
+ response = Either.right(handleImportResourceException(resourceMetaData, creator, false, e, null));
+ }
return response;
}
@@ -296,9 +282,9 @@ public class ResourceImportManager {
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) {
- toscaJson = new HashMap<String, Object>();
- toscaJson.put(ToscaTagNamesEnum.NODE_TYPES.getElementName(), toscaJsonAll.get(ToscaTagNamesEnum.NODE_TYPES.getElementName()));
+ if (toscaJsonAll.containsKey(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName()) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
+ toscaJson = new HashMap<>();
+ toscaJson.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), toscaJsonAll.get(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName()));
}
// Derived From
Either<Resource, ResponseFormat> setDerivedFrom = setDerivedFrom(toscaJson, resource);
@@ -306,7 +292,7 @@ public class ResourceImportManager {
return Either.right(setDerivedFrom.right().value());
}
Resource parentResource = setDerivedFrom.left().value();
- if(StringUtils.isEmpty(resource.getToscaResourceName())) {
+ if (StringUtils.isEmpty(resource.getToscaResourceName())) {
setToscaResourceName(toscaJson, resource);
}
setAttributes(toscaJson, resource);
@@ -328,7 +314,7 @@ public class ResourceImportManager {
}
private void setToscaResourceName(Map<String, Object> toscaJson, Resource resource) {
- Either<Map<String, Object>, ResultStatusEnum> toscaElement = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.NODE_TYPES);
+ Either<Map<String, Object>, ResultStatusEnum> toscaElement = ImportUtils.findFirstToscaMapElement(toscaJson, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
if (toscaElement.isLeft() || toscaElement.left().value().size() == 1) {
String toscaResourceName = toscaElement.left().value().keySet().iterator().next();
resource.setToscaResourceName(toscaResourceName);
@@ -336,17 +322,19 @@ public class ResourceImportManager {
}
private void setInterfaceLifecycle(Map<String, Object> toscaJson, Resource resource) {
- Either<Map<String, Object>, ResultStatusEnum> toscaInterfaces = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.INTERFACES);
+ Either<Map<String, Object>, ResultStatusEnum> toscaInterfaces = ImportUtils.findFirstToscaMapElement(toscaJson, TypeUtils.ToscaTagNamesEnum.INTERFACES);
if (toscaInterfaces.isLeft()) {
Map<String, Object> jsonInterfaces = toscaInterfaces.left().value();
- Map<String, InterfaceDefinition> moduleInterfaces = new HashMap<String, InterfaceDefinition>();
+ Map<String, InterfaceDefinition> moduleInterfaces = new HashMap<>();
Iterator<Entry<String, Object>> interfacesNameValue = jsonInterfaces.entrySet().iterator();
while (interfacesNameValue.hasNext()) {
Entry<String, Object> interfaceNameValue = interfacesNameValue.next();
- Either<InterfaceDefinition, ResultStatusEnum> eitherInterface = createModuleInterface(interfaceNameValue.getValue());
+ Either<InterfaceDefinition, ResultStatusEnum> eitherInterface = createModuleInterface(interfaceNameValue
+ .getValue());
if (eitherInterface.isRight()) {
log.info("error when creating interface:{}, for resource:{}", interfaceNameValue.getKey(), resource.getName());
- } else {
+ }
+ else {
moduleInterfaces.put(interfaceNameValue.getKey(), eitherInterface.left().value());
}
@@ -365,18 +353,21 @@ public class ResourceImportManager {
if (interfaceJson instanceof String) {
String requirementJsonString = (String) interfaceJson;
interf.setType(requirementJsonString);
- } else if (interfaceJson instanceof Map) {
+ }
+ else if (interfaceJson instanceof Map) {
Map<String, Object> requirementJsonMap = (Map<String, Object>) interfaceJson;
- if (requirementJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
- String type = (String) requirementJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName());
+ if (requirementJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName())) {
+ String type = (String) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName());
interf.setType(type);
interf.setUniqueId(type.toLowerCase());
}
- } else {
+ }
+ else {
result = Either.right(ResultStatusEnum.GENERAL_ERROR);
}
- } catch (Exception e) {
+ }
+ catch (Exception e) {
BeEcompErrorManager.getInstance().logBeSystemError("Import Resource- create interface");
log.debug("error when creating interface, message:{}", e.getMessage(), e);
result = Either.right(ResultStatusEnum.GENERAL_ERROR);
@@ -387,10 +378,10 @@ public class ResourceImportManager {
private Either<Boolean, ResponseFormat> setRequirements(Map<String, Object> toscaJson, Resource resource, Resource parentResource) {// Note that parentResource can be null
Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
- Either<List<Object>, ResultStatusEnum> toscaRequirements = ImportUtils.findFirstToscaListElement(toscaJson, ToscaTagNamesEnum.REQUIREMENTS);
+ Either<List<Object>, ResultStatusEnum> toscaRequirements = ImportUtils.findFirstToscaListElement(toscaJson, TypeUtils.ToscaTagNamesEnum.REQUIREMENTS);
if (toscaRequirements.isLeft()) {
List<Object> jsonRequirements = toscaRequirements.left().value();
- Map<String, List<RequirementDefinition>> moduleRequirements = new HashMap<String, List<RequirementDefinition>>();
+ 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
@@ -412,7 +403,8 @@ public class ResourceImportManager {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "requirement", reqNameLowerCase));
}
reqNames.add(reqNameLowerCase);
- Either<RequirementDefinition, ResponseFormat> eitherRequirement = createRequirementFromImportFile(requirementJsonWrapper.get(requirementName));
+ Either<RequirementDefinition, ResponseFormat> eitherRequirement = createRequirementFromImportFile(requirementJsonWrapper
+ .get(requirementName));
if (eitherRequirement.isRight()) {
log.info("error when creating Requirement:{}, for resource:{}", requirementName, resource.getName());
return Either.right(eitherRequirement.right().value());
@@ -421,20 +413,25 @@ public class ResourceImportManager {
requirementDef.setName(requirementName);
if (moduleRequirements.containsKey(requirementDef.getCapability())) {
moduleRequirements.get(requirementDef.getCapability()).add(requirementDef);
- } else {
- List<RequirementDefinition> list = new ArrayList<RequirementDefinition>();
+ }
+ else {
+ List<RequirementDefinition> list = new ArrayList<>();
list.add(requirementDef);
moduleRequirements.put(requirementDef.getCapability(), list);
}
// Validating against req/cap of "derived from" node
- Either<Boolean, ResponseFormat> validateVsParentCap = validateCapNameVsDerived(reqName2TypeMap, requirementDef.getCapability(), requirementDef.getName());
+ Either<Boolean, ResponseFormat> validateVsParentCap = validateCapNameVsDerived(reqName2TypeMap, requirementDef
+ .getCapability(), requirementDef.getName());
if (validateVsParentCap.isRight()) {
return Either.right(validateVsParentCap.right().value());
}
if (!validateVsParentCap.left().value()) {
- log.debug("Requirement with name {} already exists in parent {}", requirementDef.getName(), parentResource.getName());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "requirement", requirementDef.getName().toLowerCase(), parentResource.getName());
+ log.debug("Requirement with name {} already exists in parent {}", requirementDef.getName(), parentResource
+ .getName());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "requirement", requirementDef
+ .getName()
+ .toLowerCase(), parentResource.getName());
return Either.right(responseFormat);
}
}
@@ -455,21 +452,22 @@ public class ResourceImportManager {
if (requirementJson instanceof String) {
String requirementJsonString = (String) requirementJson;
requirement.setCapability(requirementJsonString);
- } else if (requirementJson instanceof Map) {
+ }
+ else if (requirementJson instanceof Map) {
Map<String, Object> requirementJsonMap = (Map<String, Object>) requirementJson;
- if (requirementJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITY.getElementName())) {
- requirement.setCapability((String) requirementJsonMap.get(ToscaTagNamesEnum.CAPABILITY.getElementName()));
+ if (requirementJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.CAPABILITY.getElementName())) {
+ requirement.setCapability((String) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.CAPABILITY.getElementName()));
}
- if (requirementJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) {
- requirement.setNode((String) requirementJsonMap.get(ToscaTagNamesEnum.NODE.getElementName()));
+ if (requirementJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.NODE.getElementName())) {
+ requirement.setNode((String) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.NODE.getElementName()));
}
- if (requirementJsonMap.containsKey(ToscaTagNamesEnum.RELATIONSHIP.getElementName())) {
- requirement.setRelationship((String) requirementJsonMap.get(ToscaTagNamesEnum.RELATIONSHIP.getElementName()));
+ if (requirementJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.RELATIONSHIP.getElementName())) {
+ requirement.setRelationship((String) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.RELATIONSHIP.getElementName()));
}
- if (requirementJsonMap.containsKey(ToscaTagNamesEnum.OCCURRENCES.getElementName())) {
- List<Object> occurrencesList = (List) requirementJsonMap.get(ToscaTagNamesEnum.OCCURRENCES.getElementName());
+ if (requirementJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName())) {
+ List<Object> occurrencesList = (List) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName());
Either<Boolean, ResponseFormat> validateAndSetOccurrencesStatus = validateOccurrences(occurrencesList);
if (validateAndSetOccurrencesStatus.isRight()) {
result = Either.right(validateAndSetOccurrencesStatus.right().value());
@@ -481,11 +479,13 @@ public class ResourceImportManager {
}
}
- } else {
+ }
+ else {
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
}
- } catch (Exception e) {
+ }
+ catch (Exception e) {
BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create Requirement");
log.debug("error when creating requirement, message:{}", e.getMessage(), e);
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
@@ -505,7 +505,7 @@ public class ResourceImportManager {
if (value != null) {
for (Entry<String, PropertyDefinition> entry : value.entrySet()) {
String name = entry.getKey();
- if(!PROPERTY_NAME_PATTERN_IGNORE_LENGTH.matcher(name).matches()){
+ if (!PROPERTY_NAME_PATTERN_IGNORE_LENGTH.matcher(name).matches()) {
log.debug("The property with invalid name {} occured upon import resource {}. ", name, resource.getName());
result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromResultStatusEnum(ResultStatusEnum.INVALID_PROPERTY_NAME, JsonPresentationFields.PROPERTY)));
}
@@ -515,8 +515,11 @@ public class ResourceImportManager {
}
}
resource.setProperties(propertiesList);
- } else if(properties.right().value() != ResultStatusEnum.ELEMENT_NOT_FOUND){
- result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromResultStatusEnum(properties.right().value(), JsonPresentationFields.PROPERTY)));
+ }
+ else if (properties.right().value() != ResultStatusEnum.ELEMENT_NOT_FOUND) {
+ result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromResultStatusEnum(properties
+ .right()
+ .value(), JsonPresentationFields.PROPERTY)));
}
return result;
}
@@ -536,19 +539,20 @@ public class ResourceImportManager {
}
}
resource.setAttributes(attributeList);
- } else {
+ }
+ else {
result = attributes.right().value();
}
return result;
}
private Either<Resource, ResponseFormat> setDerivedFrom(Map<String, Object> toscaJson, Resource resource) {
- Either<String, ResultStatusEnum> toscaDerivedFromElement = ImportUtils.findFirstToscaStringElement(toscaJson, ToscaTagNamesEnum.DERIVED_FROM);
+ Either<String, ResultStatusEnum> toscaDerivedFromElement = ImportUtils.findFirstToscaStringElement(toscaJson, TypeUtils.ToscaTagNamesEnum.DERIVED_FROM);
Resource derivedFromResource = null;
if (toscaDerivedFromElement.isLeft()) {
String derivedFrom = toscaDerivedFromElement.left().value();
log.debug("Derived from TOSCA name is {}", derivedFrom);
- resource.setDerivedFrom(Arrays.asList(new String[] { derivedFrom }));
+ resource.setDerivedFrom(Arrays.asList(new String[]{derivedFrom}));
Either<Resource, StorageOperationStatus> latestByToscaResourceName = toscaOperationFacade.getLatestByToscaResourceName(derivedFrom);
if (latestByToscaResourceName.isRight()) {
@@ -558,7 +562,8 @@ public class ResourceImportManager {
}
log.debug("Error when fetching parent resource {}, error: {}", derivedFrom, operationStatus);
ActionStatus convertFromStorageResponse = componentsUtils.convertFromStorageResponse(operationStatus);
- BeEcompErrorManager.getInstance().logBeComponentMissingError("Import TOSCA YAML", "resource", derivedFrom);
+ BeEcompErrorManager.getInstance()
+ .logBeComponentMissingError("Import TOSCA YAML", "resource", derivedFrom);
return Either.right(componentsUtils.getResponseFormat(convertFromStorageResponse, derivedFrom));
}
derivedFromResource = latestByToscaResourceName.left().value();
@@ -568,10 +573,10 @@ public class ResourceImportManager {
private Either<Boolean, ResponseFormat> setCapabilities(Map<String, Object> toscaJson, Resource resource, Resource parentResource) {// Note that parentResource can be null
Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
- Either<Map<String, Object>, ResultStatusEnum> toscaCapabilities = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.CAPABILITIES);
+ Either<Map<String, Object>, ResultStatusEnum> toscaCapabilities = ImportUtils.findFirstToscaMapElement(toscaJson, TypeUtils.ToscaTagNamesEnum.CAPABILITIES);
if (toscaCapabilities.isLeft()) {
Map<String, Object> jsonCapabilities = toscaCapabilities.left().value();
- Map<String, List<CapabilityDefinition>> moduleCapabilities = new HashMap<String, List<CapabilityDefinition>>();
+ Map<String, List<CapabilityDefinition>> moduleCapabilities = new HashMap<>();
Iterator<Entry<String, Object>> capabilitiesNameValue = jsonCapabilities.entrySet().iterator();
Set<String> capNames = new HashSet<>();
// Getting flattened list of capabilities of parent node - cap name
@@ -594,9 +599,11 @@ public class ResourceImportManager {
}
capNames.add(capNameLowerCase);
- Either<CapabilityDefinition, ResponseFormat> eitherCapability = createCapabilityFromImportFile(capabilityNameValue.getValue());
+ Either<CapabilityDefinition, ResponseFormat> eitherCapability = createCapabilityFromImportFile(capabilityNameValue
+ .getValue());
if (eitherCapability.isRight()) {
- log.debug("error when creating capability:{}, for resource:{}", capabilityNameValue.getKey(), resource.getName());
+ log.debug("error when creating capability:{}, for resource:{}", capabilityNameValue.getKey(), resource
+ .getName());
return Either.right(eitherCapability.right().value());
}
@@ -604,22 +611,27 @@ public class ResourceImportManager {
capabilityDef.setName(capabilityNameValue.getKey());
if (moduleCapabilities.containsKey(capabilityDef.getType())) {
moduleCapabilities.get(capabilityDef.getType()).add(capabilityDef);
- } else {
- List<CapabilityDefinition> list = new ArrayList<CapabilityDefinition>();
+ }
+ else {
+ List<CapabilityDefinition> list = new ArrayList<>();
list.add(capabilityDef);
moduleCapabilities.put(capabilityDef.getType(), list);
}
// Validating against req/cap of "derived from" node
- Either<Boolean, ResponseFormat> validateVsParentCap = validateCapNameVsDerived(capName2TypeMap, capabilityDef.getType(), capabilityDef.getName());
+ Either<Boolean, ResponseFormat> validateVsParentCap = validateCapNameVsDerived(capName2TypeMap, capabilityDef
+ .getType(), capabilityDef.getName());
if (validateVsParentCap.isRight()) {
return Either.right(validateVsParentCap.right().value());
}
if (!validateVsParentCap.left().value()) {
// Here parentResource is for sure not null, so it's
// null-safe
- log.debug("Capability with name {} already exists in parent {}", capabilityDef.getName(), parentResource.getName());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "capability", capabilityDef.getName().toLowerCase(), parentResource.getName());
+ log.debug("Capability with name {} already exists in parent {}", capabilityDef.getName(), parentResource
+ .getName());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "capability", capabilityDef
+ .getName()
+ .toLowerCase(), parentResource.getName());
return Either.right(responseFormat);
}
}
@@ -643,7 +655,8 @@ public class ResourceImportManager {
if (capName2type.get(nameLowerCase) != null) {
String parentResourceName = parentResource.getName();
log.debug("Resource with name {} has more than one capability with name {}, ignoring case", parentResourceName, nameLowerCase);
- BeEcompErrorManager.getInstance().logInternalDataError("Import resource", "Parent resource " + parentResourceName + " of imported resource has one or more capabilities with name " + nameLowerCase, ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance()
+ .logInternalDataError("Import resource", "Parent resource " + parentResourceName + " of imported resource has one or more capabilities with name " + nameLowerCase, ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
capName2type.put(nameLowerCase, capDefinition.getType());
@@ -665,7 +678,8 @@ public class ResourceImportManager {
if (reqName2type.get(nameLowerCase) != null) {
String parentResourceName = parentResource.getName();
log.debug("Resource with name {} has more than one requirement with name {}, ignoring case", parentResourceName, nameLowerCase);
- BeEcompErrorManager.getInstance().logInternalDataError("Import resource", "Parent resource " + parentResourceName + " of imported resource has one or more requirements with name " + nameLowerCase, ErrorSeverity.ERROR);
+ BeEcompErrorManager.getInstance()
+ .logInternalDataError("Import resource", "Parent resource " + parentResourceName + " of imported resource has one or more requirements with name " + nameLowerCase, ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
reqName2type.put(nameLowerCase, reqDefinition.getCapability());
@@ -688,7 +702,9 @@ public class ResourceImportManager {
Either<Boolean, StorageOperationStatus> capabilityTypeDerivedFrom = capabilityTypeOperation.isCapabilityTypeDerivedFrom(childCapabilityType, parentCapType);
if (capabilityTypeDerivedFrom.isRight()) {
log.debug("Couldn't check whether imported resource capability derives from its parent's capability");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(capabilityTypeDerivedFrom.right().value()));
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(capabilityTypeDerivedFrom
+ .right()
+ .value()));
return Either.right(responseFormat);
}
return Either.left(capabilityTypeDerivedFrom.left().value());
@@ -705,22 +721,24 @@ public class ResourceImportManager {
if (capabilityJson instanceof String) {
String capabilityJsonString = (String) capabilityJson;
capabilityDefinition.setType(capabilityJsonString);
- } else if (capabilityJson instanceof Map) {
+ }
+ else if (capabilityJson instanceof Map) {
Map<String, Object> capabilityJsonMap = (Map<String, Object>) capabilityJson;
// Type
- if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
- capabilityDefinition.setType((String) capabilityJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName()));
+ if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName())) {
+ capabilityDefinition.setType((String) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName()));
}
// ValidSourceTypes
- if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())) {
- capabilityDefinition.setValidSourceTypes((List<String>) capabilityJsonMap.get(ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName()));
+ if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())) {
+ capabilityDefinition.setValidSourceTypes((List<String>) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.VALID_SOURCE_TYPES
+ .getElementName()));
}
// ValidSourceTypes
- if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
- capabilityDefinition.setDescription((String) capabilityJsonMap.get(ToscaTagNamesEnum.DESCRIPTION.getElementName()));
+ if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
+ capabilityDefinition.setDescription((String) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName()));
}
- if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.OCCURRENCES.getElementName())) {
- List<Object> occurrencesList = (List) capabilityJsonMap.get(ToscaTagNamesEnum.OCCURRENCES.getElementName());
+ if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName())) {
+ List<Object> occurrencesList = (List) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName());
Either<Boolean, ResponseFormat> validateAndSetOccurrencesStatus = validateOccurrences(occurrencesList);
if (validateAndSetOccurrencesStatus.isRight()) {
result = Either.right(validateAndSetOccurrencesStatus.right().value());
@@ -731,24 +749,37 @@ public class ResourceImportManager {
capabilityDefinition.setMaxOccurrences(occurrencesList.get(1).toString());
}
}
- if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
+ if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.PROPERTIES.getElementName())) {
Either<Map<String, PropertyDefinition>, ResultStatusEnum> propertiesRes = ImportUtils.getProperties(capabilityJsonMap);
if (propertiesRes.isRight()) {
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND));
return result;
- } else {
- propertiesRes.left().value().entrySet().stream().forEach(e -> e.getValue().setName(e.getKey().toLowerCase()));
- List<ComponentInstanceProperty> capabilityProperties = propertiesRes.left().value().values().stream().map(p -> new ComponentInstanceProperty(p, p.getDefaultValue(), null)).collect(Collectors.toList());
+ }
+ else {
+ propertiesRes.left()
+ .value()
+ .entrySet()
+ .stream()
+ .forEach(e -> e.getValue().setName(e.getKey().toLowerCase()));
+ List<ComponentInstanceProperty> capabilityProperties = propertiesRes.left()
+ .value()
+ .values()
+ .stream()
+ .map(p -> new ComponentInstanceProperty(p, p
+ .getDefaultValue(), null))
+ .collect(Collectors.toList());
capabilityDefinition.setProperties(capabilityProperties);
}
}
- } else if (!(capabilityJson instanceof List)) {
+ }
+ else if (!(capabilityJson instanceof List)) {
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
}
- } catch (Exception e) {
+ }
+ catch (Exception e) {
BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create capability");
log.debug("error when creating capability, message:{}", e.getMessage(), e);
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
@@ -757,48 +788,28 @@ public class ResourceImportManager {
return result;
}
- private ResponseFormat handleImportResourceExecption(UploadResourceInfo resourceMetaData, User user, boolean isNormative, RuntimeException e) {
+ private ResponseFormat handleImportResourceException(UploadResourceInfo resourceMetaData, User user, boolean isNormative, RuntimeException e, ResponseFormat responseFormat) {
+ if(responseFormat == null ){
+ responseFormat = getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR);
+ }
String payloadName = (resourceMetaData != null) ? resourceMetaData.getPayloadName() : "";
BeEcompErrorManager.getInstance().logBeSystemError("Import Resource " + payloadName);
-
log.debug("Error when importing resource from payload:{} Exception text: {}", payloadName, e.getMessage(), e);
- ResponseFormat errorResponseWrapper = getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR);
- auditErrorImport(resourceMetaData, user, errorResponseWrapper, isNormative);
- return errorResponseWrapper;
+ auditErrorImport(resourceMetaData, user, responseFormat, isNormative);
+ return responseFormat;
}
private void auditErrorImport(UploadResourceInfo resourceMetaData, User user, ResponseFormat errorResponseWrapper, boolean isNormative) {
-// EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class);
-// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.IMPORT_RESOURCE.getName());
-// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceMetaData.getName());
-// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, ComponentTypeEnum.RESOURCE.getValue());
-// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, "");
-// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, user.getUserId());
-// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, "");
-// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, "");
-// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, errorResponseWrapper.getStatus());
-// String message = "";
-// if (errorResponseWrapper.getMessageId() != null) {
-// message = errorResponseWrapper.getMessageId() + ": ";
-// }
-// message += errorResponseWrapper.getFormattedMessage();
-// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message);
-// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, user.getFirstName() + " " + user.getLastName());
-
String version, lifeCycleState;
if (isNormative) {
- version = Constants.FIRST_CERTIFIED_VERSION_VERSION;
+ version = TypeUtils.FIRST_CERTIFIED_VERSION_VERSION;
lifeCycleState = LifecycleStateEnum.CERTIFIED.name();
- } else {
+ }
+ else {
version = "";
lifeCycleState = LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name();
}
-// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, version);
-// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, lifeCycleState);
-// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TOSCA_NODE_TYPE, "");
-// getAuditingManager().auditEvent(auditingFields);
-
String message = "";
if (errorResponseWrapper.getMessageId() != null) {
@@ -807,22 +818,22 @@ public class ResourceImportManager {
message += errorResponseWrapper.getFormattedMessage();
-
AuditEventFactory factory = new AuditImportResourceAdminEventFactory(
CommonAuditData.newBuilder()
- .status(errorResponseWrapper.getStatus())
- .description(message)
- .requestId(ThreadLocalsHolder.getUuid())
- .build(),
- ResourceAuditData.newBuilder()
- .state(lifeCycleState)
- .version(version)
- .build(),
- ResourceAuditData.newBuilder()
- .state("")
- .version("")
- .build(),
- ComponentTypeEnum.RESOURCE.getValue(), resourceMetaData.getName(), "", user, "");
+ .status(errorResponseWrapper.getStatus())
+ .description(message)
+ .requestId(ThreadLocalsHolder.getUuid())
+ .build(),
+ new ResourceCommonInfo(resourceMetaData.getName(), ComponentTypeEnum.RESOURCE.getValue()),
+ ResourceVersionInfo.newBuilder()
+ .state(lifeCycleState)
+ .version(version)
+ .build(),
+ ResourceVersionInfo.newBuilder()
+ .state("")
+ .version("")
+ .build(),
+ "", user, "");
getAuditingManager().auditEvent(factory);
}
@@ -838,7 +849,8 @@ public class ResourceImportManager {
if (categories != null && !categories.isEmpty()) {
CategoryDefinition categoryDef = categories.get(0);
resource.setAbstract(false);
- if (categoryDef != null && categoryDef.getName() != null && categoryDef.getName().equals(Constants.ABSTRACT_CATEGORY_NAME)) {
+ if (categoryDef != null && categoryDef.getName() != null && categoryDef.getName()
+ .equals(Constants.ABSTRACT_CATEGORY_NAME)) {
SubCategoryDefinition subCategoryDef = categoryDef.getSubcategories().get(0);
if (subCategoryDef != null && subCategoryDef.getName().equals(Constants.ABSTRACT_SUBCATEGORY)) {
resource.setAbstract(true);
@@ -850,10 +862,11 @@ public class ResourceImportManager {
private void setConstantMetaData(Resource resource, boolean shouldBeCertified) {
String version;
LifecycleStateEnum state;
- if(shouldBeCertified){
- version = ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION;
+ if (shouldBeCertified) {
+ version = TypeUtils.FIRST_CERTIFIED_VERSION_VERSION;
state = ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE;
- }else{
+ }
+ else {
version = ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION;
state = ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT;
}
@@ -880,10 +893,11 @@ public class ResourceImportManager {
}
Object minObj = occurrensesList.get(0);
Object maxObj = occurrensesList.get(1);
- Integer minOccurrences = null;
+ Integer minOccurrences;
Integer maxOccurrences = null;
- if (minObj instanceof Integer)
+ if (minObj instanceof Integer) {
minOccurrences = (Integer) minObj;
+ }
else {
log.debug("Invalid occurrenses format. low_bound occurrense must be Integer {}", minObj);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES);
@@ -898,14 +912,17 @@ public class ResourceImportManager {
if (maxObj instanceof String) {
if ("UNBOUNDED".equals(maxObj)) {
return Either.left(true);
- } else {
+ }
+ else {
log.debug("Invalid occurrenses format. Max occurrence is {}", maxObj);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES);
return Either.right(responseFormat);
}
- } else {
- if (maxObj instanceof Integer)
+ }
+ else {
+ if (maxObj instanceof Integer) {
maxOccurrences = (Integer) maxObj;
+ }
else {
log.debug("Invalid occurrenses format. Max occurrence is {}", maxObj);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES);
@@ -938,8 +955,7 @@ public class ResourceImportManager {
private ResourceBusinessLogic getResourceBL(ServletContext context) {
WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(org.openecomp.sdc.common.api.Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- ResourceBusinessLogic resourceBl = webApplicationContext.getBean(ResourceBusinessLogic.class);
- return resourceBl;
+ return webApplicationContext.getBean(ResourceBusinessLogic.class);
}
public ServletContext getServletContext() {
@@ -966,10 +982,6 @@ public class ResourceImportManager {
this.resourceBusinessLogic = resourceBusinessLogic;
}
- public Logger getLog() {
- return log;
- }
-
public IGraphLockOperation getGraphLockOperation() {
return graphLockOperation;
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResponseFormatManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResponseFormatManager.java
index a6344929a5..19d63f30b4 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResponseFormatManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResponseFormatManager.java
@@ -25,18 +25,17 @@ import org.openecomp.sdc.be.config.ErrorConfiguration;
import org.openecomp.sdc.be.config.ErrorInfo;
import org.openecomp.sdc.be.config.ErrorInfo.ErrorInfoType;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.exception.OkResponseInfo;
import org.openecomp.sdc.exception.PolicyException;
import org.openecomp.sdc.exception.ResponseFormat;
import org.openecomp.sdc.exception.ServiceException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
public class ResponseFormatManager {
private volatile static ResponseFormatManager instance;
private static ConfigurationManager configurationManager;
- private static final Logger log = LoggerFactory.getLogger(ResponseFormatManager.class);
+ private static final Logger log = Logger.getLogger(ResponseFormatManager.class);
public static ResponseFormatManager getInstance() {
if (instance == null) {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java
index 48cbb35fdd..f30088ce9c 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java
@@ -20,30 +20,19 @@
package org.openecomp.sdc.be.components.impl;
-import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.Set;
-import java.util.concurrent.Callable;
-import java.util.function.Function;
-import java.util.stream.Collectors;
-
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-
-import org.apache.commons.collections.CollectionUtils;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Strings;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import fj.data.Either;
import org.apache.commons.collections.MapUtils;
+import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.components.distribution.engine.IDistributionEngine;
import org.openecomp.sdc.be.components.distribution.engine.INotificationData;
import org.openecomp.sdc.be.components.distribution.engine.VfModuleArtifactPayload;
import org.openecomp.sdc.be.components.health.HealthCheckBusinessLogic;
+import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
import org.openecomp.sdc.be.components.path.ForwardingPathValidator;
import org.openecomp.sdc.be.components.validation.ServiceDistributionValidation;
@@ -56,23 +45,13 @@ import org.openecomp.sdc.be.datamodel.ServiceRelations;
import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.InstantiationTypes;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceDistributionReqInfo;
import org.openecomp.sdc.be.impl.ForwardingPathUtils;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.ComponentParametersView;
-import org.openecomp.sdc.be.model.DistributionStatusEnum;
-import org.openecomp.sdc.be.model.DistributionTransitionEnum;
-import org.openecomp.sdc.be.model.GroupInstance;
-import org.openecomp.sdc.be.model.GroupInstanceProperty;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.jsontitan.operations.ForwardingPathOperation;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
@@ -83,12 +62,9 @@ import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
-import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent;
-import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent;
-import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent;
-import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.*;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
import org.openecomp.sdc.be.user.Role;
import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
@@ -96,76 +72,67 @@ import org.openecomp.sdc.common.api.ArtifactTypeEnum;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.datastructure.Wrapper;
import org.openecomp.sdc.common.kpi.api.ASDCKpiApi;
+import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.GeneralUtility;
import org.openecomp.sdc.common.util.ThreadLocalsHolder;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
-import com.google.common.base.Strings;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import java.nio.charset.StandardCharsets;
+import java.util.*;
+import java.util.concurrent.Callable;
+import java.util.function.Function;
+import java.util.stream.Collectors;
-import fj.data.Either;
+import static org.apache.commons.collections.CollectionUtils.isEmpty;
+import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
+import static org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum.UPDATE_SERVICE_METADATA;
@org.springframework.stereotype.Component("serviceBusinessLogic")
public class ServiceBusinessLogic extends ComponentBusinessLogic {
+ private static final String CHANGE_SERVICE_DISTRIBUTION = "Change Service Distribution";
+ private static final String THE_SERVICE_WITH_SYSTEM_NAME_LOCKED = "The service with system name {} locked. ";
+ private static final String FAILED_TO_LOCK_SERVICE_RESPONSE_IS = "Failed to lock service {}. Response is {}. ";
+ private static final String AUDIT_BEFORE_SENDING_RESPONSE = "audit before sending response";
+ private static final Logger log = Logger.getLogger(ServiceBusinessLogic.class);
+ private static final String INITIAL_VERSION = "0.1";
private static final String STATUS_SUCCESS_200 = "200";
-
- private static final String STATUS_DEPLOYED = "DEPLOYED";
-
- @Autowired
- private IElementOperation elementDao;
-
+ private static final String STATUS_DEPLOYED = "DEPLOYED";
@Autowired
private IDistributionEngine distributionEngine;
-
@Autowired
private AuditCassandraDao auditCassandraDao;
-
@Autowired
private ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
-
- @Autowired
- private GroupBusinessLogic groupBusinessLogic;
-
@Autowired
private ICacheMangerOperation cacheManagerOperation;
-
@Autowired
private ServiceDistributionValidation serviceDistributionValidation;
- private static final Logger log = LoggerFactory.getLogger(ServiceBusinessLogic.class);
- private static final String INITIAL_VERSION = "0.1";
@Autowired
private ForwardingPathOperation forwardingPathOperation;
-
@Autowired
private ForwardingPathValidator forwardingPathValidator;
-
- public ServiceBusinessLogic() {
- log.debug("ServiceBusinessLogic started");
- }
+ @Autowired
+ private UiComponentDataConverter uiComponentDataConverter;
public Either<Service, ResponseFormat> changeServiceDistributionState(String serviceId, String state, LifecycleChangeInfoWithAction commentObj, User user) {
- Either<User, ResponseFormat> resp = validateUserExists(user.getUserId(), "change Service Distribution State", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(user.getUserId(), "change Service Distribution State", false);
log.debug("check request state");
- Either<DistributionTransitionEnum, ResponseFormat> validateEnum = validateTransitionEnum(state, user);
+ Either<DistributionTransitionEnum, ResponseFormat> validateEnum = validateTransitionEnum(state);
if (validateEnum.isRight()) {
return Either.right(validateEnum.right().value());
}
DistributionTransitionEnum distributionTransition = validateEnum.left().value();
AuditingActionEnum auditAction = distributionTransition == DistributionTransitionEnum.APPROVE ? AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_APPROV : AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REJECT;
- Either<String, ResponseFormat> commentResponse = validateComment(commentObj, user, auditAction);
+ Either<String, ResponseFormat> commentResponse = validateComment(commentObj);
if (commentResponse.isRight()) {
return Either.right(commentResponse.right().value());
}
@@ -211,8 +178,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
titanDao.commit();
Service updatedService = result.left().value();
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
- log.debug("audit before sending response");
- componentsUtils.auditComponent(responseFormat, user, updatedService, auditAction, ComponentTypeEnum.SERVICE, ResourceAuditData.newBuilder().build(), comment);
+ log.debug(AUDIT_BEFORE_SENDING_RESPONSE);
+ componentsUtils.auditComponent(responseFormat, user, updatedService, auditAction, new ResourceCommonInfo(ComponentTypeEnum.SERVICE.getValue()), ResourceVersionInfo.newBuilder().build(), comment);
return Either.left(result.left().value());
} finally {
graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service);
@@ -221,10 +188,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
public Either<List<Map<String, Object>>, ResponseFormat> getComponentAuditRecords(String componentVersion, String componentUUID, String userId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Component Audit Records", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "get Component Audit Records", false);
Either<List<Map<String, Object>>, ActionStatus> result;
try {
@@ -268,24 +232,52 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return Either.right(eitherCurrVerAudit.right().value());
}
+
+ Either<List<ResourceAdminEvent>, ActionStatus> eitherArchiveRestoreList = getArchiveRestoreEventList(componentUUID);
+ if (eitherArchiveRestoreList.isRight()) {
+ return Either.right(eitherArchiveRestoreList.right().value());
+ }
+
List<Map<String, Object>> prevVerAuditList = getAuditingFieldsList(eitherprevVerAudit.left().value());
List<Map<String, Object>> currVerAuditList = getAuditingFieldsList(eitherCurrVerAudit.left().value());
- List<Map<String, Object>> duplicateElements = new ArrayList<Map<String, Object>>();
+ List<Map<String, Object>> duplicateElements = new ArrayList<>();
duplicateElements.addAll(prevVerAuditList);
duplicateElements.retainAll(currVerAuditList);
- List<Map<String, Object>> joinedNonDuplicatedList = new ArrayList<Map<String, Object>>();
+ List<Map<String, Object>> joinedNonDuplicatedList = new ArrayList<>();
joinedNonDuplicatedList.addAll(prevVerAuditList);
joinedNonDuplicatedList.removeAll(duplicateElements);
joinedNonDuplicatedList.addAll(currVerAuditList);
+ joinedNonDuplicatedList.addAll(getAuditingFieldsList(eitherArchiveRestoreList.left().value()));
+
return Either.left(joinedNonDuplicatedList);
}
+ private Either<List<ResourceAdminEvent>, ActionStatus> getArchiveRestoreEventList(String componentUUID) {
+ // Archive Query
+ Either<List<ResourceAdminEvent>, ActionStatus> eitherArchiveAudit = auditCassandraDao.getArchiveAuditByServiceInstanceId(componentUUID);
+ if (eitherArchiveAudit.isRight()) {
+ return Either.right(eitherArchiveAudit.right().value());
+ }
+
+ // Restore Query
+ Either<List<ResourceAdminEvent>, ActionStatus> eitherRestoreAudit = auditCassandraDao.getRestoreAuditByServiceInstanceId(componentUUID);
+ if (eitherRestoreAudit.isRight()) {
+ return Either.right(eitherRestoreAudit.right().value());
+ }
+
+ List<ResourceAdminEvent> archiveAudit = new ArrayList<>();
+ archiveAudit.addAll(eitherArchiveAudit.left().value());
+ archiveAudit.addAll(eitherRestoreAudit.left().value());
+
+ return Either.left(archiveAudit);
+ }
+
private List<Map<String, Object>> getAuditingFieldsList(List<? extends AuditingGenericEvent> prevVerAuditList) {
- List<Map<String, Object>> prevVerAudit = new ArrayList<Map<String, Object>>();
+ List<Map<String, Object>> prevVerAudit = new ArrayList<>();
for (AuditingGenericEvent auditEvent : prevVerAuditList) {
auditEvent.fillFields();
prevVerAudit.add(auditEvent.getFields());
@@ -305,19 +297,10 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
public Either<Service, ResponseFormat> createService(Service service, User user) {
// get user details
- Either<User, ResponseFormat> eitherCreator = validateUser(user, "Create Service", service, AuditingActionEnum.CREATE_RESOURCE, false);
- if (eitherCreator.isRight()) {
- return Either.right(eitherCreator.right().value());
- }
- user = eitherCreator.left().value();
-
+ user = validateUser(user, "Create Service", service, AuditingActionEnum.CREATE_RESOURCE, false);
// validate user role
- Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, service, new ArrayList<Role>(), AuditingActionEnum.CREATE_RESOURCE, null);
- if (validateRes.isRight()) {
- return Either.right(validateRes.right().value());
- }
+ validateUserRole(user, service, new ArrayList<>(), AuditingActionEnum.CREATE_RESOURCE, null);
service.setCreatorUserId(user.getUserId());
-
// warn on overridden fields
checkFieldsForOverideAttampt(service);
// enrich object
@@ -358,11 +341,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
createMandatoryArtifactsData(service, user);
createServiceApiArtifactsData(service, user);
setToscaArtifactsPlaceHolders(service, user);
- Either<Resource, ResponseFormat> genericServiceEither = fetchAndSetDerivedFromGenericType(service);
- if (genericServiceEither.isRight())
- return Either.right(genericServiceEither.right().value());
-
- generateAndAddInputsFromGenericTypeProperties(service, genericServiceEither.left().value());
+ generateAndAddInputsFromGenericTypeProperties(service, fetchAndSetDerivedFromGenericType(service));
Either<Service, StorageOperationStatus> dataModelResponse = toscaOperationFacade.createToscaComponent(service);
@@ -376,7 +355,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), service, ComponentTypeEnum.SERVICE);
- log.debug("audit before sending response");
+ log.debug(AUDIT_BEFORE_SENDING_RESPONSE);
componentsUtils.auditComponentAdmin(responseFormat, user, service, actionEnum, ComponentTypeEnum.SERVICE);
return Either.right(responseFormat);
@@ -394,7 +373,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
String serviceUniqueId = service.getUniqueId();
Map<String, ArtifactDefinition> artifactMap = service.getServiceApiArtifacts();
if (artifactMap == null)
- artifactMap = new HashMap<String, ArtifactDefinition>();
+ artifactMap = new HashMap<>();
Map<String, Object> serviceApiArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceApiArtifacts();
List<String> exludeServiceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeServiceCategory();
@@ -439,77 +418,61 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
service.setInvariantUUID(invariantUUID);
return Either.left(service);
- }
-
+ }
+
+
+
private Either<Boolean, ResponseFormat> validateServiceFieldsBeforeCreate(User user, Service service, AuditingActionEnum actionEnum) {
- Either<Boolean, ResponseFormat> componentsFieldsValidation = validateComponentFieldsBeforeCreate(user, service, actionEnum);
- if (componentsFieldsValidation.isRight()) {
- return componentsFieldsValidation;
- }
-
- log.debug("validate service name uniqueness");
- Either<Boolean, ResponseFormat> serviceNameUniquenessValidation = validateComponentNameUnique(user, service, actionEnum);
- if (serviceNameUniquenessValidation.isRight()) {
- return serviceNameUniquenessValidation;
- }
-
- log.debug("validate category");
- Either<Boolean, ResponseFormat> categoryValidation = validateServiceCategory(user, service, actionEnum);
- if (categoryValidation.isRight()) {
- return categoryValidation;
- }
-
- // validate project name (ProjectCode) - mandatory in service
- log.debug("validate projectName");
- Either<Boolean, ResponseFormat> projectCodeValidation = validateProjectCode(user, service, actionEnum);
- if (projectCodeValidation.isRight()) {
- return projectCodeValidation;
- }
+ try {
+ validateComponentFieldsBeforeCreate(user, service, actionEnum);
- log.debug("validate service type");
- Either<Boolean, ResponseFormat> serviceTypeValidation = validateServiceTypeAndCleanup(user, service, actionEnum);
- if (serviceTypeValidation.isRight()) {
- return serviceTypeValidation;
- }
+ Either<Boolean, ResponseFormat> serviceNameUniquenessValidation = validateComponentNameUnique(user, service, actionEnum);
+ if (serviceNameUniquenessValidation.isRight()) {
+ throw new ComponentException(serviceNameUniquenessValidation.right().value());
+ }
+ Either<Boolean, ResponseFormat> categoryValidation = validateServiceCategory(user, service, actionEnum);
+ if (categoryValidation.isRight()) {
+ return categoryValidation;
+ }
+ Either<Boolean, ResponseFormat> projectCodeValidation = validateProjectCode(user, service, actionEnum);
+ if (projectCodeValidation.isRight()) {
+ return projectCodeValidation;
+ }
+ validateServiceTypeAndCleanup(service);
- log.debug("validate service role");
- Either<Boolean, ResponseFormat> serviceRoleValidation = validateServiceRoleAndCleanup(user, service, actionEnum);
- if (serviceRoleValidation.isRight()) {
- return serviceRoleValidation;
+ Either<Boolean, ResponseFormat> serviceRoleValidation = validateServiceRoleAndCleanup(user, service, actionEnum);
+ if (serviceRoleValidation.isRight()) {
+ return serviceRoleValidation;
+ }
+ return validateInstantiationTypeValue(user, service, actionEnum);
+ } catch (ComponentException exception) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(exception);
+ componentsUtils.auditComponentAdmin(responseFormat, user, service,
+ AuditingActionEnum.CREATE_SERVICE, ComponentTypeEnum.SERVICE);
+ return Either.right(responseFormat);
}
-
- return Either.left(true);
-
}
private Either<Boolean, ResponseFormat> validateServiceCategory(User user, Service service, AuditingActionEnum actionEnum) {
log.debug("validate Service category");
-
- if (service.getCategories() == null || service.getCategories().size() == 0) {
+ if (isEmpty(service.getCategories())) {
ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
componentsUtils.auditComponentAdmin(errorResponse, user, service, actionEnum, ComponentTypeEnum.SERVICE);
return Either.right(errorResponse);
}
-
Either<Boolean, ResponseFormat> validatCategory = validateServiceCategory(service.getCategories());
if (validatCategory.isRight()) {
ResponseFormat responseFormat = validatCategory.right().value();
componentsUtils.auditComponentAdmin(responseFormat, user, service, actionEnum, ComponentTypeEnum.SERVICE);
return Either.right(responseFormat);
}
-
return Either.left(true);
}
public Either<Map<String, Boolean>, ResponseFormat> validateServiceNameExists(String serviceName, String userId) {
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "validate Service Name Exists", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "validate Service Name Exists", false);
Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(serviceName, null, ComponentTypeEnum.SERVICE);
-
// DE242223
titanDao.commit();
@@ -519,9 +482,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
log.debug("validation was successfully performed.");
return Either.left(result);
}
-
ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
-
return Either.right(responseFormat);
}
@@ -542,17 +503,9 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
public Either<Service, ResponseFormat> updateServiceMetadata(String serviceId, Service serviceUpdate, User user) {
- Either<User, ResponseFormat> eitherCreator = validateUser(user, "updateServiceMetadata", serviceUpdate, null, false);
- if (eitherCreator.isRight()) {
- return Either.right(eitherCreator.right().value());
- }
- user = eitherCreator.left().value();
-
+ user = validateUser(user, "updateServiceMetadata", serviceUpdate, null, false);
// validate user role
- Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, serviceUpdate, new ArrayList<>(), null, null);
- if (validateRes.isRight()) {
- return Either.right(validateRes.right().value());
- }
+ validateUserRole(user, serviceUpdate, new ArrayList<>(), null, null);
Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
if (storageStatus.isRight()) {
@@ -595,17 +548,9 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
public Either<Set<String>, ResponseFormat> deleteForwardingPaths(String serviceId, Set<String> pathIdsToDelete, User user, boolean lock) {
Service serviceToDelete = initServiceToDeletePaths(serviceId, pathIdsToDelete);
- Either<User, ResponseFormat> eitherCreator = validateUser(user, "deleteForwardingPaths", serviceToDelete, null, false);
- if (eitherCreator.isRight()) {
- return Either.right(eitherCreator.right().value());
- }
- user = eitherCreator.left().value();
-
+ user = validateUser(user, "deleteForwardingPaths", serviceToDelete, null, false);
// validate user role
- Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, serviceToDelete, new ArrayList<>(), null, null);
- if (validateRes.isRight()) {
- return Either.right(validateRes.right().value());
- }
+ validateUserRole(user, serviceToDelete, new ArrayList<>(), null, null);
Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
if (storageStatus.isRight()) {
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), ""));
@@ -623,12 +568,12 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
try{
result = forwardingPathOperation.deleteForwardingPath(service ,pathIdsToDelete);
if (result.isRight()) {
- log.debug("Failed to lock service {}. Response is {}. ", service.getName(), result.right().value());
+ log.debug(FAILED_TO_LOCK_SERVICE_RESPONSE_IS, service.getName(), result.right().value());
titanDao.rollback();
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE)));
}
titanDao.commit();
- log.debug("The service with system name {} locked. ", service.getSystemName());
+ log.debug(THE_SERVICE_WITH_SYSTEM_NAME_LOCKED, service.getSystemName());
} catch (Exception e){
log.error("Exception occurred during delete forwarding path : {}", e.getMessage(), e);
@@ -669,8 +614,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
private Either<Service, ResponseFormat> createOrUpdateForwardingPath(String serviceId, Service serviceUpdate, User user, boolean isUpdate, String errorContext, boolean lock) {
- Either<Service, ResponseFormat> eitherCreator1 = validateUserAndRole(serviceUpdate, user, errorContext);
- if (eitherCreator1 != null) return eitherCreator1;
+ validateUserAndRole(serviceUpdate, user, errorContext);
Map<String, ForwardingPathDataDefinition> forwardingPaths = serviceUpdate.getForwardingPaths();
@@ -693,9 +637,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
Service storedService = serviceStorageOperationStatusEither.left().value();
- Set<ForwardingPathDataDefinition> forwardingPathDataDefinitions = trimmedForwardingPaths.entrySet().stream().map(entry -> entry.getValue())
- .collect(Collectors.toSet());
-
Either<ForwardingPathDataDefinition, StorageOperationStatus> result;
Either<Component, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade.getLatestByName(ForwardingPathUtils.FORWARDING_PATH_NODE_NAME);
if (forwardingPathOrigin.isRight()) {
@@ -715,11 +656,11 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
lockResult =
lockComponent(storedService.getUniqueId(), storedService, "Add or Update Forwarding Path on Service");
if (lockResult.isRight()) {
- log.debug("Failed to lock service {}. Response is {}. ", storedService.getName(),
+ log.debug(FAILED_TO_LOCK_SERVICE_RESPONSE_IS, storedService.getName(),
lockResult.right().value().getFormattedMessage());
return Either.right(lockResult.right().value());
} else {
- log.debug("The service with system name {} locked. ", storedService.getSystemName());
+ log.debug(THE_SERVICE_WITH_SYSTEM_NAME_LOCKED, storedService.getSystemName());
}
}
Map<String, ForwardingPathDataDefinition> resultMap = new HashMap<>();
@@ -767,175 +708,118 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return service;
}
- private Either<Service, ResponseFormat> validateUserAndRole(Service serviceUpdate, User user, String errorContext) {
- Either<User, ResponseFormat> eitherCreator = validateUser(user, errorContext, serviceUpdate, null, false);
- if (eitherCreator.isRight()) {
- return Either.right(eitherCreator.right().value());
- }
- user = eitherCreator.left().value();
-
- // validate user role
- Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, serviceUpdate, new ArrayList<>(), null, null);
- if (validateRes.isRight()) {
- return Either.right(validateRes.right().value());
- }
- return null;
- }private Either<Service, ResponseFormat> validateAndUpdateServiceMetadata(User user, Service currentService, Service serviceUpdate) {
+ private void validateUserAndRole(Service serviceUpdate, User user, String errorContext) {
+ user = validateUser(user, errorContext, serviceUpdate, null, false);
+ validateUserRole(user, serviceUpdate, new ArrayList<>(), null, null);
- boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentService.getVersion());
- Either<Boolean, ResponseFormat> response = validateAndUpdateCategory(user, currentService, serviceUpdate, hasBeenCertified, null);
- if (response.isRight()) {
- ResponseFormat errorResponse = response.right().value();
- return Either.right(errorResponse);
- }
+ }
- String creatorUserIdUpdated = serviceUpdate.getCreatorUserId();
- String creatorUserIdCurrent = currentService.getCreatorUserId();
- if (creatorUserIdUpdated != null && !creatorUserIdCurrent.equals(creatorUserIdUpdated)) {
- log.info("update srvice: recived request to update creatorUserId to {} the field is not updatable ignoring.", creatorUserIdUpdated);
- }
+ @VisibleForTesting
+ Either<Service, ResponseFormat> validateAndUpdateServiceMetadata(User user, Service currentService, Service serviceUpdate) {
- String creatorFullNameUpdated = serviceUpdate.getCreatorFullName();
- String creatorFullNameCurrent = currentService.getCreatorFullName();
- if (creatorFullNameUpdated != null && !creatorFullNameCurrent.equals(creatorFullNameUpdated)) {
- log.info("update srvice: recived request to update creatorFullName to {} the field is not updatable ignoring.", creatorFullNameUpdated);
- }
+ try {
+ boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentService.getVersion());
+ Either<Boolean, ResponseFormat> response = validateAndUpdateCategory(user, currentService, serviceUpdate, hasBeenCertified, UPDATE_SERVICE_METADATA);
+ if (response.isRight()) {
+ ResponseFormat errorResponse = response.right().value();
+ return Either.right(errorResponse);
+ }
- String lastUpdaterUserIdUpdated = serviceUpdate.getLastUpdaterUserId();
- String lastUpdaterUserIdCurrent = currentService.getLastUpdaterUserId();
- if (lastUpdaterUserIdUpdated != null && !lastUpdaterUserIdCurrent.equals(lastUpdaterUserIdUpdated)) {
- log.info("update srvice: recived request to update lastUpdaterUserId to {} the field is not updatable ignoring.", lastUpdaterUserIdUpdated);
- }
+ verifyValuesAreIdentical(serviceUpdate.getCreatorUserId(), currentService.getCreatorUserId(), "creatorUserId");
+ verifyValuesAreIdentical(serviceUpdate.getCreatorFullName(), currentService.getCreatorFullName(), "creatorFullName");
+ verifyValuesAreIdentical(serviceUpdate.getLastUpdaterUserId(), currentService.getLastUpdaterUserId(), "lastUpdaterUserId");
+ verifyValuesAreIdentical(serviceUpdate.getLastUpdaterFullName(), currentService.getLastUpdaterFullName(), "lastUpdaterFullName");
- String lastUpdaterFullNameUpdated = serviceUpdate.getLastUpdaterFullName();
- String lastUpdaterFullNameCurrent = currentService.getLastUpdaterFullName();
- if (lastUpdaterFullNameUpdated != null && !lastUpdaterFullNameCurrent.equals(lastUpdaterFullNameUpdated)) {
- log.info("update srvice: recived request to update lastUpdaterFullName to {} the field is not updatable ignoring.", lastUpdaterFullNameUpdated);
- }
+ response = validateAndUpdateServiceName(user, currentService, serviceUpdate, hasBeenCertified, null);
+ if (response.isRight()) {
+ return Either.right(response.right().value());
+ }
- response = validateAndUpdateServiceName(user, currentService, serviceUpdate, hasBeenCertified, null);
- if (response.isRight()) {
- ResponseFormat errorResponse = response.right().value();
- return Either.right(errorResponse);
- }
+ verifyValuesAreIdentical(serviceUpdate.getDistributionStatus(), currentService.getDistributionStatus(), "distributionStatus");
- DistributionStatusEnum distributionStatusUpdated = serviceUpdate.getDistributionStatus();
- DistributionStatusEnum distributionStatusCurrent = currentService.getDistributionStatus();
- if (distributionStatusUpdated != null && !distributionStatusUpdated.name().equals(distributionStatusCurrent != null ? distributionStatusCurrent.name() : null)) {
- log.info("update service: received request to update distributionStatus to {}. the field is read only, ignoring.", distributionStatusUpdated);
- }
+ if (serviceUpdate.getProjectCode() != null) {
+ response = validateAndUpdateProjectCode(user, currentService, serviceUpdate, UPDATE_SERVICE_METADATA);
+ if (response.isRight()) {
+ return Either.right(response.right().value());
+ }
+ }
- if (serviceUpdate.getProjectCode() != null) {
- response = validateAndUpdateProjectCode(user, currentService, serviceUpdate, null);
+ response = validateAndUpdateIcon(user, currentService, serviceUpdate, hasBeenCertified, UPDATE_SERVICE_METADATA);
if (response.isRight()) {
- ResponseFormat errorResponse = response.right().value();
- return Either.right(errorResponse);
+ return Either.right(response.right().value());
}
- }
- response = validateAndUpdateIcon(user, currentService, serviceUpdate, hasBeenCertified, null);
- if (response.isRight()) {
- ResponseFormat errorResponse = response.right().value();
- return Either.right(errorResponse);
- }
-
- Long creationDateUpdated = serviceUpdate.getCreationDate();
- Long creationDateCurrent = currentService.getCreationDate();
- if (creationDateUpdated != null && !creationDateCurrent.equals(creationDateUpdated)) {
- log.info("update srvice: recived request to update creationDate to {} the field is not updatable ignoring.", creationDateUpdated);
- }
+ verifyValuesAreIdentical(serviceUpdate.getCreationDate(), currentService.getCreationDate(), "creationDate");
+ verifyValuesAreIdentical(serviceUpdate.getVersion(), currentService.getVersion(), "version");
- String versionUpdated = serviceUpdate.getVersion();
- String versionCurrent = currentService.getVersion();
- if (versionUpdated != null && !versionCurrent.equals(versionUpdated)) {
- log.info("update srvice: recived request to update version to {} the field is not updatable ignoring.", versionUpdated);
- }
+ response = validateAndUpdateDescription(user, currentService, serviceUpdate, UPDATE_SERVICE_METADATA);
+ if (response.isRight()) {
+ return Either.right(response.right().value());
+ }
- response = validateAndUpdateDescription(user, currentService, serviceUpdate, hasBeenCertified, null);
- if (response.isRight()) {
- ResponseFormat errorResponse = response.right().value();
- return Either.right(errorResponse);
- }
+ response = validateAndUpdateTags(user, currentService, serviceUpdate, UPDATE_SERVICE_METADATA);
+ if (response.isRight()) {
+ return Either.right(response.right().value());
+ }
- response = validateAndUpdateTags(user, currentService, serviceUpdate, hasBeenCertified, null);
- if (response.isRight()) {
- ResponseFormat errorResponse = response.right().value();
- return Either.right(errorResponse);
- }
+ response = validateAndUpdateContactId(user, currentService, serviceUpdate, UPDATE_SERVICE_METADATA);
+ if (response.isRight()) {
+ return Either.right(response.right().value());
+ }
- response = validateAndUpdateContactId(user, currentService, serviceUpdate, null);
- if (response.isRight()) {
- ResponseFormat errorResponse = response.right().value();
- return Either.right(errorResponse);
- }
+ verifyValuesAreIdentical(serviceUpdate.getLastUpdateDate(), currentService.getLastUpdateDate(), "lastUpdateDate");
+ verifyValuesAreIdentical(serviceUpdate.getLifecycleState(), currentService.getLifecycleState(), "lifecycleState");
+ verifyValuesAreIdentical(serviceUpdate.isHighestVersion(), currentService.isHighestVersion(), "isHighestVersion");
+ verifyValuesAreIdentical(serviceUpdate.getUUID(), currentService.getUUID(), "uuid");
- Long lastUpdateDateUpdated = serviceUpdate.getLastUpdateDate();
- Long lastUpdateDateCurrent = currentService.getLastUpdateDate();
- if (lastUpdateDateUpdated != null && !lastUpdateDateCurrent.equals(lastUpdateDateUpdated)) {
- log.info("update srvice: recived request to update lastUpdateDate to {} the field is not updatable ignoring.", lastUpdateDateUpdated);
- }
+ validateAndUpdateServiceType(currentService, serviceUpdate);
- LifecycleStateEnum lifecycleStateUpdated = serviceUpdate.getLifecycleState();
- LifecycleStateEnum lifecycleStateCurrent = currentService.getLifecycleState();
- if (lifecycleStateUpdated != null && !lifecycleStateCurrent.name().equals(lifecycleStateUpdated.name())) {
- log.info("update srvice: recived request to update lifecycleState to {} the field is not updatable ignoring.", lifecycleStateUpdated);
- }
+ response = validateAndUpdateServiceRole(user, currentService, serviceUpdate, UPDATE_SERVICE_METADATA);
+ if (response.isRight()) {
+ return Either.right(response.right().value());
+ }
- Boolean isHighestVersionUpdated = serviceUpdate.isHighestVersion();
- Boolean isHighestVersionCurrent = currentService.isHighestVersion();
- if (isHighestVersionUpdated != null && !isHighestVersionCurrent.equals(isHighestVersionUpdated)) {
- log.info("update srvice: recived request to update isHighestVersion to {} the field is not updatable ignoring.", isHighestVersionUpdated);
- }
+ response = validateAndUpdateInstantiationTypeValue(user, currentService, serviceUpdate, UPDATE_SERVICE_METADATA);
+ if (response.isRight()) {
+ return Either.right(response.right().value());
+ }
- String uuidUpdated = serviceUpdate.getUUID();
- String uuidCurrent = currentService.getUUID();
- if (!uuidCurrent.equals(uuidUpdated)) {
- log.info("update service: recived request to update uuid to {} the field is not updatable ignoring.", uuidUpdated);
- }
+ verifyValuesAreIdentical(serviceUpdate.getInvariantUUID(), currentService.getInvariantUUID(), "invariantUUID");
- response = validateAndUpdateServiceType(user, currentService, serviceUpdate, null);
- if (response.isRight()) {
- ResponseFormat errorResponse = response.right().value();
- return Either.right(errorResponse);
- }
+ validateAndUpdateEcompNaming(currentService, serviceUpdate);
- response = validateAndUpdateServiceRole(user, currentService, serviceUpdate, null);
- if (response.isRight()) {
- ResponseFormat errorResponse = response.right().value();
- return Either.right(errorResponse);
- }
+ currentService.setEnvironmentContext(serviceUpdate.getEnvironmentContext());
- String currentInvariantUuid = currentService.getInvariantUUID();
- String updatedInvariantUuid = serviceUpdate.getInvariantUUID();
+ return Either.left(currentService);
- if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
- log.warn("Product invariant UUID is automatically set and cannot be updated");
- serviceUpdate.setInvariantUUID(currentInvariantUuid);
+ } catch (ComponentException exception) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(exception);
+ componentsUtils.auditComponentAdmin(responseFormat, user, serviceUpdate,
+ AuditingActionEnum.UPDATE_SERVICE_METADATA, ComponentTypeEnum.SERVICE);
+ return Either.right(responseFormat);
}
- validateAndUpdateEcompNaming(currentService, serviceUpdate);
-
- currentService.setEnvironmentContext(serviceUpdate.getEnvironmentContext());
-
- return Either.left(currentService);
+ }
+ private void verifyValuesAreIdentical(Object updatedValue, Object originalValue, String fieldName) {
+ if (updatedValue != null && !updatedValue.equals(originalValue)) {
+ log.info("update service: received request to update {} to {} the field is not updatable ignoring.", fieldName, updatedValue);
+ }
}
private void validateAndUpdateEcompNaming(Service currentService, Service serviceUpdate) {
- Boolean isEcompoGeneratedCurr = currentService.isEcompGeneratedNaming();
- Boolean isEcompoGeneratedUpdate = serviceUpdate.isEcompGeneratedNaming();
- if (isEcompoGeneratedUpdate != null && isEcompoGeneratedCurr.equals(isEcompoGeneratedUpdate)) {
- currentService.setEcompGeneratedNaming(isEcompoGeneratedUpdate);
- }
- String namingPolicyUpd = serviceUpdate.getNamingPolicy();
- if (!currentService.isEcompGeneratedNaming()) {
- if (ValidationUtils.validateStringNotEmpty(namingPolicyUpd)) {
+ Boolean isEcompGeneratedCurr = currentService.isEcompGeneratedNaming();
+ Boolean isEcompGeneratedUpdate = serviceUpdate.isEcompGeneratedNaming();
+ if (isEcompGeneratedUpdate != null && !isEcompGeneratedUpdate.equals(isEcompGeneratedCurr)) {
+ currentService.setEcompGeneratedNaming(isEcompGeneratedUpdate);
+ }
+ String namingPolicyUpdate = serviceUpdate.getNamingPolicy();
+ if (currentService.isEcompGeneratedNaming()) {
+ currentService.setNamingPolicy(namingPolicyUpdate);
+ } else {
+ if (!StringUtils.isEmpty(namingPolicyUpdate)) {
log.warn("NamingPolicy must be empty for EcompGeneratedNaming=false");
- currentService.setNamingPolicy("");
- } else {
- currentService.setNamingPolicy(namingPolicyUpd);
}
- }else{
- currentService.setNamingPolicy(namingPolicyUpd);
+ currentService.setNamingPolicy("");
}
}
@@ -943,17 +827,13 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
String contactIdUpdated = serviceUpdate.getContactId();
String contactIdCurrent = currentService.getContactId();
if (!contactIdCurrent.equals(contactIdUpdated)) {
- Either<Boolean, ResponseFormat> validatContactId = validateContactId(user, serviceUpdate, audatingAction);
- if (validatContactId.isRight()) {
- ResponseFormat errorRespons = validatContactId.right().value();
- return Either.right(errorRespons);
- }
+ validateContactId(user, serviceUpdate, audatingAction);
currentService.setContactId(contactIdUpdated.toLowerCase());
}
return Either.left(true);
}
- private Either<Boolean, ResponseFormat> validateAndUpdateTags(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) {
+ private Either<Boolean, ResponseFormat> validateAndUpdateTags(User user, Service currentService, Service serviceUpdate, AuditingActionEnum audatingAction) {
List<String> tagsUpdated = serviceUpdate.getTags();
List<String> tagsCurrent = currentService.getTags();
if (tagsUpdated == null || tagsUpdated.isEmpty()) {
@@ -963,25 +843,17 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
if (!(tagsCurrent.containsAll(tagsUpdated) && tagsUpdated.containsAll(tagsCurrent))) {
- Either<Boolean, ResponseFormat> validatResponse = validateTagsListAndRemoveDuplicates(user, serviceUpdate, audatingAction);
- if (validatResponse.isRight()) {
- ResponseFormat errorRespons = validatResponse.right().value();
- return Either.right(errorRespons);
- }
+ validateTagsListAndRemoveDuplicates(user, serviceUpdate, audatingAction);
currentService.setTags(tagsUpdated);
}
return Either.left(true);
}
- private Either<Boolean, ResponseFormat> validateAndUpdateDescription(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) {
+ private Either<Boolean, ResponseFormat> validateAndUpdateDescription(User user, Service currentService, Service serviceUpdate, AuditingActionEnum audatingAction) {
String descriptionUpdated = serviceUpdate.getDescription();
String descriptionCurrent = currentService.getDescription();
if (!descriptionCurrent.equals(descriptionUpdated)) {
- Either<Boolean, ResponseFormat> validateDescriptionResponse = validateDescriptionAndCleanup(user, serviceUpdate, audatingAction);
- if (validateDescriptionResponse.isRight()) {
- ResponseFormat errorRespons = validateDescriptionResponse.right().value();
- return Either.right(errorRespons);
- }
+ validateDescriptionAndCleanup(user, serviceUpdate, audatingAction);
currentService.setDescription(serviceUpdate.getDescription());
}
return Either.left(true);
@@ -1008,11 +880,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
String iconCurrent = currentService.getIcon();
if (!iconCurrent.equals(iconUpdated)) {
if (!hasBeenCertified) {
- Either<Boolean, ResponseFormat> validatIconResponse = validateIcon(user, serviceUpdate, audatingAction);
- if (validatIconResponse.isRight()) {
- ResponseFormat errorRespons = validatIconResponse.right().value();
- return Either.right(errorRespons);
- }
+ validateIcon(user, serviceUpdate, audatingAction);
currentService.setIcon(iconUpdated);
} else {
log.info("icon {} cannot be updated once the service has been certified once.", iconUpdated);
@@ -1028,12 +896,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
String serviceNameCurrent = currentService.getName();
if (!serviceNameCurrent.equals(serviceNameUpdated)) {
if (!hasBeenCertified) {
- Either<Boolean, ResponseFormat> validatServiceNameResponse = validateComponentName(user, serviceUpdate, auditingAction);
- if (validatServiceNameResponse.isRight()) {
- ResponseFormat errorRespons = validatServiceNameResponse.right().value();
- return Either.right(errorRespons);
- }
-
+ validateComponentName(user, serviceUpdate, auditingAction);
Either<Boolean, ResponseFormat> serviceNameUniquenessValidation = validateComponentNameUnique(user, serviceUpdate, auditingAction);
if (serviceNameUniquenessValidation.isRight()) {
return serviceNameUniquenessValidation;
@@ -1051,54 +914,38 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return Either.left(true);
}
- private Either<Boolean, ResponseFormat> validateAndUpdateServiceType(User user, Service currentService, Service updatedService, AuditingActionEnum auditingAction) {
+ private void validateAndUpdateServiceType(Service currentService, Service updatedService) {
String updatedServiceType = updatedService.getServiceType();
String currentServiceType = currentService.getServiceType();
if (!currentServiceType.equals(updatedServiceType)) {
- Either<Boolean, ResponseFormat> validateServiceType = validateServiceTypeAndCleanup(user, updatedService , auditingAction);
- if (validateServiceType.isRight()) {
- ResponseFormat errorResponse = validateServiceType.right().value();
- componentsUtils.auditComponentAdmin(errorResponse, user, updatedService, auditingAction, ComponentTypeEnum.SERVICE);
- return Either.right(errorResponse);
- }
+ validateServiceTypeAndCleanup(updatedService);
currentService.setServiceType(updatedServiceType);
}
- return Either.left(true);
}
- protected Either<Boolean, ResponseFormat> validateServiceTypeAndCleanup(User user, Component component, AuditingActionEnum actionEnum) {
+ private void validateServiceTypeAndCleanup(Component component) {
+ log.debug("validate service type");
String serviceType = ((Service)component).getServiceType();
- if (serviceType != null){
- serviceType = cleanUpText(serviceType);
- Either<Boolean, ResponseFormat> validateServiceType = validateServiceType(serviceType);
- if (validateServiceType.isRight()) {
- ResponseFormat responseFormat = validateServiceType.right().value();
- componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, ComponentTypeEnum.SERVICE);
- return Either.right(responseFormat);
- }
- return Either.left(true);
- } else {
- return Either.left(false);
+ if (serviceType == null) {
+ log.info("service type is not valid.");
+ throw new ComponentException(ActionStatus.INVALID_SERVICE_TYPE);
}
+ serviceType = cleanUpText(serviceType);
+ validateServiceType(serviceType);
}
- private Either<Boolean, ResponseFormat> validateServiceType(String serviceType) {
- if (serviceType.equals("")){
- return Either.left(true);
- } else {
- if (!ValidationUtils.validateServiceTypeLength(serviceType)) {
- log.info("service type exceeds limit.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_TYPE_EXCEEDS_LIMIT, "" + ValidationUtils.SERVICE_TYPE_MAX_LENGTH);
- return Either.right(errorResponse);
- }
-
- if (!ValidationUtils.validateIsEnglish(serviceType)) {
- log.info("service type is not valid.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_TYPE);
- return Either.right(errorResponse);
- }
- return Either.left(true);
+ private void validateServiceType(String serviceType) {
+ if (serviceType.isEmpty()) {
+ return;
+ }
+ if (!ValidationUtils.validateServiceTypeLength(serviceType)) {
+ log.info("service type exceeds limit.");
+ throw new ComponentException(ActionStatus.SERVICE_TYPE_EXCEEDS_LIMIT, "" + ValidationUtils.SERVICE_TYPE_MAX_LENGTH);
+ }
+ if (!ValidationUtils.validateIsEnglish(serviceType)) {
+ log.info("service type is not valid.");
+ throw new ComponentException(ActionStatus.INVALID_SERVICE_TYPE);
}
}
@@ -1118,6 +965,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
protected Either<Boolean, ResponseFormat> validateServiceRoleAndCleanup(User user, Component component, AuditingActionEnum actionEnum) {
+ log.debug("validate service role");
String serviceRole = ((Service)component).getServiceRole();
if (serviceRole != null){
serviceRole = cleanUpText(serviceRole);
@@ -1134,7 +982,33 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
}
+ private Either<Boolean, ResponseFormat> validateAndUpdateInstantiationTypeValue(User user, Service currentService, Service updatedService, AuditingActionEnum auditingAction) {
+ String updatedInstaType= updatedService.getInstantiationType();
+ String currentInstaType = currentService.getInstantiationType();
+ if (!currentInstaType.equals(updatedInstaType)) {
+ Either<Boolean, ResponseFormat> validateInstantiationType = validateInstantiationTypeValue(user, updatedService , auditingAction);
+ if (validateInstantiationType.isRight()) {
+ ResponseFormat errorResponse = validateInstantiationType.right().value();
+ componentsUtils.auditComponentAdmin(errorResponse, user, updatedService, auditingAction, ComponentTypeEnum.SERVICE);
+ return Either.right(errorResponse);
+ }
+ currentService.setInstantiationType(updatedInstaType);
+ }
+ return Either.left(true);
+ }
+ private Either<Boolean, ResponseFormat> validateInstantiationTypeValue(User user, Service service, AuditingActionEnum actionEnum) {
+ log.debug("validate instantiation type");
+ String instantiationType = service.getInstantiationType();
+ if (!InstantiationTypes.containsName(instantiationType) || instantiationType == null){
+ log.error("Recieved Instantiation type {} is not valid.", instantiationType);
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_INSTANTIATION_TYPE);
+ componentsUtils.auditComponentAdmin(errorResponse, user, service, actionEnum, ComponentTypeEnum.SERVICE);
+ return Either.right(errorResponse);
+ }
+ return Either.left(true);
+ }
+
private Either<Boolean, ResponseFormat> validateServiceRole(String serviceRole) {
if (serviceRole.equals("")){
return Either.left(true);
@@ -1154,15 +1028,12 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
}
-
-
private Either<Boolean, ResponseFormat> validateAndUpdateCategory(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) {
List<CategoryDefinition> categoryUpdated = serviceUpdate.getCategories();
List<CategoryDefinition> categoryCurrent = currentService.getCategories();
- Either<Boolean, ResponseFormat> validatCategoryResponse = validateServiceCategory(user, serviceUpdate, audatingAction);
- if (validatCategoryResponse.isRight()) {
- ResponseFormat errorRespons = validatCategoryResponse.right().value();
- return Either.right(errorRespons);
+ Either<Boolean, ResponseFormat> validateCategoryResponse = validateServiceCategory(user, serviceUpdate, audatingAction);
+ if (validateCategoryResponse.isRight()) {
+ return Either.right(validateCategoryResponse.right().value());
}
if (!categoryCurrent.get(0).getName().equals(categoryUpdated.get(0).getName())) {
if (!hasBeenCertified) {
@@ -1177,7 +1048,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
- public Either<Boolean, ResponseFormat> validateServiceCategory(List<CategoryDefinition> list) {
+ private Either<Boolean, ResponseFormat> validateServiceCategory(List<CategoryDefinition> list) {
if (list != null) {
if (list.size() > 1) {
log.debug("Must be only one category for service");
@@ -1224,16 +1095,13 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return Either.left(serviceRelations);
- }public ResponseFormat deleteService(String serviceId, User user) {
+ }
+
+ public ResponseFormat deleteService(String serviceId, User user) {
ResponseFormat responseFormat;
String ecompErrorContext = "delete service";
- Either<User, ResponseFormat> eitherCreator = validateUserExists(user, ecompErrorContext, false);
- if (eitherCreator.isRight()) {
- return eitherCreator.right().value();
- }
- user = eitherCreator.left().value();
-
+ validateUserExists(user, ecompErrorContext, false);
Either<Service, StorageOperationStatus> serviceStatus = toscaOperationFacade.getToscaElement(serviceId);
if (serviceStatus.isRight()) {
log.debug("failed to get service {}", serviceId);
@@ -1245,12 +1113,9 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
StorageOperationStatus result = StorageOperationStatus.OK;
Either<Boolean, ResponseFormat> lockResult = lockComponent(service, "Mark service to delete");
if (lockResult.isRight()) {
- result = StorageOperationStatus.GENERAL_ERROR;
- return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ return lockResult.right().value();
}
-
try {
-
result = markComponentToDelete(service);
if (result.equals(StorageOperationStatus.OK)) {
responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
@@ -1259,7 +1124,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, service.getName());
}
return responseFormat;
-
} finally {
if (result == null || !result.equals(StorageOperationStatus.OK)) {
log.warn("operation failed. do rollback");
@@ -1276,16 +1140,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
public ResponseFormat deleteServiceByNameAndVersion(String serviceName, String version, User user) {
ResponseFormat responseFormat;
String ecompErrorContext = "delete service";
- Either<User, ResponseFormat> validateEmptyResult = validateUserNotEmpty(user, ecompErrorContext);
- if (validateEmptyResult.isRight()) {
- return validateEmptyResult.right().value();
- }
-
- Either<User, ResponseFormat> eitherCreator = validateUserExists(user, ecompErrorContext, false);
- if (eitherCreator.isRight()) {
- return eitherCreator.right().value();
- }
- user = eitherCreator.left().value();
+ validateUserNotEmpty(user, ecompErrorContext);
+ user = validateUserExists(user, ecompErrorContext, false);
Either<Service, ResponseFormat> getResult = getServiceByNameAndVersion(serviceName, version, user.getUserId());
if (getResult.isRight()) {
@@ -1325,15 +1181,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
public Either<Service, ResponseFormat> getService(String serviceId, User user) {
String ecompErrorContext = "Get service";
- Either<User, ResponseFormat> validateEmptyResult = validateUserNotEmpty(user, ecompErrorContext);
- if (validateEmptyResult.isRight()) {
- return Either.right(validateEmptyResult.right().value());
- }
-
- Either<User, ResponseFormat> eitherCreator = validateUserExists(user, ecompErrorContext, false);
- if (eitherCreator.isRight()) {
- return Either.right(eitherCreator.right().value());
- }
+ validateUserNotEmpty(user, ecompErrorContext);
+ validateUserExists(user, ecompErrorContext, false);
Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
if (storageStatus.isRight()) {
@@ -1353,10 +1202,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
public Either<Service, ResponseFormat> getServiceByNameAndVersion(String serviceName, String serviceVersion, String userId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Service By Name And Version", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "get Service By Name And Version", false);
Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.SERVICE, serviceName, serviceVersion);
if (storageStatus.isRight()) {
log.debug("failed to get service by name {} and version {}", serviceName, serviceVersion);
@@ -1375,7 +1221,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
String serviceUniqueId = service.getUniqueId();
Map<String, ArtifactDefinition> artifactMap = service.getArtifacts();
if (artifactMap == null)
- artifactMap = new HashMap<String, ArtifactDefinition>();
+ artifactMap = new HashMap<>();
Map<String, Object> informationalServiceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getInformationalServiceArtifacts();
List<String> exludeServiceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeServiceCategory();
@@ -1416,12 +1262,12 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return artifactInfo;
}
- private Either<DistributionTransitionEnum, ResponseFormat> validateTransitionEnum(String distributionTransition, User user) {
+ private Either<DistributionTransitionEnum, ResponseFormat> validateTransitionEnum(String distributionTransition) {
DistributionTransitionEnum transitionEnum = null;
transitionEnum = DistributionTransitionEnum.getFromDisplayName(distributionTransition);
if (transitionEnum == null) {
- BeEcompErrorManager.getInstance().logBeSystemError("Change Service Distribution");
+ BeEcompErrorManager.getInstance().logBeSystemError(CHANGE_SERVICE_DISTRIBUTION);
log.info("state operation is not valid. operations allowed are: {}", DistributionTransitionEnum.valuesAsString());
ResponseFormat error = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
return Either.right(error);
@@ -1430,11 +1276,11 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return Either.left(transitionEnum);
}
- private Either<String, ResponseFormat> validateComment(LifecycleChangeInfoWithAction comment, User user, AuditingActionEnum auditAction) {
+ private Either<String, ResponseFormat> validateComment(LifecycleChangeInfoWithAction comment) {
String data = comment.getUserRemarks();
if (data == null || data.trim().isEmpty()) {
- BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Change Service Distribution");
+ BeEcompErrorManager.getInstance().logBeInvalidJsonInput(CHANGE_SERVICE_DISTRIBUTION);
log.debug("user comment cannot be empty or null.");
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
@@ -1444,7 +1290,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
data = ValidationUtils.stripOctets(data);
if (!ValidationUtils.validateLength(data, ValidationUtils.COMMENT_MAX_LENGTH)) {
- BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Change Service Distribution");
+ BeEcompErrorManager.getInstance().logBeInvalidJsonInput(CHANGE_SERVICE_DISTRIBUTION);
log.debug("user comment exceeds limit.");
return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, "comment", String.valueOf(ValidationUtils.COMMENT_MAX_LENGTH)));
}
@@ -1458,8 +1304,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
if (storageStatus.isRight()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceId);
- log.debug("audit before sending response");
- componentsUtils.auditComponent(responseFormat, user, auditAction, serviceId, ComponentTypeEnum.SERVICE, comment);
+ log.debug(AUDIT_BEFORE_SENDING_RESPONSE);
+ componentsUtils.auditComponent(responseFormat, user, auditAction, new ResourceCommonInfo(serviceId, ComponentTypeEnum.SERVICE.getValue()), comment);
return Either.right(responseFormat);
}
Service service = storageStatus.left().value();
@@ -1477,28 +1323,24 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
log.debug("get user from DB");
// get user details
- Either<User, ResponseFormat> eitherCreator = validateUser(user, "Activate Distribution", service, auditAction, false);
- if (eitherCreator.isRight()) {
- return Either.right(eitherCreator.right().value());
- }
- user = eitherCreator.left().value();
-
+ user = validateUser(user, "Activate Distribution", service, auditAction, false);
// validate user role
List<Role> roles = new ArrayList<>();
roles.add(Role.ADMIN);
roles.add(Role.GOVERNOR);
roles.add(Role.OPS);
- Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, service, roles, auditAction, comment);
- if (validateRes.isRight()) {
- return Either.right(validateRes.right().value());
- }
+ validateUserRole(user, service, roles, auditAction, comment);
return Either.left(user);
}
private void createAudit(User user, AuditingActionEnum auditAction, String comment, Service component, ResponseFormat responseFormat) {
- log.debug("audit before sending response");
- componentsUtils.auditComponent(responseFormat, user, component, auditAction, ComponentTypeEnum.SERVICE,
- ResourceAuditData.newBuilder().state(component.getLifecycleState().name()).version(component.getVersion()).build(), comment);
+ log.debug(AUDIT_BEFORE_SENDING_RESPONSE);
+ componentsUtils.auditComponent(responseFormat, user, component, auditAction, new ResourceCommonInfo(ComponentTypeEnum.SERVICE.getValue()),
+ ResourceVersionInfo.newBuilder()
+ .state(component.getLifecycleState().name())
+ .version(component.getVersion())
+ .build(),
+ comment);
}
private String getEnvNameFromConfiguration() {
@@ -1517,24 +1359,16 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
ActivationRequestInformation activationRequestInformation = activationRequestInformationEither.left().value();
Either<String, ResponseFormat> result = null;
- ResponseFormat response = null;
String did = ThreadLocalsHolder.getUuid();
Service service = activationRequestInformation.getServiceToActivate();
-
- StorageOperationStatus readyForDistribution = distributionEngine.verifyServiceHasDeploymentArtifacts(service);
- if (readyForDistribution.equals(StorageOperationStatus.OK)) {
- result = buildAndSendServiceNotification(service, envId, did, activationRequestInformation.getWorkloadContext(), modifier);
- } else {
- response = componentsUtils.getResponseFormatByDE(componentsUtils.convertFromStorageResponse(readyForDistribution), service.getName(), envId);
- result = Either.right(response);
- }
+ result = buildAndSendServiceNotification(service, envId, did, activationRequestInformation.getWorkloadContext(), modifier);
return result;
}
public Either<String, ResponseFormat> buildAndSendServiceNotification(Service service, String envId, String did, String workloadContext, User modifier) {
String envName = getEnvNameFromConfiguration();
INotificationData notificationData = distributionEngine.buildServiceForDistribution(service, did, workloadContext);
- ActionStatus notifyServiceResponse = distributionEngine.notifyService(did, service, notificationData, envId, envName, modifier.getUserId(), modifier.getFullName());
+ ActionStatus notifyServiceResponse = distributionEngine.notifyService(did, service, notificationData, envId, envName, modifier);
if (notifyServiceResponse == ActionStatus.OK) {
return Either.left(did);
} else {
@@ -1547,20 +1381,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
public Either<Service, ResponseFormat> activateDistribution(String serviceId, String envName, User modifier, HttpServletRequest request) {
- Either<User, ResponseFormat> eitherCreator = validateUserExists(modifier.getUserId(), "activate Distribution", false);
- if (eitherCreator.isRight()) {
- return Either.right(eitherCreator.right().value());
- }
-
- User user = eitherCreator.left().value();
-
+ User user = validateUserExists(modifier.getUserId(), "activate Distribution", false);
Either<Service, ResponseFormat> result = null;
ResponseFormat response = null;
Service updatedService = null;
String did = ThreadLocalsHolder.getUuid();
// DE194021
String configuredEnvName = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getEnvironments().get(0);
- if (configuredEnvName != null && false == envName.equals(configuredEnvName)) {
+ if (configuredEnvName != null && !configuredEnvName.equals(envName)) {
log.trace("Update environment name to be {} instead of {}", configuredEnvName, envName);
envName = configuredEnvName;
}
@@ -1579,17 +1407,20 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
if (serviceRes.isRight()) {
log.debug("failed retrieving service");
response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceRes.right().value(), ComponentTypeEnum.SERVICE), serviceId);
- componentsUtils.auditComponent(response, user, null, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST, ComponentTypeEnum.SERVICE,
- ResourceAuditData.newBuilder().build(), did);
+ componentsUtils.auditComponent(response, user, null, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST,
+ new ResourceCommonInfo(ComponentTypeEnum.SERVICE.getValue()),
+ ResourceVersionInfo.newBuilder()
+ .build(),
+ did);
return Either.right(response);
}
Service service = serviceRes.left().value();
String dcurrStatus = service.getDistributionStatus().name();
String updatedStatus = dcurrStatus;
- StorageOperationStatus readyForDistribution = distributionEngine.isReadyForDistribution(service, envName);
+ StorageOperationStatus readyForDistribution = distributionEngine.isReadyForDistribution(envName);
if (readyForDistribution.equals(StorageOperationStatus.OK)) {
INotificationData notificationData = distributionEngine.buildServiceForDistribution(service, did, null);
- ActionStatus notifyServiceResponse = distributionEngine.notifyService(did, service, notificationData, envName, user.getUserId(), user.getFullName());
+ ActionStatus notifyServiceResponse = distributionEngine.notifyService(did, service, notificationData, envName, user);
if (notifyServiceResponse == ActionStatus.OK) {
Either<Service, ResponseFormat> updateStateRes = updateDistributionStatusForActivation(service, user, DistributionStatusEnum.DISTRIBUTED);
if (updateStateRes.isLeft() && updateStateRes.left().value() != null) {
@@ -1609,12 +1440,17 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
result = Either.right(response);
}
} else {
- response = componentsUtils.getResponseFormatByDE(componentsUtils.convertFromStorageResponse(readyForDistribution), service.getName(), envName);
+ response = componentsUtils.getResponseFormatByDE(componentsUtils.convertFromStorageResponse(readyForDistribution), envName);
result = Either.right(response);
}
- componentsUtils.auditComponent(response, user, service, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST, ComponentTypeEnum.SERVICE,
- ResourceAuditData.newBuilder().distributionStatus(dcurrStatus).build(),
- ResourceAuditData.newBuilder().distributionStatus(updatedStatus).build(), service.getName(),
+ componentsUtils.auditComponent(response, user, service, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST,
+ new ResourceCommonInfo(service.getName(),ComponentTypeEnum.SERVICE.getValue()),
+ ResourceVersionInfo.newBuilder()
+ .distributionStatus(dcurrStatus)
+ .build(),
+ ResourceVersionInfo.newBuilder()
+ .distributionStatus(updatedStatus)
+ .build(),
null, null, did);
return result;
}
@@ -1622,10 +1458,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
// convert to private after deletion of temp url
public Either<Service, ResponseFormat> updateDistributionStatusForActivation(Service service, User user, DistributionStatusEnum state) {
- Either<User, ResponseFormat> resp = validateUserExists(user.getUserId(), "update Distribution Status For Activation", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(user.getUserId(), "update Distribution Status For Activation", false);
String serviceId = service.getUniqueId();
Either<Boolean, ResponseFormat> lockResult = lockComponent(serviceId, service, "updateDistributionStatusForActivation");
@@ -1649,11 +1482,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
public Either<Service, ResponseFormat> markDistributionAsDeployed(String serviceId, String did, User user) {
- Either<User, ResponseFormat> resp = validateUserExists(user.getUserId(), "mark Distribution As Deployed", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
+ validateUserExists(user.getUserId(), "mark Distribution As Deployed", false);
log.debug("mark distribution deployed");
AuditingActionEnum auditAction = AuditingActionEnum.DISTRIBUTION_DEPLOY;
@@ -1667,13 +1496,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
Service service = getServiceResponse.left().value();
-
- Either<User, ResponseFormat> validateRoleForDeploy = validateRoleForDeploy(did, user, auditAction, service);
- if (validateRoleForDeploy.isRight()) {
- return Either.right(validateRoleForDeploy.right().value());
- }
- user = validateRoleForDeploy.left().value();
-
+ user = validateRoleForDeploy(did, user, auditAction, service);
return checkDistributionAndDeploy(did, user, auditAction, service);
}
@@ -1688,7 +1511,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
private List<ArtifactGenerator<ArtifactDefinition>> buildArtifactGenList(Service service, User modifier, boolean shouldLock, boolean inTransaction, ComponentInstance ri) {
- List<ArtifactGenerator<ArtifactDefinition>> asList = new ArrayList<ArtifactGenerator<ArtifactDefinition>>();
+ List<ArtifactGenerator<ArtifactDefinition>> asList = new ArrayList<>();
if (ri.getOriginType() == OriginTypeEnum.VF) {
asList = Arrays.asList(new VfModuleArtifacGenerator(modifier, ri, service, shouldLock, inTransaction));
@@ -1696,15 +1519,15 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return asList;
}
- private List<GroupInstance> collectGroupsInstanceForCompInstance(ComponentInstance currVF, Wrapper<ResponseFormat> responseWrapper) {
+ private List<GroupInstance> collectGroupsInstanceForCompInstance(ComponentInstance currVF) {
Map<String, ArtifactDefinition> deploymentArtifacts = currVF.getDeploymentArtifacts();
if(currVF.getGroupInstances() != null){
- currVF.getGroupInstances().stream().forEach(gi -> gi.alignArtifactsUuid(deploymentArtifacts));
+ currVF.getGroupInstances().forEach(gi -> gi.alignArtifactsUuid(deploymentArtifacts));
}
return currVF.getGroupInstances();
}
- private ArtifactDefinition getVfModuleInstArtifactForCompInstance(ComponentInstance currVF, Service service, User modifier, List<GroupInstance> groupsForCurrVF, Wrapper<String> payloadWrapper, Wrapper<ResponseFormat> responseWrapper) {
+ private ArtifactDefinition getVfModuleInstArtifactForCompInstance(ComponentInstance currVF, Service service, Wrapper<String> payloadWrapper, Wrapper<ResponseFormat> responseWrapper) {
ArtifactDefinition vfModuleAertifact = null;
if (MapUtils.isNotEmpty(currVF.getDeploymentArtifacts())) {
Optional<ArtifactDefinition> optionalVfModuleArtifact = currVF.getDeploymentArtifacts().values().stream().filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.VF_MODULES_METADATA.name())).findAny();
@@ -1713,7 +1536,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
}
if (vfModuleAertifact == null) {
- Either<ArtifactDefinition, ResponseFormat> createVfModuleArtifact = createVfModuleArtifact(modifier, currVF, service, payloadWrapper.getInnerElement());
+ Either<ArtifactDefinition, ResponseFormat> createVfModuleArtifact = createVfModuleArtifact(currVF, service, payloadWrapper.getInnerElement());
if (createVfModuleArtifact.isLeft()) {
vfModuleAertifact = createVfModuleArtifact.left().value();
} else {
@@ -1724,43 +1547,40 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
private void fillVfModuleInstHeatEnvPayload(List<GroupInstance> groupsForCurrVF, Wrapper<String> payloadWrapper) {
- // Converts GroupDefinition to VfModuleArtifactPayload which is the
- // format used in the payload
-
- List<VfModuleArtifactPayload> vfModulePayloadForCurrVF = new ArrayList<VfModuleArtifactPayload>();
+ List<VfModuleArtifactPayload> vfModulePayloads = new ArrayList<>();
if (groupsForCurrVF != null) {
for (GroupInstance groupInstance : groupsForCurrVF) {
VfModuleArtifactPayload modulePayload = new VfModuleArtifactPayload(groupInstance);
- vfModulePayloadForCurrVF.add(modulePayload);
+ vfModulePayloads.add(modulePayload);
}
- Collections.sort(vfModulePayloadForCurrVF, (art1, art2) -> VfModuleArtifactPayload.compareByGroupName(art1, art2));
+ vfModulePayloads.sort(VfModuleArtifactPayload::compareByGroupName);
final Gson gson = new GsonBuilder().setPrettyPrinting().create();
- String vfModulePayloadString = gson.toJson(vfModulePayloadForCurrVF);
+ String vfModulePayloadString = gson.toJson(vfModulePayloads);
payloadWrapper.setInnerElement(vfModulePayloadString);
}
}
private Either<ArtifactDefinition, ResponseFormat> generateVfModuleInstanceArtifact(User modifier, ComponentInstance currVFInstance, Service service, boolean shouldLock, boolean inTransaction) {
- ArtifactDefinition vfModuleAertifact = null;
+ ArtifactDefinition vfModuleArtifact = null;
Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
Wrapper<String> payloadWrapper = new Wrapper<>();
- List<GroupInstance> groupsForCurrVF = collectGroupsInstanceForCompInstance(currVFInstance, responseWrapper);
+ List<GroupInstance> groupsForCurrVF = collectGroupsInstanceForCompInstance(currVFInstance);
if (responseWrapper.isEmpty()) {
fillVfModuleInstHeatEnvPayload(groupsForCurrVF, payloadWrapper);
}
if (responseWrapper.isEmpty() && payloadWrapper.getInnerElement() != null) {
- vfModuleAertifact = getVfModuleInstArtifactForCompInstance(currVFInstance, service, modifier, groupsForCurrVF, payloadWrapper, responseWrapper);
+ vfModuleArtifact = getVfModuleInstArtifactForCompInstance(currVFInstance, service, payloadWrapper, responseWrapper);
}
- if (responseWrapper.isEmpty() && vfModuleAertifact != null) {
- vfModuleAertifact = fillVfModulePayload(modifier, currVFInstance, vfModuleAertifact, shouldLock, inTransaction, payloadWrapper, responseWrapper, service);
+ if (responseWrapper.isEmpty() && vfModuleArtifact != null) {
+ vfModuleArtifact = fillVfModulePayload(modifier, currVFInstance, vfModuleArtifact, shouldLock, inTransaction, payloadWrapper, responseWrapper, service);
}
Either<ArtifactDefinition, ResponseFormat> result;
if (responseWrapper.isEmpty()) {
- result = Either.left(vfModuleAertifact);
+ result = Either.left(vfModuleArtifact);
} else {
result = Either.right(responseWrapper.getInnerElement());
}
@@ -1770,7 +1590,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
private ArtifactDefinition fillVfModulePayload(User modifier, ComponentInstance currVF, ArtifactDefinition vfModuleArtifact, boolean shouldLock, boolean inTransaction, Wrapper<String> payloadWrapper, Wrapper<ResponseFormat> responseWrapper, Service service) {
ArtifactDefinition result = null;
- Either<ArtifactDefinition, ResponseFormat> eitherPayload = artifactsBusinessLogic.generateArtifactPayload(vfModuleArtifact, ComponentTypeEnum.RESOURCE_INSTANCE, service, currVF.getName(), modifier, shouldLock, inTransaction, () -> System.currentTimeMillis(),
+ Either<ArtifactDefinition, ResponseFormat> eitherPayload = artifactsBusinessLogic.generateArtifactPayload(vfModuleArtifact, ComponentTypeEnum.RESOURCE_INSTANCE, service, currVF.getName(), modifier, shouldLock, inTransaction, System::currentTimeMillis,
() -> Either.left(artifactsBusinessLogic.createEsArtifactData(vfModuleArtifact, payloadWrapper.getInnerElement().getBytes(StandardCharsets.UTF_8))), currVF.getUniqueId());
if (eitherPayload.isLeft()) {
result = eitherPayload.left().value();
@@ -1784,7 +1604,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return result;
}
- private Either<ArtifactDefinition, ResponseFormat> createVfModuleArtifact(User modifier, ComponentInstance currVF, Service service, String vfModulePayloadString) {
+ private Either<ArtifactDefinition, ResponseFormat> createVfModuleArtifact(ComponentInstance currVF, Service service, String vfModulePayloadString) {
ArtifactDefinition vfModuleArtifactDefinition = new ArtifactDefinition();
String newCheckSum = null;
@@ -1918,28 +1738,28 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
- private synchronized Either<Service, ResponseFormat> checkDistributionAndDeploy(String did, User user, AuditingActionEnum auditAction, Service service) {
- boolean isDeployed = isDistributionDeployed(did, service);
+ private synchronized Either<Service, ResponseFormat> checkDistributionAndDeploy(String distributionId, User user, AuditingActionEnum auditAction, Service service) {
+ boolean isDeployed = isDistributionDeployed(distributionId);
if (isDeployed) {
return Either.left(service);
}
- Either<Boolean, ResponseFormat> distributionSuccess = checkDistributionSuccess(did, user, auditAction, service);
+ Either<Boolean, ResponseFormat> distributionSuccess = checkDistributionSuccess(distributionId, user, auditAction, service);
if (distributionSuccess.isRight()) {
return Either.right(distributionSuccess.right().value());
}
- log.debug("mark distribution {} as deployed - success", did);
- componentsUtils.auditServiceDistributionDeployed(auditAction, service.getName(), service.getVersion(), service.getUUID(), did, STATUS_DEPLOYED, "OK", user);
+ log.debug("mark distribution {} as deployed - success", distributionId);
+ componentsUtils.auditServiceDistributionDeployed(service.getName(), service.getVersion(), service.getUUID(), distributionId, STATUS_DEPLOYED, "OK", user);
return Either.left(service);
}
- private boolean isDistributionDeployed(String did, Service service) {
- Either<List<DistributionDeployEvent>, ActionStatus> alreadyDeployed = auditCassandraDao.getDistributionDeployByStatus(did, AuditingActionEnum.DISTRIBUTION_DEPLOY.getName(), STATUS_DEPLOYED);
+ private boolean isDistributionDeployed(String distributionId) {
+ Either<List<DistributionDeployEvent>, ActionStatus> alreadyDeployed = auditCassandraDao.getDistributionDeployByStatus(distributionId, AuditingActionEnum.DISTRIBUTION_DEPLOY.getName(), STATUS_DEPLOYED);
boolean isDeployed = false;
if (alreadyDeployed.isLeft() && !alreadyDeployed.left().value().isEmpty()) {
// already deployed
- log.debug("distribution {} is already deployed", did);
+ log.debug("distribution {} is already deployed", distributionId);
isDeployed = true;
}
return isDeployed;
@@ -2010,36 +1830,35 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
message += error.getFormattedMessage();
if (service != null) {
- componentsUtils.auditServiceDistributionDeployed(auditAction, service.getName(), service.getVersion(), service.getUUID(), did, error.getStatus().toString(), message, user);
+ componentsUtils.auditServiceDistributionDeployed(service.getName(), service.getVersion(), service.getUUID(), did, error.getStatus().toString(), message, user);
} else {
- componentsUtils.auditServiceDistributionDeployed(auditAction, "", "", "", did, error.getStatus().toString(), message, user);
+ componentsUtils.auditServiceDistributionDeployed("", "", "", did, error.getStatus().toString(), message, user);
}
return error;
}
- private Either<User, ResponseFormat> validateRoleForDeploy(String did, User user, AuditingActionEnum auditAction, Service service) {
+ private User validateRoleForDeploy(String did, User user, AuditingActionEnum auditAction, Service service) {
Either<User, ActionStatus> eitherCreator = userAdmin.getUser(user.getUserId(), false);
if (eitherCreator.isRight() || eitherCreator.left().value() == null) {
BeEcompErrorManager.getInstance().logBeUserMissingError("Deploy Service", user.getUserId());
log.debug("validateRoleForDeploy method - user is not listed. userId= {}", user.getUserId());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND, user.getUserId());
auditDeployError(did, user, auditAction, service, ActionStatus.USER_NOT_FOUND);
- return Either.right(responseFormat);
+ throw new ComponentException(ActionStatus.USER_NOT_FOUND, user.getUserId());
}
user = eitherCreator.left().value();
log.debug("validate user role");
List<Role> roles = new ArrayList<>();
roles.add(Role.ADMIN);
roles.add(Role.OPS);
- Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, service, roles, auditAction, null);
- if (validateRes.isRight()) {
+ try{
+ validateUserRole(user, service, roles, auditAction, null);
+ } catch (ComponentException e){
log.info("role {} is not allowed to perform this action", user.getRole());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
- auditDeployError(did, user, auditAction, service, ActionStatus.RESTRICTED_OPERATION);
- return Either.right(responseFormat);
+ auditDeployError(did, user, auditAction, service, e.getActionStatus());
+ throw e;
}
- return Either.left(user);
-
+ return user;
}
@Override
@@ -2055,8 +1874,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
private HealthCheckBusinessLogic getHealthCheckBL(ServletContext context) {
WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- HealthCheckBusinessLogic healthCheckBl = webApplicationContext.getBean(HealthCheckBusinessLogic.class);
- return healthCheckBl;
+ return webApplicationContext.getBean(HealthCheckBusinessLogic.class);
}
@Override
@@ -2065,12 +1883,9 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
@Override
- public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) {
+ public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, String userId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "Get Component Instances", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
+ validateUserExists(userId, "Get Component Instances", false);
Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
if (getComponentRes.isRight()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentRes.right().value()));
@@ -2100,12 +1915,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}/**
* updates group instance with new property values in case of successful update of group instance related component instance will be updated with new modification time and related service will be updated with new last update date
*
- * @param modifier
- * @param serviceId
- * @param componentInstanceId
- * @param groupInstanceId
- * @param newProperties
- * @return
*/
public Either<List<GroupInstanceProperty>, ResponseFormat> updateGroupInstancePropertyValues(User modifier, String serviceId, String componentInstanceId, String groupInstanceId, List<GroupInstanceProperty> newProperties) {
@@ -2124,10 +1933,10 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
component = validateUserAndComponentRes.left().value().getKey();
lockResult = lockComponentByName(component.getSystemName(), component, "Update Group Instance on Service");
if (lockResult.isRight()) {
- log.debug("Failed to lock service {}. Response is {}. ", component.getName(), lockResult.right().value().getFormattedMessage());
+ log.debug(FAILED_TO_LOCK_SERVICE_RESPONSE_IS, component.getName(), lockResult.right().value().getFormattedMessage());
actionResult = Either.right(lockResult.right().value());
} else {
- log.debug("The service with system name {} locked. ", component.getSystemName());
+ log.debug(THE_SERVICE_WITH_SYSTEM_NAME_LOCKED, component.getSystemName());
}
}
if (actionResult == null) {
@@ -2157,27 +1966,26 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
Either<GroupInstance, ResponseFormat> updateGroupInstanceResult = null;
GroupInstance updatedGroupInstance = null;
boolean inTransaction = true;
- boolean shouldCloseTransaction = true;
findGroupInstanceRes = findGroupInstanceOnRelatedComponentInstance(component, componentInstanceId, groupInstanceId);
if (findGroupInstanceRes.isRight()) {
- log.debug("Group instance {} not found. ", groupInstanceId);
+ log.debug("#validateAndUpdateGroupInstancePropertyValuesAndContainingParents - Group instance {} not found. ", groupInstanceId);
actionResult = Either.right(findGroupInstanceRes.right().value());
}
if (actionResult == null) {
oldGroupInstance = findGroupInstanceRes.left().value().getValue();
relatedComponentInstance = findGroupInstanceRes.left().value().getKey();
- updateGroupInstanceResult = groupBusinessLogic.validateAndUpdateGroupInstancePropertyValues(component.getUniqueId(), componentInstanceId, oldGroupInstance, newProperties, inTransaction);
+ updateGroupInstanceResult = groupBusinessLogic.validateAndUpdateGroupInstancePropertyValues(component.getUniqueId(), componentInstanceId, oldGroupInstance, newProperties);
if (updateGroupInstanceResult.isRight()) {
- log.debug("Failed to update group instance {} property values. ", oldGroupInstance.getName());
+ log.debug("#validateAndUpdateGroupInstancePropertyValuesAndContainingParents - Failed to update group instance {} property values. ", oldGroupInstance.getName());
actionResult = Either.right(updateGroupInstanceResult.right().value());
}
}
if (actionResult == null) {
updatedGroupInstance = updateGroupInstanceResult.left().value();
if (!oldGroupInstance.getModificationTime().equals(updatedGroupInstance.getModificationTime())) {
- updateParentsModificationTimeRes = updateParentsModificationTimeAndCustomizationUuid(component, relatedComponentInstance, updatedGroupInstance, inTransaction, shouldCloseTransaction);
+ updateParentsModificationTimeRes = updateParentsModificationTimeAndCustomizationUuid(component, relatedComponentInstance, updatedGroupInstance, inTransaction);
if (updateParentsModificationTimeRes.isRight()) {
- log.debug("Failed to update modification time. ", oldGroupInstance.getName());
+ log.debug("#validateAndUpdateGroupInstancePropertyValuesAndContainingParents - Failed to update modification time for group instance {}. ", oldGroupInstance.getName());
actionResult = Either.right(updateParentsModificationTimeRes.right().value());
}
}
@@ -2189,7 +1997,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
private Either<ImmutablePair<ComponentMetadataData, ComponentInstanceData>, ResponseFormat> updateParentsModificationTimeAndCustomizationUuid(Component component, ComponentInstance relatedComponentInstance, GroupInstance updatedGroupInstance,
- boolean inTranscation, boolean shouldCloseTransaction) {
+ boolean inTranscation) {
Either<ImmutablePair<ComponentMetadataData, ComponentInstanceData>, ResponseFormat> actionResult;
Either<ComponentMetadataData, StorageOperationStatus> serviceMetadataUpdateResult;
@@ -2199,7 +2007,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
log.debug("Failed to update component instance {} after update of group instance {}. ", relatedComponentInstance.getName(), updatedGroupInstance.getName());
actionResult = Either.right(updateComponentInstanceRes.right().value());
} else {
- serviceMetadataUpdateResult = toscaOperationFacade.updateComponentLastUpdateDateOnGraph(component, updatedGroupInstance.getModificationTime());
+ serviceMetadataUpdateResult = toscaOperationFacade.updateComponentLastUpdateDateOnGraph(component);
if (serviceMetadataUpdateResult.isRight()) {
log.debug("Failed to update service {} after update of component instance {} with new property values of group instance {}. ", component.getName(), relatedComponentInstance.getName(), updatedGroupInstance.getName());
actionResult = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceMetadataUpdateResult.right().value())));
@@ -2218,21 +2026,21 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
Component component = null;
Either<User, ResponseFormat> validationUserResult = validateUserIgnoreAudit(modifier, "updateGroupInstancePropertyValues");
if (validationUserResult.isRight()) {
- log.debug("Failed to validate user with userId for update service {}. ", modifier.getUserId(), serviceId);
+ log.debug("#validateUserAndComponent - Failed to validate user with userId {}, for update service {}. ", modifier.getUserId(), serviceId);
result = Either.right(validationUserResult.right().value());
}
if (result == null) {
currUser = validationUserResult.left().value();
validateComponentExistsRes = validateComponentExists(serviceId, ComponentTypeEnum.SERVICE, null);
if (validateComponentExistsRes.isRight()) {
- log.debug("Failed to validate service existing {}. ", serviceId);
+ log.debug("#validateUserAndComponent - Failed to validate service existing {}. ", serviceId);
result = Either.right(validateComponentExistsRes.right().value());
}
}
if (result == null) {
component = validateComponentExistsRes.left().value();
if (!ComponentValidationUtils.canWorkOnComponent(component, currUser.getUserId())) {
- log.info("Restricted operation for user: {}, on service: {}", currUser.getUserId(), component.getCreatorUserId());
+ log.info("#validateUserAndComponent - Restricted operation for user: {}, on service: {}", currUser.getUserId(), component.getCreatorUserId());
return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
}
}
@@ -2250,7 +2058,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
if (foundComponentInstance == null) {
log.debug("Component instance {} not found on service {}. ", componentInstanceId, component.getName());
actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstanceId, "resource instance", "service", component.getName()));
- } else if (!CollectionUtils.isEmpty(foundComponentInstance.getGroupInstances())) {
+ }
+ else if (isNotEmpty(foundComponentInstance.getGroupInstances())) {
groupInstance = foundComponentInstance.getGroupInstances().stream().filter(gi -> gi.getUniqueId().equals(groupInstanceId)).findFirst().orElse(null);
if (groupInstance == null) {
log.debug("Group instance {} not found on component instance {}. ", groupInstanceId, foundComponentInstance.getName());
@@ -2265,43 +2074,38 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
private ComponentInstance findRelatedComponentInstance(Component component, String componentInstanceId) {
ComponentInstance componentInstance = null;
- if (!CollectionUtils.isEmpty(component.getComponentInstances())) {
+ if (isNotEmpty(component.getComponentInstances())) {
componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstanceId)).findFirst().orElse(null);
}
return componentInstance;
}
private Either<User, ResponseFormat> validateUserIgnoreAudit(User modifier, String ecompErrorContext) {
- Either<User, ResponseFormat> result = validateUser(modifier, ecompErrorContext, null, null, false);
- if (result.isLeft()) {
- List<Role> roles = new ArrayList<>();
- roles.add(Role.ADMIN);
- roles.add(Role.DESIGNER);
- Either<Boolean, ResponseFormat> validationRoleRes = validateUserRole(result.left().value(), roles);
- if (validationRoleRes.isRight()) {
- result = Either.right(validationRoleRes.right().value());
- }
- }
- return result;
+ User user = validateUser(modifier, ecompErrorContext, null, null, false);
+ List<Role> roles = new ArrayList<>();
+ roles.add(Role.ADMIN);
+ roles.add(Role.DESIGNER);
+ validateUserRole(user, roles);
+ return Either.left(user);
}
public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String serviceId, List<String> dataParamsToReturn) {
- ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
- Either<Service, StorageOperationStatus> serviceResultEither = toscaOperationFacade.getToscaElement(serviceId, paramsToRetuen);
+ ComponentParametersView paramsToReturn = new ComponentParametersView(dataParamsToReturn);
+ Either<Service, StorageOperationStatus> serviceResultEither = toscaOperationFacade.getToscaElement(serviceId, paramsToReturn);
if (serviceResultEither.isRight()) {
if(serviceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
- log.debug("Failed to found service with id {} ", serviceId);
- Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceId));
+ log.debug("#getUiComponentDataTransferByComponentId - Failed to find service with id {} ", serviceId);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceId));
}
- log.debug("failed to get service by id {} with filters {}", serviceId, dataParamsToReturn.toString());
+ log.debug("#getUiComponentDataTransferByComponentId - failed to get service by id {} with filters {}", serviceId, dataParamsToReturn);
return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(serviceResultEither.right().value()), ""));
}
Service service = serviceResultEither.left().value();
- UiComponentDataTransfer dataTransfer = UiComponentDataConverter.getUiDataTransferFromServiceByParams(service, dataParamsToReturn);
+ UiComponentDataTransfer dataTransfer = uiComponentDataConverter.getUiDataTransferFromServiceByParams(service, dataParamsToReturn);
return Either.left(dataTransfer);
}
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ComponentException.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ComponentException.java
index 6347bc2eaf..69ac1b892a 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ComponentException.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ComponentException.java
@@ -10,12 +10,11 @@ public class ComponentException extends RuntimeException {
*/
private final transient ResponseFormat responseFormat;
-
private final ActionStatus actionStatus;
private final String[] params;
public ComponentException(ResponseFormat responseFormat) {
- this(responseFormat, ActionStatus.OK, null);
+ this(responseFormat, ActionStatus.OK);
}
public ComponentException(ActionStatus actionStatus, String... params) {
@@ -24,7 +23,7 @@ public class ComponentException extends RuntimeException {
private ComponentException(ResponseFormat responseFormat, ActionStatus actionStatus, String... params) {
this.actionStatus = actionStatus;
- this.params = params;
+ this.params = params.clone();
this.responseFormat = responseFormat;
}
@@ -37,7 +36,7 @@ public class ComponentException extends RuntimeException {
}
public String[] getParams() {
- return params;
+ return params.clone();
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/SdcResourceNotFoundException.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/SdcResourceNotFoundException.java
new file mode 100644
index 0000000000..227ce20a1a
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/SdcResourceNotFoundException.java
@@ -0,0 +1,12 @@
+package org.openecomp.sdc.be.components.impl.exceptions;
+
+public class SdcResourceNotFoundException extends RuntimeException {
+
+ private static final long serialVersionUID = 4431147390120646573L;
+
+ public SdcResourceNotFoundException(){}
+
+ public SdcResourceNotFoundException(String message){
+ super(message);
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogic.java
index 94d4373795..93d79a361e 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogic.java
@@ -1,9 +1,6 @@
package org.openecomp.sdc.be.components.impl.generic;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.stream.Collectors;
-
+import fj.data.Either;
import org.apache.commons.collections.CollectionUtils;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
@@ -15,17 +12,18 @@ import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import fj.data.Either;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
@org.springframework.stereotype.Component
public class GenericTypeBusinessLogic {
- private final static Logger log = LoggerFactory.getLogger(GenericTypeBusinessLogic.class);
+ private final static Logger log = Logger.getLogger(GenericTypeBusinessLogic.class);
@Autowired
private ComponentsUtils componentsUtils;
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/group/GroupMembersUpdater.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/group/GroupMembersUpdater.java
new file mode 100644
index 0000000000..609a705639
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/group/GroupMembersUpdater.java
@@ -0,0 +1,56 @@
+package org.openecomp.sdc.be.components.impl.group;
+
+import org.apache.commons.collections.MapUtils;
+import org.openecomp.sdc.be.model.GroupDefinition;
+import org.springframework.stereotype.Component;
+
+import java.util.List;
+import java.util.Map;
+
+import static org.apache.commons.collections.MapUtils.isEmpty;
+
+/**
+ * A Helper class which handles altering the members state of a group
+ */
+@Component
+public class GroupMembersUpdater {
+
+ public void removeMember(List<GroupDefinition> groups, String memberId) {
+ groups.forEach(group -> removeGroupMember(group, memberId));
+ }
+
+ public void replaceMember(List<GroupDefinition> groups, String oldMemberId, String newMemberId) {
+ groups.forEach(grp -> replaceMember(grp, oldMemberId, newMemberId));
+ }
+
+ private void removeGroupMember(GroupDefinition group, String memberId) {
+ Map<String, String> membersNameToId = group.getMembers();
+ String groupMemberKey = findGroupMemberKey(membersNameToId, memberId);
+ if (groupMemberKey != null) {
+ membersNameToId.remove(groupMemberKey);
+ }
+ }
+
+ private void replaceMember(GroupDefinition group, String oldMemberId, String newMemberId) {
+ Map<String, String> membersNameToId = group.getMembers();
+ String groupMemberKey = findGroupMemberKey(membersNameToId, oldMemberId);
+ if (groupMemberKey != null) {
+ membersNameToId.replace(groupMemberKey, newMemberId);
+ }
+ }
+
+ private String findGroupMemberKey(Map<String, String> members, String memberToFind) {
+ if (isEmpty(members)) {
+ return null;
+ }
+ Map invertedMap = MapUtils.invertMap(members);
+ if (!invertedMap.containsKey(memberToFind)) {
+ return null;
+ }
+ return invertedMap.get(memberToFind).toString();
+ }
+
+
+
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/ComponentInstanceChangeOperationOrchestrator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/ComponentInstanceChangeOperationOrchestrator.java
new file mode 100644
index 0000000000..e922daf837
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/ComponentInstanceChangeOperationOrchestrator.java
@@ -0,0 +1,43 @@
+package org.openecomp.sdc.be.components.impl.instance;
+
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.common.log.wrappers.Logger;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.function.Function;
+
+@org.springframework.stereotype.Component
+public class ComponentInstanceChangeOperationOrchestrator {
+
+ private static final Logger log = Logger.getLogger(ComponentInstanceChangeOperationOrchestrator.class);
+ private final List<OnComponentInstanceChangeOperation> onInstanceChangeOperations;
+
+ public ComponentInstanceChangeOperationOrchestrator(List<OnComponentInstanceChangeOperation> onInstanceChangeOperations) {
+ this.onInstanceChangeOperations = onInstanceChangeOperations;
+ }
+
+ public ActionStatus doPostChangeVersionOperations(Component container, ComponentInstance prevVersion, ComponentInstance newVersion) {
+ log.debug("#doPostChangeVersionOperations - starting post change version operations for component {}. from instance {} to instance {}", container.getUniqueId(), prevVersion.getUniqueId(), newVersion.getUniqueId());
+ Function<OnComponentInstanceChangeOperation, ActionStatus> instanceChangeTaskRunner = operation -> operation.onChangeVersion(container, prevVersion, newVersion);
+ return doOnChangeInstanceOperations(instanceChangeTaskRunner);
+ }
+
+ public ActionStatus doOnDeleteInstanceOperations(Component container, String deletedInstanceId) {
+ log.debug("#doPostChangeVersionOperations - starting on delete instance operations for component {} and instance {}.", container.getUniqueId(), deletedInstanceId);
+ Function<OnComponentInstanceChangeOperation, ActionStatus> instanceChangeTaskRunner = operation -> operation.onDelete(container, deletedInstanceId);
+ return doOnChangeInstanceOperations(instanceChangeTaskRunner);
+ }
+
+ private ActionStatus doOnChangeInstanceOperations(Function<OnComponentInstanceChangeOperation, ActionStatus> instanceChangeTaskRunner) {
+ ActionStatus onDeleteInstanceResult = ActionStatus.OK;
+ Iterator<OnComponentInstanceChangeOperation> onDeleteInstIter = onInstanceChangeOperations.iterator();
+ while(onDeleteInstIter.hasNext() && onDeleteInstanceResult == ActionStatus.OK) {
+ onDeleteInstanceResult = instanceChangeTaskRunner.apply(onDeleteInstIter.next());
+ }
+ return onDeleteInstanceResult;
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/GroupMembersUpdateOperation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/GroupMembersUpdateOperation.java
new file mode 100644
index 0000000000..cc6e9e9cd3
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/GroupMembersUpdateOperation.java
@@ -0,0 +1,62 @@
+package org.openecomp.sdc.be.components.impl.instance;
+
+import org.openecomp.sdc.be.components.impl.group.GroupMembersUpdater;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation;
+import org.openecomp.sdc.common.log.wrappers.Logger;
+
+import java.util.List;
+import java.util.function.Consumer;
+
+import static org.apache.commons.collections.CollectionUtils.isEmpty;
+@org.springframework.stereotype.Component
+public class GroupMembersUpdateOperation implements OnComponentInstanceChangeOperation {
+
+ private static final Logger log = Logger.getLogger(GroupMembersUpdateOperation.class);
+ private final GroupsOperation groupsOperation;
+ private final ComponentsUtils componentsUtils;
+ private final GroupMembersUpdater groupMembersUpdater;
+
+ public GroupMembersUpdateOperation(GroupsOperation groupsOperation, ComponentsUtils componentsUtils, GroupMembersUpdater groupMembersUpdater) {
+ this.groupsOperation = groupsOperation;
+ this.componentsUtils = componentsUtils;
+ this.groupMembersUpdater = groupMembersUpdater;
+ }
+
+ @Override
+ public ActionStatus onChangeVersion(Component container, ComponentInstance prevVersion, ComponentInstance newVersion) {
+ log.debug("#onChangeVersion - replacing all group members for component instance {} with new component instance on component", prevVersion.getUniqueId(), newVersion.getUniqueId(), container.getUniqueId());
+ Consumer<List<GroupDefinition>> replaceGroupMemberTask = (groups) -> groupMembersUpdater.replaceMember(groups, prevVersion.getUniqueId(), newVersion.getUniqueId());
+ return doUpdateGroupMembers(container, prevVersion.getUniqueId(), replaceGroupMemberTask);
+ }
+
+ @Override
+ public ActionStatus onDelete(Component container, String deletedEntityId) {
+ log.debug("#onDelete - deleting group member referencing component instance {} on component {}.", deletedEntityId, container.getUniqueId());
+ Consumer<List<GroupDefinition>> deleteGroupMemberTask = (groups) -> groupMembersUpdater.removeMember(groups, deletedEntityId);
+ return doUpdateGroupMembers(container, deletedEntityId, deleteGroupMemberTask);
+ }
+
+ private ActionStatus doUpdateGroupMembers(Component container, String memberId, Consumer<List<GroupDefinition>> updateGroupMemberTask) {
+ List<GroupDefinition> groupsWithPrevInstAsMember = container.resolveGroupsByMember(memberId);
+ if (isEmpty(groupsWithPrevInstAsMember)) {
+ log.debug("#doUpdateGroupMembers - container {} has no groups with component instance {} as member.", container.getUniqueId(), memberId);
+ return ActionStatus.OK;
+ }
+ updateGroupMemberTask.accept(groupsWithPrevInstAsMember);
+ return updateGroups(container, groupsWithPrevInstAsMember);
+ }
+
+ private ActionStatus updateGroups(Component container, List<GroupDefinition> groupsToUpdate) {
+ log.debug("#updateGroups - updating {} groups for container {}", groupsToUpdate.size(), container.getUniqueId());
+ return groupsOperation.updateGroups(container, groupsToUpdate, false)
+ .either(groupsUpdated -> ActionStatus.OK,
+ err -> componentsUtils.convertFromStorageResponse(err, container.getComponentType()));
+ }
+
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/OnChangeVersionOperation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/OnChangeVersionOperation.java
new file mode 100644
index 0000000000..90d006b733
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/OnChangeVersionOperation.java
@@ -0,0 +1,18 @@
+package org.openecomp.sdc.be.components.impl.instance;
+
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+@FunctionalInterface
+public interface OnChangeVersionOperation {
+
+ /**
+ * A side effect operation to execute when a component instance version was changed from {@code prevVersion} to {@code newVersion}
+ * @param container the container which contains the instance which is version was changed
+ * @param prevVersion the previous version of the component instance.
+ * @param newVersion the new version of the component instance.
+ * @return the status of the operation
+ */
+ ActionStatus onChangeVersion(Component container, ComponentInstance prevVersion, ComponentInstance newVersion);
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/OnComponentInstanceChangeOperation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/OnComponentInstanceChangeOperation.java
new file mode 100644
index 0000000000..f5c21af4a6
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/OnComponentInstanceChangeOperation.java
@@ -0,0 +1,9 @@
+package org.openecomp.sdc.be.components.impl.instance;
+
+import org.openecomp.sdc.be.components.impl.OnDeleteEntityOperation;
+
+/**
+ * An interface which groups all operations to be executed when an action on a component instance has occurred
+ */
+public interface OnComponentInstanceChangeOperation extends OnChangeVersionOperation, OnDeleteEntityOperation {
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/PolicyTargetsUpdateOperation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/PolicyTargetsUpdateOperation.java
new file mode 100644
index 0000000000..f7bfc6d65a
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/PolicyTargetsUpdateOperation.java
@@ -0,0 +1,33 @@
+package org.openecomp.sdc.be.components.impl.instance;
+
+import org.openecomp.sdc.be.components.impl.policy.PolicyTargetsUpdateHandler;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.common.log.wrappers.Logger;
+
+@org.springframework.stereotype.Component
+public class PolicyTargetsUpdateOperation implements OnComponentInstanceChangeOperation {
+
+ private static final Logger log = Logger.getLogger(PolicyTargetsUpdateOperation.class);
+ private final PolicyTargetsUpdateHandler policyTargetsUpdateHandler;
+
+ public PolicyTargetsUpdateOperation(PolicyTargetsUpdateHandler policyTargetsUpdateHandler) {
+ this.policyTargetsUpdateHandler = policyTargetsUpdateHandler;
+ }
+
+ @Override
+ public ActionStatus onChangeVersion(Component container, ComponentInstance prevVersion, ComponentInstance newVersion) {
+ log.debug("#onChangeVersion - replacing all policy targets referencing component instance {} with component instance {}", prevVersion.getUniqueId(), newVersion.getUniqueId());
+ return policyTargetsUpdateHandler.replacePoliciesTargets(container, prevVersion.getUniqueId(), newVersion.getUniqueId(), PolicyTargetType.COMPONENT_INSTANCES);
+ }
+
+ @Override
+ public ActionStatus onDelete(Component container, String deletedEntityId) {
+ log.debug("#onDelete - removing all component {} policy targets referencing component instance {}", container.getUniqueId(), deletedEntityId);
+ return policyTargetsUpdateHandler.removePoliciesTargets(container, deletedEntityId, PolicyTargetType.COMPONENT_INSTANCES);
+ }
+
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/lock/ComponentLockAspect.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/lock/ComponentLockAspect.java
new file mode 100644
index 0000000000..9304caa607
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/lock/ComponentLockAspect.java
@@ -0,0 +1,38 @@
+package org.openecomp.sdc.be.components.impl.lock;
+
+import org.aspectj.lang.ProceedingJoinPoint;
+import org.openecomp.sdc.be.components.impl.ComponentLocker;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.common.log.wrappers.Logger;
+
+public class ComponentLockAspect {
+
+ private static final Logger log = Logger.getLogger(ComponentLockAspect.class);
+ private final ComponentLocker componentLocker;
+
+ public ComponentLockAspect(ComponentLocker componentLocker) {
+ this.componentLocker = componentLocker;
+ }
+
+ public Object lock(ProceedingJoinPoint proceedingJoinPoint, String componentId, ComponentTypeEnum componentType) throws Throwable {
+ return surroundWithLockUnlock(proceedingJoinPoint, componentId, componentType.getNodeType());
+ }
+
+ private Object surroundWithLockUnlock(ProceedingJoinPoint proceedingJoinPoint, String componentId, NodeTypeEnum componentType) throws Throwable {
+ String methodName = proceedingJoinPoint.getSignature().toShortString();
+ try {
+ log.trace("#{} - before locking component {} of type {}", methodName, componentId, componentType);
+ componentLocker.lock(componentId, componentType);
+ log.trace("#{} - after locking component {} of type {}", methodName, componentId, componentType);
+ return proceedingJoinPoint.proceed();
+ }
+ finally {
+ log.trace("#{} - before unlocking component {} of type {}", methodName, componentId, componentType);
+ componentLocker.unlock(componentId, componentType);
+ log.trace("#{} - after unlocking component {} of type {}", methodName, componentId, componentType);
+ }
+ }
+
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/lock/LockingTransactional.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/lock/LockingTransactional.java
new file mode 100644
index 0000000000..366969f284
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/lock/LockingTransactional.java
@@ -0,0 +1,13 @@
+package org.openecomp.sdc.be.components.impl.lock;
+
+import org.springframework.transaction.annotation.Transactional;
+
+import java.lang.annotation.*;
+
+@Target({ElementType.METHOD, ElementType.TYPE})
+@Retention(RetentionPolicy.RUNTIME)
+@Transactional
+@Inherited
+public @interface LockingTransactional {
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/model/ToscaTypeImportData.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/model/ToscaTypeImportData.java
new file mode 100644
index 0000000000..5568842798
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/model/ToscaTypeImportData.java
@@ -0,0 +1,24 @@
+package org.openecomp.sdc.be.components.impl.model;
+
+import org.openecomp.sdc.be.model.normatives.ToscaTypeMetadata;
+
+import java.util.Map;
+
+public class ToscaTypeImportData {
+
+ private String toscaTypesYml;
+ private Map<String, ToscaTypeMetadata> toscaTypeMetadata;
+
+ public ToscaTypeImportData(String toscaTypesYml, Map<String, ToscaTypeMetadata> toscaTypeMetadata) {
+ this.toscaTypesYml = toscaTypesYml;
+ this.toscaTypeMetadata = toscaTypeMetadata;
+ }
+
+ public String getToscaTypesYml() {
+ return toscaTypesYml;
+ }
+
+ public Map<String, ToscaTypeMetadata> getToscaTypeMetadata() {
+ return toscaTypeMetadata;
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdateHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdateHandler.java
new file mode 100644
index 0000000000..10a35d0128
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdateHandler.java
@@ -0,0 +1,58 @@
+package org.openecomp.sdc.be.components.impl.policy;
+
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.PolicyDefinition;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.common.log.wrappers.Logger;
+
+import java.util.List;
+import java.util.function.Consumer;
+
+import static org.apache.commons.collections.CollectionUtils.isEmpty;
+
+@org.springframework.stereotype.Component
+public class PolicyTargetsUpdateHandler {
+
+ private static final Logger log = Logger.getLogger(PolicyTargetsUpdateHandler.class);
+ private final ToscaOperationFacade toscaOperationFacade;
+ private final ComponentsUtils componentsUtils;
+ private final PolicyTargetsUpdater policyTargetsUpdater;
+
+ public PolicyTargetsUpdateHandler(ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils, PolicyTargetsUpdater policyTargetsUpdater) {
+ this.toscaOperationFacade = toscaOperationFacade;
+ this.componentsUtils = componentsUtils;
+ this.policyTargetsUpdater = policyTargetsUpdater;
+ }
+
+ public ActionStatus removePoliciesTargets(Component container, String targetId, PolicyTargetType targetType) {
+ log.debug("#removePoliciesTargets - removing all component {} policy targets referencing target {}", container.getUniqueId(), targetId);
+ Consumer<List<PolicyDefinition>> removeTarget = policies -> policyTargetsUpdater.removeTarget(policies, targetId, targetType);
+ return updatePolicyTargets(container, targetId, targetType, removeTarget);
+ }
+
+ public ActionStatus replacePoliciesTargets(Component container, String prevTargetId, String newTargetId, PolicyTargetType targetType) {
+ log.debug("#replacePoliciesTargets - replacing all policy targets referencing target {} with target {}", prevTargetId, newTargetId);
+ Consumer<List<PolicyDefinition>> replaceTarget = policies -> policyTargetsUpdater.replaceTarget(policies, prevTargetId, newTargetId, targetType);
+ return updatePolicyTargets(container, prevTargetId, targetType, replaceTarget);
+ }
+
+ private ActionStatus updatePolicyTargets(Component container, String targetId, PolicyTargetType targetType, Consumer<List<PolicyDefinition>> updatePolicyTargetTaskRunner) {
+ List<PolicyDefinition> policiesWithPrevInstanceAsTarget = container.resolvePoliciesContainingTarget(targetId, targetType);
+ if (isEmpty(policiesWithPrevInstanceAsTarget)) {
+ return ActionStatus.OK;
+ }
+ updatePolicyTargetTaskRunner.accept(policiesWithPrevInstanceAsTarget);
+ return updatePolicies(container, policiesWithPrevInstanceAsTarget);
+ }
+
+ private ActionStatus updatePolicies(Component policiesContainer, List<PolicyDefinition> policiesToUpdate) {
+ log.debug("#updatePolicies - updating {} policies for container {}", policiesToUpdate.size(), policiesContainer.getUniqueId());
+ StorageOperationStatus updatePolicyResult = toscaOperationFacade.updatePoliciesOfComponent(policiesContainer.getUniqueId(), policiesToUpdate);
+ return componentsUtils.convertFromStorageResponse(updatePolicyResult, policiesContainer.getComponentType());
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdater.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdater.java
new file mode 100644
index 0000000000..1f094f5a60
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdater.java
@@ -0,0 +1,57 @@
+package org.openecomp.sdc.be.components.impl.policy;
+
+import org.apache.commons.collections.MapUtils;
+import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType;
+import org.openecomp.sdc.be.model.PolicyDefinition;
+import org.springframework.stereotype.Component;
+
+import java.util.List;
+import java.util.Map;
+import java.util.function.UnaryOperator;
+
+import static java.util.Collections.emptyList;
+import static org.apache.commons.collections.CollectionUtils.isEmpty;
+
+/**
+ * A Helper class which handles altering the targets state of a policy
+ */
+@Component
+public class PolicyTargetsUpdater {
+
+ public void removeTarget(List<PolicyDefinition> policies, String targetId, PolicyTargetType targetType) {
+ policies.forEach(policy -> removePolicyTarget(policy, targetId, targetType));
+ }
+
+ public void replaceTarget(List<PolicyDefinition> policies, String oldTargetId, String newTargetId, PolicyTargetType targetType) {
+ policies.forEach(policy -> replacePolicyTarget(policy, targetType, oldTargetId, newTargetId));
+ }
+
+ private void replacePolicyTarget(PolicyDefinition policyDefinition, PolicyTargetType targetType, String oldTargetId, String newTargetId) {
+ List<String> policyTargets = getTargetsList(policyDefinition, targetType);
+ if (isEmpty(policyTargets)) {
+ return;
+ }
+ policyTargets.replaceAll(prevInstanceIdByNewInstanceId(oldTargetId, newTargetId));
+ }
+
+ private void removePolicyTarget(PolicyDefinition policy, String targetId, PolicyTargetType targetType) {
+ List<String> policyTargets = getTargetsList(policy, targetType);
+ if (isEmpty(policyTargets)) {
+ return;
+ }
+ policyTargets.remove(targetId);
+ }
+
+ private List<String> getTargetsList(PolicyDefinition policyDefinition, PolicyTargetType targetType) {
+ Map<PolicyTargetType, List<String>> targets = policyDefinition.getTargets();
+ if(MapUtils.isEmpty(targets) || isEmpty(targets.get(targetType))) {
+ return emptyList();
+ }
+ return targets.get(targetType);
+ }
+
+ private UnaryOperator<String> prevInstanceIdByNewInstanceId(String prevInstanceId, String newInstanceId) {
+ return instId -> instId.equals(prevInstanceId) ? newInstanceId: instId;
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CapabilityTypeImportUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CapabilityTypeImportUtils.java
new file mode 100644
index 0000000000..d506a85996
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CapabilityTypeImportUtils.java
@@ -0,0 +1,28 @@
+package org.openecomp.sdc.be.components.impl.utils;
+
+import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
+
+import java.util.Objects;
+
+public class CapabilityTypeImportUtils {
+
+ private CapabilityTypeImportUtils() {
+ }
+
+ public static boolean isCapabilityTypesEquals(CapabilityTypeDefinition capabilityType1, CapabilityTypeDefinition capabilityType2) {
+ if (capabilityType1 == capabilityType2) {
+ return true;
+ }
+
+ if (capabilityType1 == null || capabilityType2 == null) {
+ return false;
+ }
+
+ return Objects.equals(capabilityType1.getType(), capabilityType2.getType()) &&
+ Objects.equals(capabilityType1.getVersion(), capabilityType2.getVersion()) &&
+ Objects.equals(capabilityType1.getDerivedFrom(), capabilityType2.getDerivedFrom()) &&
+ Objects.equals(capabilityType1.getValidSourceTypes(), capabilityType2.getValidSourceTypes()) &&
+ Objects.equals(capabilityType1.getDescription(), capabilityType2.getDescription()) &&
+ Objects.equals(capabilityType1.getProperties(), capabilityType2.getProperties());
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/ExceptionUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/ExceptionUtils.java
new file mode 100644
index 0000000000..e48d21cb77
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/ExceptionUtils.java
@@ -0,0 +1,44 @@
+package org.openecomp.sdc.be.components.impl.utils;
+
+import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.model.operations.StorageException;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.exception.ResponseFormat;
+import org.springframework.stereotype.Component;
+
+@Component
+public class ExceptionUtils {
+
+ private final TitanDao titanDao;
+
+ public ExceptionUtils(TitanDao titanDao) {
+ this.titanDao = titanDao;
+ }
+
+ public <T> T rollBackAndThrow(ActionStatus actionStatus, String ... params) {
+ titanDao.rollback();
+ throw new ComponentException(actionStatus, params);
+ }
+
+ public <T> T rollBackAndThrow(ResponseFormat responseFormat) {
+ titanDao.rollback();
+ throw new ComponentException(responseFormat);
+ }
+
+ public <T> T rollBackAndThrow(StorageOperationStatus status, String ... params) {
+ titanDao.rollback();
+ throw new StorageException(status, params);
+ }
+
+ public <T> T rollBackAndThrow(TitanOperationStatus status, String ... params) {
+ titanDao.rollback();
+ throw new StorageException(status, params);
+ }
+
+
+
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtils.java
index 50f64e2f3f..04260df7eb 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtils.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtils.java
@@ -1,13 +1,15 @@
package org.openecomp.sdc.be.components.impl.utils;
+import org.openecomp.sdc.be.dao.utils.MapUtil;
+import org.openecomp.sdc.be.model.PolicyTypeDefinition;
+import org.openecomp.sdc.be.model.PropertyDefinition;
+
import java.util.List;
import java.util.Map;
import java.util.Objects;
-import org.apache.commons.collections.CollectionUtils;
-import org.openecomp.sdc.be.dao.utils.MapUtil;
-import org.openecomp.sdc.be.model.PolicyTypeDefinition;
-import org.openecomp.sdc.be.model.PropertyDefinition;
+import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
+import static org.springframework.util.CollectionUtils.isEmpty;
public class PolicyTypeImportUtils {
@@ -22,6 +24,8 @@ public class PolicyTypeImportUtils {
return false;
}
return Objects.equals(pt1.getType(), pt2.getType()) &&
+ Objects.equals(pt1.getName(), pt2.getName()) &&
+ Objects.equals(pt1.getIcon(), pt2.getIcon()) &&
Objects.equals(pt1.getVersion(), pt2.getVersion()) &&
Objects.equals(pt1.getDerivedFrom(), pt2.getDerivedFrom()) &&
Objects.equals(pt1.getTargets(), pt2.getTargets()) &&
@@ -34,8 +38,8 @@ public class PolicyTypeImportUtils {
if (pt1Props == pt2Props) {
return true;
}
- if (pt1Props == null || pt2Props == null) {
- return false;
+ if (pt1Props == null && isEmpty(pt2Props) || pt2Props == null && isEmpty(pt1Props)) {
+ return true;
}
if (isPropertiesListSizesNotEquals(pt1Props, pt2Props)) {
return false;
@@ -62,9 +66,9 @@ public class PolicyTypeImportUtils {
}
private static boolean isPropertiesListSizesNotEquals(List<PropertyDefinition> pt1Props, List<PropertyDefinition> pt2Props) {
- return CollectionUtils.isEmpty(pt1Props) && CollectionUtils.isNotEmpty(pt2Props) ||
- CollectionUtils.isEmpty(pt2Props) && CollectionUtils.isNotEmpty(pt1Props) ||
- pt1Props.size() != pt2Props.size();
+ return isEmpty(pt1Props) && isNotEmpty(pt2Props) ||
+ isEmpty(pt2Props) && isNotEmpty(pt1Props) ||
+ pt1Props.size() != pt2Props.size();
}
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/GroupMembersUpdateOperation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/GroupMembersUpdateOperation.java
deleted file mode 100644
index 1b6f49df8b..0000000000
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/GroupMembersUpdateOperation.java
+++ /dev/null
@@ -1,66 +0,0 @@
-package org.openecomp.sdc.be.components.impl.version;
-
-import static org.apache.commons.collections.CollectionUtils.isEmpty;
-
-import java.util.List;
-import java.util.Map;
-
-import org.apache.commons.collections.MapUtils;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.GroupDefinition;
-import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-@org.springframework.stereotype.Component
-public class GroupMembersUpdateOperation implements PostChangeVersionOperation {
-
- private static final Logger log = LoggerFactory.getLogger(GroupMembersUpdateOperation.class);
- private final GroupsOperation groupsOperation;
- private final ComponentsUtils componentsUtils;
-
- public GroupMembersUpdateOperation(GroupsOperation groupsOperation, ComponentsUtils componentsUtils) {
- this.groupsOperation = groupsOperation;
- this.componentsUtils = componentsUtils;
- }
-
- @Override
- public ActionStatus onChangeVersion(Component container, ComponentInstance prevVersion, ComponentInstance newVersion) {
- return updateGroupMembersOnChangeVersion(container, prevVersion, newVersion);
- }
-
- private ActionStatus updateGroupMembersOnChangeVersion(Component container, ComponentInstance prevVersion, ComponentInstance newVersion) {
- log.debug("#updateGroupMembersOnChangeVersion - replacing all group members for component instance {} with new component instance.", prevVersion.getUniqueId(), newVersion.getUniqueId());
- if (isEmpty(container.getGroups())) {
- log.debug("#updateGroupMembersOnChangeVersion - container {} has no groups.", container.getUniqueId());
- return ActionStatus.OK;
- }
- List<GroupDefinition> groupsWithPrevInstAsMember = container.resolveGroupsByMember(prevVersion.getUniqueId());
- if (isEmpty(groupsWithPrevInstAsMember)) {
- log.debug("#updateGroupMembersOnChangeVersion - container {} has no groups with component instance {} as member.", container.getUniqueId(), prevVersion.getUniqueId());
- return ActionStatus.OK;
- }
- replacePrevInstanceMemberWithNewInstance(prevVersion, newVersion, groupsWithPrevInstAsMember);
- return updateGroups(container, groupsWithPrevInstAsMember);
- }
-
- private ActionStatus updateGroups(Component container, List<GroupDefinition> groupsToUpdate) {
- log.debug("#updateGroups - updating {} groups for container {}", groupsToUpdate.size(), container.getUniqueId());
- return groupsOperation.updateGroups(container, groupsToUpdate)
- .either(groupsUpdated -> ActionStatus.OK,
- err -> componentsUtils.convertFromStorageResponse(err, container.getComponentType()));
- }
-
- private void replacePrevInstanceMemberWithNewInstance(ComponentInstance prevVersion, ComponentInstance newVersion, List<GroupDefinition> groupsWithPrevInstAsMember) {
- groupsWithPrevInstAsMember.forEach(grp -> replacePrevInstanceMemberWithNewInstance(grp, prevVersion.getUniqueId(), newVersion.getUniqueId()));
- }
-
- private void replacePrevInstanceMemberWithNewInstance(GroupDefinition groupDefinition, String prevInstanceId, String newInstanceId) {
- Map<String, String> membersNameToId = groupDefinition.getMembers();
- String prevInstanceMemberName = MapUtils.invertMap(membersNameToId).get(prevInstanceId).toString();
- membersNameToId.replace(prevInstanceMemberName, newInstanceId);
- }
-
-}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PolicyTargetsUpdateOperation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PolicyTargetsUpdateOperation.java
deleted file mode 100644
index 1d27228c50..0000000000
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PolicyTargetsUpdateOperation.java
+++ /dev/null
@@ -1,67 +0,0 @@
-package org.openecomp.sdc.be.components.impl.version;
-
-import static org.apache.commons.collections.CollectionUtils.isEmpty;
-
-import java.util.List;
-import java.util.function.UnaryOperator;
-
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.PolicyDefinition;
-import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-@org.springframework.stereotype.Component
-public class PolicyTargetsUpdateOperation implements PostChangeVersionOperation {
-
- private static final Logger log = LoggerFactory.getLogger(PolicyTargetsUpdateOperation.class);
- private final ToscaOperationFacade toscaOperationFacade;
- private final ComponentsUtils componentsUtils;
-
- public PolicyTargetsUpdateOperation(ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils) {
- this.toscaOperationFacade = toscaOperationFacade;
- this.componentsUtils = componentsUtils;
- }
-
- @Override
- public ActionStatus onChangeVersion(Component container, ComponentInstance prevVersion, ComponentInstance newVersion) {
- return replacePolicyTargetsInstanceId(container, prevVersion, newVersion);
- }
-
- private ActionStatus replacePolicyTargetsInstanceId(Component container, ComponentInstance prevVersion, ComponentInstance newVersion) {
- log.debug("#replacePolicyTargetsInstanceId - replacing all policy targets for component instance {} with component instance {}", prevVersion.getUniqueId(), newVersion.getUniqueId());
- List<PolicyDefinition> policiesWithPrevInstanceAsTarget = container.resolvePoliciesByComponentInstanceTarget(prevVersion.getUniqueId());
- if (isEmpty(policiesWithPrevInstanceAsTarget)) {
- return ActionStatus.OK;
- }
- replaceTargetsPrevInstanceIdWithNewInstanceId(prevVersion, newVersion, policiesWithPrevInstanceAsTarget);
- return updatePolicies(container, policiesWithPrevInstanceAsTarget);
- }
-
- private ActionStatus updatePolicies(Component policiesContainer, List<PolicyDefinition> policiesToUpdate) {
- log.debug("#updatePolicies - updating {} policies for container {}", policiesToUpdate.size(), policiesContainer.getUniqueId());
- StorageOperationStatus updatePolicyResult = toscaOperationFacade.updatePoliciesOfComponent(policiesContainer.getUniqueId(), policiesToUpdate);
- return componentsUtils.convertFromStorageResponse(updatePolicyResult, policiesContainer.getComponentType());
- }
-
- private void replaceTargetsPrevInstanceIdWithNewInstanceId(ComponentInstance prevVersion, ComponentInstance newVersion, List<PolicyDefinition> policiesWithPrevInstanceAsTarget) {
- policiesWithPrevInstanceAsTarget.forEach(policy -> updatePolicyTargetWithNewInstanceVersion(policy, prevVersion.getUniqueId(), newVersion.getUniqueId()));
- }
-
- private void updatePolicyTargetWithNewInstanceVersion(PolicyDefinition policyDefinition, String prevInstanceId, String newInstanceId) {
- List<String> policyInstanceTargets = policyDefinition.resolveComponentInstanceTargets();
- if (isEmpty(policyInstanceTargets)) {
- return;
- }
- policyInstanceTargets.replaceAll(prevInstanceIdByNewInstanceId(prevInstanceId, newInstanceId));
- }
-
- private UnaryOperator<String> prevInstanceIdByNewInstanceId(String prevInstanceId, String newInstanceId) {
- return instId -> instId.equals(prevInstanceId) ? newInstanceId: instId;
- }
-
-}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperation.java
deleted file mode 100644
index ee16c203bf..0000000000
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperation.java
+++ /dev/null
@@ -1,11 +0,0 @@
-package org.openecomp.sdc.be.components.impl.version;
-
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-@FunctionalInterface
-public interface PostChangeVersionOperation {
-
- ActionStatus onChangeVersion(Component container, ComponentInstance prevVersion, ComponentInstance newVersion);
-
-}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestrator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestrator.java
deleted file mode 100644
index 375d8e6e12..0000000000
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestrator.java
+++ /dev/null
@@ -1,32 +0,0 @@
-package org.openecomp.sdc.be.components.impl.version;
-
-import java.util.Iterator;
-import java.util.List;
-
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-@org.springframework.stereotype.Component
-public class PostChangeVersionOperationOrchestrator {
-
- private static final Logger log = LoggerFactory.getLogger(PostChangeVersionOperationOrchestrator.class);
- private final List<PostChangeVersionOperation> postChangeVersionOperations;
-
- public PostChangeVersionOperationOrchestrator(List<PostChangeVersionOperation> postChangeVersionOperations) {
- this.postChangeVersionOperations = postChangeVersionOperations;
- }
-
- public ActionStatus doPostChangeVersionOperations(Component container, ComponentInstance prevVersion, ComponentInstance newVersion) {
- log.debug("#doPostChangeVersionOperations - starting post change version operations for component {}. from instance {} to instance {}", container.getUniqueId(), prevVersion.getUniqueId(), newVersion.getUniqueId());
- ActionStatus postOperationsResult = ActionStatus.OK;
- Iterator<PostChangeVersionOperation> postChangeVersionIter = postChangeVersionOperations.iterator();
- while(postChangeVersionIter.hasNext() && postOperationsResult == ActionStatus.OK) {
- postOperationsResult = postChangeVersionIter.next().onChangeVersion(container, prevVersion, newVersion);
- }
- return postOperationsResult;
- }
-
-}