2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
19 * Modifications copyright (c) 2019 Nokia
20 * ================================================================================
23 package org.openecomp.sdc.be.components.impl;
25 import static org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR;
27 import com.google.gson.JsonElement;
28 import fj.data.Either;
29 import java.util.ArrayList;
30 import java.util.Arrays;
31 import java.util.Collections;
32 import java.util.List;
34 import java.util.function.Function;
35 import org.apache.commons.lang3.ArrayUtils;
36 import org.apache.commons.lang3.StringUtils;
37 import org.apache.commons.lang3.tuple.ImmutablePair;
38 import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException;
39 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
40 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
41 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
42 import org.openecomp.sdc.be.components.validation.UserValidations;
43 import org.openecomp.sdc.be.config.BeEcompErrorManager;
44 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
45 import org.openecomp.sdc.be.dao.api.ActionStatus;
46 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao;
47 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
48 import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao;
49 import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils;
50 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
51 import org.openecomp.sdc.be.datatypes.elements.PropertyRule;
52 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
53 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
54 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
55 import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
56 import org.openecomp.sdc.be.impl.ComponentsUtils;
57 import org.openecomp.sdc.be.model.ArtifactDefinition;
58 import org.openecomp.sdc.be.model.Component;
59 import org.openecomp.sdc.be.model.ComponentInstInputsMap;
60 import org.openecomp.sdc.be.model.ComponentInstance;
61 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
62 import org.openecomp.sdc.be.model.ComponentParametersView;
63 import org.openecomp.sdc.be.model.DataTypeDefinition;
64 import org.openecomp.sdc.be.model.IComplexDefaultValue;
65 import org.openecomp.sdc.be.model.IPropertyInputCommon;
66 import org.openecomp.sdc.be.model.LifecycleStateEnum;
67 import org.openecomp.sdc.be.model.PolicyDefinition;
68 import org.openecomp.sdc.be.model.PropertyConstraint;
69 import org.openecomp.sdc.be.model.PropertyDefinition;
70 import org.openecomp.sdc.be.model.User;
71 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
72 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
73 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
74 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
75 import org.openecomp.sdc.be.model.operations.StorageException;
76 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
77 import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
78 import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
79 import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
80 import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
81 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
82 import org.openecomp.sdc.be.model.operations.impl.AttributeOperation;
83 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
84 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
85 import org.openecomp.sdc.be.model.operations.impl.PolicyTypeOperation;
86 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
87 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
88 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
89 import org.openecomp.sdc.be.model.tosca.ToscaType;
90 import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter;
91 import org.openecomp.sdc.be.model.tosca.validators.DataTypeValidatorConverter;
92 import org.openecomp.sdc.be.model.tosca.validators.PropertyTypeValidator;
93 import org.openecomp.sdc.be.user.Role;
94 import org.openecomp.sdc.be.user.UserBusinessLogic;
95 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
96 import org.openecomp.sdc.common.datastructure.Wrapper;
97 import org.openecomp.sdc.common.log.wrappers.Logger;
98 import org.openecomp.sdc.exception.ResponseFormat;
99 import org.springframework.beans.factory.annotation.Autowired;
101 public abstract class BaseBusinessLogic {
103 private static final String FAILED_TO_LOCK_COMPONENT_ERROR = "Failed to lock component {} error - {}";
105 private static final Logger log = Logger.getLogger(BaseBusinessLogic.class);
106 private static final String EMPTY_VALUE = null;
107 private static final String SCHEMA_DOESN_T_EXISTS_FOR_PROPERTY_OF_TYPE = "Schema doesn't exists for property of type {}";
108 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";
109 private static final String ADD_PROPERTY_VALUE = "Add property value";
110 private static final String THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID = "The value {} of property from type {} is invalid";
111 protected IGroupTypeOperation groupTypeOperation;
112 protected InterfaceOperation interfaceOperation;
113 protected IElementOperation elementDao;
114 protected ComponentsUtils componentsUtils;
115 protected UserBusinessLogic userAdmin;
116 protected IGraphLockOperation graphLockOperation;
117 protected JanusGraphDao janusGraphDao;
118 protected JanusGraphGenericDao janusGraphGenericDao;
119 protected PropertyOperation propertyOperation;
120 protected AttributeOperation attributeOperation;
121 protected ApplicationDataTypeCache applicationDataTypeCache;
122 protected ToscaOperationFacade toscaOperationFacade;
123 protected ApplicationDataTypeCache dataTypeCache;
124 protected IGroupOperation groupOperation;
125 protected IGroupInstanceOperation groupInstanceOperation;
126 protected InterfaceLifecycleOperation interfaceLifecycleTypeOperation;
127 protected PolicyTypeOperation policyTypeOperation;
128 protected ArtifactsOperations artifactToscaOperation;
129 protected UserValidations userValidations;
131 DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance();
133 public BaseBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation,
134 IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
135 InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) {
136 this.elementDao = elementDao;
137 this.groupOperation = groupOperation;
138 this.groupInstanceOperation = groupInstanceOperation;
139 this.groupTypeOperation = groupTypeOperation;
140 this.interfaceOperation = interfaceOperation;
141 this.interfaceLifecycleTypeOperation = interfaceLifecycleTypeOperation;
142 this.artifactToscaOperation = artifactToscaOperation;
146 public void setUserAdmin(UserBusinessLogic userAdmin) {
147 this.userAdmin = userAdmin;
151 public void setUserValidations(UserValidations userValidations) {
152 this.userValidations = userValidations;
156 public void setComponentsUtils(ComponentsUtils componentsUtils) {
157 this.componentsUtils = componentsUtils;
161 public void setJanusGraphDao(JanusGraphDao janusGraphDao) {
162 this.janusGraphDao = janusGraphDao;
166 public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) {
167 this.applicationDataTypeCache = applicationDataTypeCache;
171 public void setJanusGraphGenericDao(JanusGraphGenericDao janusGraphGenericDao) {
172 this.janusGraphGenericDao = janusGraphGenericDao;
176 public void setGraphLockOperation(IGraphLockOperation graphLockOperation) {
177 this.graphLockOperation = graphLockOperation;
181 public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) {
182 this.toscaOperationFacade = toscaOperationFacade;
186 void setPolicyTypeOperation(PolicyTypeOperation policyTypeOperation) {
187 this.policyTypeOperation = policyTypeOperation;
191 public void setDataTypeCache(ApplicationDataTypeCache dataTypeCache) {
192 this.dataTypeCache = dataTypeCache;
196 public void setPropertyOperation(PropertyOperation propertyOperation) {
197 this.propertyOperation = propertyOperation;
201 public void setAttributeOperation(AttributeOperation attributeOperation) {
202 this.attributeOperation = attributeOperation;
205 User validateUserNotEmpty(User user, String ecompErrorContext) {
206 return userValidations.validateUserNotEmpty(user, ecompErrorContext);
209 protected User validateUserExists(String userId) {
210 return userValidations.validateUserExists(userId);
213 public User validateUserExists(User user) {
214 return userValidations.validateUserExists(user);
217 ActionStatus validateUserExistsActionStatus(String userId) {
218 return userValidations.validateUserExistsActionStatus(userId);
221 protected void validateUserRole(User user, List<Role> roles) {
222 userValidations.validateUserRole(user, roles);
225 protected void lockComponent(Component component, String ecompErrorContext) {
226 lockComponent(component.getUniqueId(), component, ecompErrorContext);
229 protected boolean isVolumeGroup(List<String> artifactsInGroup,List <ArtifactDefinition> deploymentArtifacts) {
230 for (String artifactId : artifactsInGroup) {
231 ArtifactDefinition artifactDef = ArtifactUtils.findArtifactInList(deploymentArtifacts, artifactId);
232 if (artifactDef != null
233 && artifactDef.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) {
240 protected void lockComponent(Component component, boolean shouldLock, String ecompErrorContext) {
242 lockComponent(component.getUniqueId(), component, ecompErrorContext);
246 protected void lockComponent(String componentId, Component component, String ecompErrorContext) {
247 ActionStatus lock = lockElement(componentId, component, ecompErrorContext);
248 if (lock!= ActionStatus.OK) {
249 logAndThrowComponentException(lock, component.getUniqueId(), component.getName());
253 protected void lockComponent(String componentId, Component component, boolean needLock, String ecompErrorContext) {
255 lockComponent(componentId, component, ecompErrorContext);
259 private ResponseFormat logAndThrowComponentException(ActionStatus status, String componentId, String name){
260 log.debug(FAILED_TO_LOCK_COMPONENT_ERROR, componentId, status);
261 throw new ByActionStatusComponentException(status, name);
264 private ActionStatus lockElement(String componentId, Component component, String ecompErrorContext) {
265 ComponentTypeEnum componentType = component.getComponentType();
266 NodeTypeEnum nodeType = componentType.getNodeType();
267 StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponent(componentId, nodeType);
269 if (lockResourceStatus == StorageOperationStatus.OK) {
270 return ActionStatus.OK;
272 BeEcompErrorManager.getInstance().logBeFailedLockObjectError(ecompErrorContext, nodeType.getName(), componentId);
273 return componentsUtils.convertFromStorageResponse(lockResourceStatus, componentType);
277 protected void unlockComponent(boolean failed, Component component, boolean inTransaction) {
278 if (component != null) {
279 ComponentTypeEnum componentType = component.getComponentType();
280 NodeTypeEnum nodeType = componentType.getNodeType();
281 if (!inTransaction) {
283 janusGraphDao.rollback();
285 janusGraphDao.commit();
289 graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
291 else log.debug("component is NULL");
294 protected void unlockComponent(boolean failed, Component component) {
295 unlockComponent(failed, component, false);
297 void unlockComponentById(boolean failed, String componentId) {
298 Either<Component, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(componentId);
299 if(component.isLeft()) {
300 unlockComponent(failed, component.left().value(), false);
304 <T> Boolean validateJsonBody(T bodyObject, Class<T> clazz) {
305 if (bodyObject == null) {
306 log.debug("Invalid JSON received for object of type {}", clazz.getSimpleName());
307 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
314 ComponentTypeEnum validateComponentType(String componentType) {
315 ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
316 if (componentTypeEnum == null) {
317 log.debug("Invalid component type {}", componentType);
318 throw new ByActionStatusComponentException(ActionStatus.UNSUPPORTED_ERROR, componentType);
320 return componentTypeEnum;
324 Component validateComponentExists(String componentId, ComponentTypeEnum componentType, ComponentParametersView filter) {
326 Either<Component, StorageOperationStatus> toscaElement = toscaOperationFacade.getToscaElement(componentId, filter == null ? new ComponentParametersView() : filter);
327 if(toscaElement.isRight()){
328 handleGetComponentError(componentId, componentType, toscaElement.right().value());
330 return validateComponentType(toscaElement.left().value(), componentType);
333 private Component validateComponentType(Component cmpt, ComponentTypeEnum componentType) {
334 if (componentType != cmpt.getComponentType()) {
335 log.debug("component {} is not of requested type {}", cmpt.getUniqueId(), componentType);
336 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, componentType));
341 <T extends PropertyDataDefinition> String updateInputPropertyObjectValue(T property) {
342 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypesEither = dataTypeCache.getAll();
343 if (allDataTypesEither.isRight()) {
344 JanusGraphOperationStatus status = allDataTypesEither.right().value();
345 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
346 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)));
348 Map<String, DataTypeDefinition> allDataTypes = allDataTypesEither.left().value();
349 String propertyType = property.getType();
350 String innerType = getInnerType(property);
351 // Specific Update Logic
352 Either<Object, Boolean> isValid =
353 propertyOperation.validateAndUpdatePropertyValue(propertyType, (String) property.getValue(), true,
354 innerType, allDataTypes);
355 String newValue = property.getValue();
356 if (isValid.isRight()) {
357 Boolean res = isValid.right().value();
358 if (Boolean.FALSE.equals(res)) {
359 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
362 Object object = isValid.left().value();
363 if (object != null) {
364 newValue = object.toString();
370 <T extends PropertyDataDefinition> String getInnerType(T property){
371 ToscaPropertyType type = ToscaPropertyType.isValidType(property.getType());
372 log.debug("#getInnerType - The type of the property {} is {}", property.getUniqueId(), property.getType());
373 String innerType = null;
374 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
375 if (property.getSchema() == null) {
376 log.debug(SCHEMA_DOESN_T_EXISTS_FOR_PROPERTY_OF_TYPE, type);
377 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE));
379 PropertyDataDefinition innerProperty = property.getSchema().getProperty();
380 if (innerProperty == null) {
381 log.debug(PROPERTY_IN_SCHEMA_DEFINITION_INSIDE_PROPERTY_OF_TYPE_DOESN_T_EXIST, type);
382 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE));
384 innerType = innerProperty.getType();
389 public void validateCanWorkOnComponent(Component component, String userId) {
390 ActionStatus actionStatus = ActionStatus.RESTRICTED_OPERATION;
391 // verify resource is not archived
392 if (component.isArchived() == true){
393 actionStatus = ActionStatus.COMPONENT_IS_ARCHIVED;
394 throw new ByActionStatusComponentException(actionStatus, component.getName());
397 if (component.getLifecycleState() != LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
398 log.debug("Component {} is not checked-out", component.getName());
399 throw new ByActionStatusComponentException(actionStatus);
402 // verify userId is not null
403 if (userId == null) {
404 log.debug("Current user userId is null");
405 throw new ByActionStatusComponentException(actionStatus);
408 // verify component last update user is the current user
409 String lastUpdaterUserId = component.getLastUpdaterUserId();
410 if (!userId.equals(lastUpdaterUserId)) {
411 log.debug("Current user is not last updater, last updater userId: {}, current user userId: {}", lastUpdaterUserId, userId);
412 throw new ByActionStatusComponentException(actionStatus);
415 // verify resource is not deleted
416 if (Boolean.TRUE.equals(component.getIsDeleted())) {
417 log.debug("Component {} is marked as deleted", component.getUniqueId());
418 throw new ByActionStatusComponentException(actionStatus);
424 ComponentTypeEnum getComponentTypeByParentComponentType(ComponentTypeEnum parentComponentType) {
425 switch (parentComponentType) {
428 return ComponentTypeEnum.RESOURCE;
430 return ComponentTypeEnum.SERVICE;
439 protected Map<String, DataTypeDefinition> getAllDataTypes(ApplicationDataTypeCache applicationDataTypeCache) {
440 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = applicationDataTypeCache.getAll();
441 if (allDataTypes.isRight()) {
442 JanusGraphOperationStatus operationStatus = allDataTypes.right().value();
443 if (operationStatus == JanusGraphOperationStatus.NOT_FOUND) {
444 BeEcompErrorManager.getInstance().logInternalDataError("FetchDataTypes", "Data types are not loaded", ErrorSeverity.ERROR);
445 throw new ByActionStatusComponentException(ActionStatus.DATA_TYPE_CANNOT_BE_EMPTY);
447 BeEcompErrorManager.getInstance().logInternalFlowError("FetchDataTypes", "Failed to fetch data types", ErrorSeverity.ERROR);
448 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
451 return allDataTypes.left().value();
454 Either<Boolean, ResponseFormat> validatePropertyDefaultValue(IComplexDefaultValue property, Map<String, DataTypeDefinition> dataTypes) {
456 String innerType = null;
457 if (!propertyOperation.isPropertyTypeValid(property)) {
458 log.info("Invalid type for property '{}' type '{}'", property.getName(), property.getType());
459 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
460 return Either.right(responseFormat);
462 type = property.getType();
463 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
464 ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property, dataTypes);
465 innerType = propertyInnerTypeValid.getLeft();
466 if (!propertyInnerTypeValid.getRight()) {
467 log.info("Invalid inner type for property '{}' type '{}', dataTypeCount '{}'", property.getName(), property.getType(), dataTypes.size());
468 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
469 return Either.right(responseFormat);
472 if (!propertyOperation.isPropertyDefaultValueValid(property, dataTypes)) {
473 log.info("Invalid default value for property '{}' type '{}'", property.getName(), property.getType());
474 ResponseFormat responseFormat;
475 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
476 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, property.getName(), type, innerType,
477 property.getDefaultValue());
479 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type,
480 property.getDefaultValue());
482 return Either.right(responseFormat);
485 return Either.left(true);
488 void validateComponentTypeEnum(ComponentTypeEnum componentTypeEnum, String errorContext, Wrapper<ResponseFormat> errorWrapper) {
489 if (componentTypeEnum == null) {
490 BeEcompErrorManager.getInstance().logInvalidInputError(errorContext, "invalid component type", ErrorSeverity.INFO);
491 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
496 protected void validateCanWorkOnComponent(String componentId, ComponentTypeEnum componentTypeEnum, String userId, Wrapper<ResponseFormat> errorWrapper) {
497 if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
498 log.info("Restricted operation for user {} on {} {}", userId, componentTypeEnum.getValue(), componentId);
499 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
504 void validateComponentLock(String componentId, ComponentTypeEnum componentTypeEnum, Wrapper<ResponseFormat> errorWrapper) {
505 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
506 if (lockStatus != StorageOperationStatus.OK) {
507 log.debug("Failed to lock {} {}", componentTypeEnum.getValue(), componentId);
508 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
513 protected ToscaPropertyType getType(String propertyType) {
514 return ToscaPropertyType.isValidType(propertyType);
517 void commitOrRollback(Either<?, ResponseFormat> result) {
518 if (result == null || result.isRight()) {
519 log.warn("operation failed. do rollback");
520 janusGraphDao.rollback();
522 log.debug("operation success. do commit");
523 janusGraphDao.commit();
527 protected Either<Boolean, ResponseFormat> lockComponentByName(String name, Component component, String ecompErrorContext) {
528 ComponentTypeEnum componentType = component.getComponentType();
529 NodeTypeEnum nodeType = componentType.getNodeType();
530 StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponentByName(name, nodeType);
532 if (lockResourceStatus == StorageOperationStatus.OK) {
533 return Either.left(true);
535 BeEcompErrorManager.getInstance().logBeFailedLockObjectError(ecompErrorContext, nodeType.getName(), name);
536 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(lockResourceStatus, componentType);
537 ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, component.getName());
538 log.debug(FAILED_TO_LOCK_COMPONENT_ERROR, name, actionStatus);
539 return Either.right(responseFormat);
543 protected Component validateComponentExistsByFilter(String componentId, ComponentTypeEnum componentType, ComponentParametersView componentParametersView) {
544 return toscaOperationFacade.getToscaElement(componentId, componentParametersView)
546 .on(err -> handleGetComponentError(componentId, componentType, err));
550 private Component handleGetComponentError(String componentId, ComponentTypeEnum componentType, StorageOperationStatus getComponentError) {
551 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentError, componentType);
552 log.debug("error fetching component with id {}. error status: {}", componentId, getComponentError);
553 throw new ByActionStatusComponentException(actionStatus, componentId);
557 static <T extends Enum<T>> boolean enumHasValueFilter(String name, Function<String, T> enumGetter, T... enumValues) {
558 T enumFound = enumGetter.apply(name);
559 return Arrays.asList(enumValues).contains(enumFound);
562 String validatePropValueBeforeCreate(IPropertyInputCommon property, String value, boolean isValidate,
563 Map<String, DataTypeDefinition> allDataTypes) {
564 String propertyType = property.getType();
565 String updatedInnerType = updateInnerType(property);
566 Either<Object, Boolean> isValid = validateAndUpdatePropertyValue(propertyType, value, isValidate, updatedInnerType, allDataTypes);
567 String newValue = value;
568 if (isValid.isRight()) {
569 Boolean res = isValid.right().value();
570 if (Boolean.FALSE.equals(res)) {
571 throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(
572 JanusGraphOperationStatus.ILLEGAL_ARGUMENT));
575 Object object = isValid.left().value();
576 if (object != null) {
577 newValue = object.toString();
580 ImmutablePair<String, Boolean> pair = validateAndUpdateRules(propertyType, property.getRules(), updatedInnerType, allDataTypes, isValidate);
581 log.trace("After validateAndUpdateRules. pair = {}", pair);
582 if (Boolean.FALSE.equals(pair.getRight())) {
583 BeEcompErrorManager.getInstance().logBeInvalidValueError(ADD_PROPERTY_VALUE, pair.getLeft(), property.getName(), propertyType);
584 throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(
585 JanusGraphOperationStatus.ILLEGAL_ARGUMENT));
590 private String updateInnerType(IPropertyInputCommon property) {
591 ToscaPropertyType type = ToscaPropertyType.isValidType(property.getType());
592 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
593 SchemaDefinition def = property.getSchema();
595 log.debug(SCHEMA_DOESN_T_EXISTS_FOR_PROPERTY_OF_TYPE, type);
596 failOnIllegalArgument();
598 PropertyDataDefinition propDef = def.getProperty();
599 if (propDef == null) {
600 log.debug(PROPERTY_IN_SCHEMA_DEFINITION_INSIDE_PROPERTY_OF_TYPE_DOESN_T_EXIST, type);
601 failOnIllegalArgument();
603 return propDef.getType();
608 private void failOnIllegalArgument() {
609 throw new ByActionStatusComponentException(
610 componentsUtils.convertFromStorageResponse(
611 DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
614 public Either<Object, Boolean> validateAndUpdatePropertyValue(String propertyType, String value, boolean isValidate, String innerType, Map<String, DataTypeDefinition> dataTypes) {
615 log.trace("Going to validate property value and its type. type = {}, value = {}", propertyType, value);
616 ToscaPropertyType type = getType(propertyType);
621 DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
622 ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, dataTypes);
623 if (Boolean.FALSE.equals(validateResult.right)) {
624 log.debug(THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID, value, propertyType);
625 return Either.right(false);
627 JsonElement jsonElement = validateResult.left;
628 String valueFromJsonElement = getValueFromJsonElement(jsonElement);
629 return Either.left(valueFromJsonElement);
631 log.trace("before validating property type {}", propertyType);
632 boolean isValidProperty = isValidValue(type, value, innerType, dataTypes);
633 if (!isValidProperty) {
634 log.debug(THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID, value, type);
635 return Either.right(false);
638 Object convertedValue = value;
639 if (!isEmptyValue(value) && isValidate) {
640 PropertyValueConverter converter = type.getConverter();
641 convertedValue = converter.convert(value, innerType, dataTypes);
643 return Either.left(convertedValue);
646 private ImmutablePair<String, Boolean> validateAndUpdateRules(String propertyType, List<PropertyRule> rules, String innerType, Map<String, DataTypeDefinition> dataTypes, boolean isValidate) {
648 if (rules == null || rules.isEmpty()) {
649 return ImmutablePair.of(null, true);
652 for (PropertyRule rule : rules) {
653 String value = rule.getValue();
654 Either<Object, Boolean> updateResult = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, dataTypes);
655 if (updateResult.isRight()) {
656 Boolean status = updateResult.right().value();
657 if (Boolean.FALSE.equals(status)) {
658 return ImmutablePair.of(value, status);
661 String newValue = null;
662 Object object = updateResult.left().value();
663 if (object != null) {
664 newValue = object.toString();
666 rule.setValue(newValue);
670 return ImmutablePair.of(null, true);
673 protected boolean isValidValue(ToscaPropertyType type, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
674 if (isEmptyValue(value)) {
678 PropertyTypeValidator validator = type.getValidator();
680 return validator.isValid(value, innerType, dataTypes);
683 public boolean isEmptyValue(String value) {
684 return value == null;
687 protected String getValueFromJsonElement(JsonElement jsonElement) {
688 if (jsonElement == null || jsonElement.isJsonNull()) {
691 if (jsonElement.toString().isEmpty()) {
694 return jsonElement.toString();
697 protected void rollbackWithException(ActionStatus actionStatus, String... params) {
698 janusGraphDao.rollback();
699 throw new ByActionStatusComponentException(actionStatus, params);
702 public <T extends ToscaDataDefinition> Either<List<T>, ResponseFormat> declareProperties(String userId, String componentId,
703 ComponentTypeEnum componentTypeEnum, ComponentInstInputsMap componentInstInputsMap) {
705 return Either.left(new ArrayList<>());
708 public <T extends PropertyDataDefinition> List<PropertyConstraint> setInputConstraint(T inputDefinition) {
709 if (StringUtils.isNotBlank(inputDefinition.getParentPropertyType())
710 && StringUtils.isNotBlank(inputDefinition.getSubPropertyInputPath())) {
711 return setConstraint(inputDefinition);
714 return Collections.emptyList();
717 private <T extends PropertyDataDefinition> List<PropertyConstraint> setConstraint(T inputDefinition) {
718 List<PropertyConstraint> constraints = new ArrayList<>();
719 String[] inputPathArr = inputDefinition.getSubPropertyInputPath().split("#");
720 if (inputPathArr.length > 1) {
721 inputPathArr = ArrayUtils.remove(inputPathArr, 0);
724 Map<String, DataTypeDefinition> dataTypeDefinitionMap =
725 applicationDataTypeCache.getAll().left().value();
727 String propertyType = inputDefinition.getParentPropertyType();
729 for (String anInputPathArr : inputPathArr) {
730 if (ToscaType.isPrimitiveType(propertyType)) {
732 dataTypeDefinitionMap.get(propertyType).getConstraints());
733 } else if (!ToscaType.isCollectionType(propertyType)) {
734 propertyType = setConstraintForComplexType(dataTypeDefinitionMap, propertyType, anInputPathArr,
742 private String setConstraintForComplexType(Map<String, DataTypeDefinition> dataTypeDefinitionMap,
744 String anInputPathArr,
745 List<PropertyConstraint> constraints) {
747 List<PropertyDefinition> propertyDefinitions =
748 dataTypeDefinitionMap.get(propertyType).getProperties();
749 for (PropertyDefinition propertyDefinition : propertyDefinitions) {
750 if (propertyDefinition.getName().equals(anInputPathArr)) {
751 if (ToscaType.isPrimitiveType(propertyDefinition.getType())) {
752 constraints.addAll(propertyDefinition.safeGetConstraints());
754 type = propertyDefinition.getType();
764 protected void rollbackWithException(StorageException e) {
765 janusGraphDao.rollback();
769 protected void rollbackWithException(ComponentException e) {
770 janusGraphDao.rollback();
774 protected void unlockRollbackWithException(Component component, RuntimeException e) {
775 janusGraphDao.rollback();
776 graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType().getNodeType());
780 protected void unlockWithCommit(Component component){
781 ComponentTypeEnum componentType = component.getComponentType();
782 NodeTypeEnum nodeType = componentType.getNodeType();
783 janusGraphDao.commit();
784 graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
787 protected ComponentInstance componentInstanceException(StorageOperationStatus storageOperationStatus) {
788 throw new StorageException(storageOperationStatus);
791 protected Component componentException(StorageOperationStatus storageOperationStatus) {
792 throw new StorageException(storageOperationStatus);
795 protected PolicyDefinition storageExceptionPolicyDefinition(StorageOperationStatus storageOperationStatus) {
796 throw new StorageException(storageOperationStatus);
799 protected PolicyDefinition componentExceptionPolicyDefinition(ResponseFormat responseFormat) {
800 throw new ByResponseFormatComponentException(responseFormat);
803 protected Component componentException(ResponseFormat responseFormat) {
804 throw new ByResponseFormatComponentException(responseFormat);
807 protected List<ComponentInstanceProperty> componentInstancePropertyListException(StorageOperationStatus storageOperationStatus) {
808 throw new StorageException(storageOperationStatus);
811 protected Component getComponent(final String componentId) throws BusinessLogicException {
813 final Either<Component, StorageOperationStatus> result = toscaOperationFacade.getToscaElement(componentId);
815 if (result.isRight()) {
816 final StorageOperationStatus errorStatus = result.right().value();
817 log.error(BUSINESS_PROCESS_ERROR, this.getClass().getName(),
818 "Failed to fetch component information by component id, error {}", errorStatus);
819 throw new BusinessLogicException(componentsUtils.getResponseFormat(
820 componentsUtils.convertFromStorageResponse(errorStatus)));
822 return result.left().value();