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 * ================================================================================
22 package org.openecomp.sdc.be.components.impl;
24 import static org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR;
25 import static org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode.DATA_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.validation.UserValidations;
42 import org.openecomp.sdc.be.config.BeEcompErrorManager;
43 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
44 import org.openecomp.sdc.be.dao.api.ActionStatus;
45 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphDao;
46 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao;
47 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
48 import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils;
49 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
50 import org.openecomp.sdc.be.datatypes.elements.PropertyRule;
51 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
52 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
53 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
54 import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
55 import org.openecomp.sdc.be.impl.ComponentsUtils;
56 import org.openecomp.sdc.be.model.ArtifactDefinition;
57 import org.openecomp.sdc.be.model.Component;
58 import org.openecomp.sdc.be.model.ComponentInstInputsMap;
59 import org.openecomp.sdc.be.model.ComponentInstOutputsMap;
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 - {}";
104 private static final Logger log = Logger.getLogger(BaseBusinessLogic.class);
105 private static final String EMPTY_VALUE = null;
106 private static final String SCHEMA_DOESN_T_EXISTS_FOR_PROPERTY_OF_TYPE = "Schema doesn't exists for property of type {}";
107 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";
108 private static final String ADD_PROPERTY_VALUE = "Add property value";
109 private static final String THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID = "The value {} of property from type {} is invalid";
110 private static final String INVALID_PROPERTY_TYPE = "The property 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 IGroupOperation groupOperation;
124 protected IGroupInstanceOperation groupInstanceOperation;
125 protected InterfaceLifecycleOperation interfaceLifecycleTypeOperation;
126 protected PolicyTypeOperation policyTypeOperation;
127 protected ArtifactsOperations artifactToscaOperation;
128 protected UserValidations userValidations;
129 DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance();
131 protected BaseBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
132 IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
133 InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) {
134 this.elementDao = elementDao;
135 this.groupOperation = groupOperation;
136 this.groupInstanceOperation = groupInstanceOperation;
137 this.groupTypeOperation = groupTypeOperation;
138 this.interfaceOperation = interfaceOperation;
139 this.interfaceLifecycleTypeOperation = interfaceLifecycleTypeOperation;
140 this.artifactToscaOperation = artifactToscaOperation;
144 static <T extends Enum<T>> boolean enumHasValueFilter(String name, Function<String, T> enumGetter, T... enumValues) {
145 T enumFound = enumGetter.apply(name);
146 return Arrays.asList(enumValues).contains(enumFound);
150 public void setUserAdmin(UserBusinessLogic userAdmin) {
151 this.userAdmin = userAdmin;
155 public void setUserValidations(UserValidations userValidations) {
156 this.userValidations = userValidations;
160 public void setComponentsUtils(ComponentsUtils componentsUtils) {
161 this.componentsUtils = componentsUtils;
165 public void setJanusGraphDao(JanusGraphDao janusGraphDao) {
166 this.janusGraphDao = janusGraphDao;
170 public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) {
171 this.applicationDataTypeCache = applicationDataTypeCache;
175 public void setJanusGraphGenericDao(JanusGraphGenericDao janusGraphGenericDao) {
176 this.janusGraphGenericDao = janusGraphGenericDao;
180 public void setGraphLockOperation(IGraphLockOperation graphLockOperation) {
181 this.graphLockOperation = graphLockOperation;
185 public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) {
186 this.toscaOperationFacade = toscaOperationFacade;
190 void setPolicyTypeOperation(PolicyTypeOperation policyTypeOperation) {
191 this.policyTypeOperation = policyTypeOperation;
195 public void setPropertyOperation(PropertyOperation propertyOperation) {
196 this.propertyOperation = propertyOperation;
200 public void setAttributeOperation(AttributeOperation attributeOperation) {
201 this.attributeOperation = attributeOperation;
204 User validateUserNotEmpty(User user, String ecompErrorContext) {
205 return userValidations.validateUserNotEmpty(user, ecompErrorContext);
208 protected User validateUserExists(String userId) {
209 return userValidations.validateUserExists(userId);
212 public User validateUserExists(User user) {
213 return userValidations.validateUserExists(user);
216 ActionStatus validateUserExistsActionStatus(String userId) {
217 return userValidations.validateUserExistsActionStatus(userId);
220 protected void validateUserRole(User user, List<Role> roles) {
221 userValidations.validateUserRole(user, roles);
224 protected void lockComponent(Component component, String ecompErrorContext) {
225 lockComponent(component.getUniqueId(), component, ecompErrorContext);
228 protected boolean isVolumeGroup(List<String> artifactsInGroup, List<ArtifactDefinition> deploymentArtifacts) {
229 for (String artifactId : artifactsInGroup) {
230 ArtifactDefinition artifactDef = ArtifactUtils.findArtifactInList(deploymentArtifacts, artifactId);
231 if (artifactDef != null && artifactDef.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) {
238 protected void lockComponent(Component component, boolean shouldLock, String ecompErrorContext) {
240 lockComponent(component.getUniqueId(), component, ecompErrorContext);
244 protected void lockComponent(String componentId, Component component, String ecompErrorContext) {
245 ActionStatus lock = lockElement(componentId, component, ecompErrorContext);
246 if (lock != ActionStatus.OK) {
247 logAndThrowComponentException(lock, component.getUniqueId(), component.getName());
251 protected void lockComponent(String componentId, Component component, boolean needLock, String ecompErrorContext) {
253 lockComponent(componentId, component, ecompErrorContext);
257 private ResponseFormat logAndThrowComponentException(ActionStatus status, String componentId, String name) {
258 log.debug(FAILED_TO_LOCK_COMPONENT_ERROR, componentId, status);
259 throw new ByActionStatusComponentException(status, name);
262 private ActionStatus lockElement(String componentId, Component component, String ecompErrorContext) {
263 ComponentTypeEnum componentType = component.getComponentType();
264 NodeTypeEnum nodeType = componentType.getNodeType();
265 StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponent(componentId, nodeType);
266 if (lockResourceStatus == StorageOperationStatus.OK) {
267 return ActionStatus.OK;
269 BeEcompErrorManager.getInstance().logBeFailedLockObjectError(ecompErrorContext, nodeType.getName(), componentId);
270 return componentsUtils.convertFromStorageResponse(lockResourceStatus, componentType);
274 protected void unlockComponent(boolean failed, Component component, boolean inTransaction) {
275 if (component != null) {
276 ComponentTypeEnum componentType = component.getComponentType();
277 NodeTypeEnum nodeType = componentType.getNodeType();
278 if (!inTransaction) {
280 janusGraphDao.rollback();
282 janusGraphDao.commit();
286 graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
288 log.debug("component is NULL");
292 protected void unlockComponent(boolean failed, Component component) {
293 unlockComponent(failed, component, false);
296 void unlockComponentById(boolean failed, String componentId) {
297 Either<Component, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(componentId);
298 if (component.isLeft()) {
299 unlockComponent(failed, component.left().value(), false);
303 <T> Boolean validateJsonBody(T bodyObject, Class<T> clazz) {
304 if (bodyObject == null) {
305 log.debug("Invalid JSON received for object of type {}", clazz.getSimpleName());
306 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
312 ComponentTypeEnum validateComponentType(String componentType) {
313 ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
314 if (componentTypeEnum == null) {
315 log.debug("Invalid component type {}", componentType);
316 throw new ByActionStatusComponentException(ActionStatus.UNSUPPORTED_ERROR, componentType);
318 return componentTypeEnum;
322 Component validateComponentExists(String componentId, ComponentTypeEnum componentType, ComponentParametersView filter) {
323 Either<Component, StorageOperationStatus> toscaElement = toscaOperationFacade
324 .getToscaElement(componentId, filter == null ? new ComponentParametersView() : filter);
325 if (toscaElement.isRight()) {
326 handleGetComponentError(componentId, componentType, toscaElement.right().value());
328 return validateComponentType(toscaElement.left().value(), componentType);
331 private Component validateComponentType(Component cmpt, ComponentTypeEnum componentType) {
332 if (componentType != cmpt.getComponentType()) {
333 log.debug("component {} is not of requested type {}", cmpt.getUniqueId(), componentType);
334 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, componentType));
339 <T extends PropertyDataDefinition> String getInnerType(T property) {
340 ToscaPropertyType type = ToscaPropertyType.isValidType(property.getType());
341 log.debug("#getInnerType - The type of the property {} is {}", property.getUniqueId(), property.getType());
342 String innerType = null;
343 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
344 if (property.getSchema() == null) {
345 log.debug(SCHEMA_DOESN_T_EXISTS_FOR_PROPERTY_OF_TYPE, type);
346 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE));
348 PropertyDataDefinition innerProperty = property.getSchema().getProperty();
349 if (innerProperty == null) {
350 log.debug(PROPERTY_IN_SCHEMA_DEFINITION_INSIDE_PROPERTY_OF_TYPE_DOESN_T_EXIST, type);
351 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE));
353 innerType = innerProperty.getType();
358 public void validateCanWorkOnComponent(Component component, String userId) {
359 ActionStatus actionStatus = ActionStatus.RESTRICTED_OPERATION;
360 // verify resource is not archived
361 if (Boolean.TRUE.equals(component.isArchived())) {
362 actionStatus = ActionStatus.COMPONENT_IS_ARCHIVED;
363 throw new ByActionStatusComponentException(actionStatus, component.getName());
365 if (component.getLifecycleState() != LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
366 log.debug("Component {} is not checked-out", component.getName());
367 throw new ByActionStatusComponentException(actionStatus);
369 // verify userId is not null
370 if (userId == null) {
371 log.debug("Current user userId is null");
372 throw new ByActionStatusComponentException(actionStatus);
374 // verify component last update user is the current user
375 String lastUpdaterUserId = component.getLastUpdaterUserId();
376 if (!userId.equals(lastUpdaterUserId)) {
377 log.debug("Current user is not last updater, last updater userId: {}, current user userId: {}", lastUpdaterUserId, userId);
378 throw new ByActionStatusComponentException(actionStatus);
380 // verify resource is not deleted
381 if (Boolean.TRUE.equals(component.getIsDeleted())) {
382 log.debug("Component {} is marked as deleted", component.getUniqueId());
383 throw new ByActionStatusComponentException(actionStatus);
387 ComponentTypeEnum getComponentTypeByParentComponentType(ComponentTypeEnum parentComponentType) {
388 switch (parentComponentType) {
391 return ComponentTypeEnum.RESOURCE;
393 return ComponentTypeEnum.SERVICE;
400 Either<Boolean, ResponseFormat> validatePropertyDefaultValue(IComplexDefaultValue property, Map<String, DataTypeDefinition> dataTypes) {
402 String innerType = null;
403 if (!propertyOperation.isPropertyTypeValid(property, dataTypes)) {
404 log.info("Invalid type for property '{}' type '{}'", property.getName(), property.getType());
405 ResponseFormat responseFormat = componentsUtils
406 .getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
407 return Either.right(responseFormat);
409 type = property.getType();
410 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
411 ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property, dataTypes);
412 innerType = propertyInnerTypeValid.getLeft();
413 if (Boolean.FALSE.equals(propertyInnerTypeValid.getRight())) {
414 log.info("Invalid inner type for property '{}' type '{}', dataTypeCount '{}'", property.getName(), property.getType(),
416 ResponseFormat responseFormat = componentsUtils
417 .getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
418 return Either.right(responseFormat);
421 if (!propertyOperation.isPropertyDefaultValueValid(property, dataTypes)) {
422 log.info("Invalid default value for property '{}' type '{}'", property.getName(), property.getType());
423 ResponseFormat responseFormat;
424 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
425 responseFormat = componentsUtils
426 .getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, property.getName(), type, innerType, property.getDefaultValue());
428 responseFormat = componentsUtils
429 .getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type, property.getDefaultValue());
431 return Either.right(responseFormat);
433 return Either.left(true);
436 void validateComponentTypeEnum(ComponentTypeEnum componentTypeEnum, String errorContext, Wrapper<ResponseFormat> errorWrapper) {
437 if (componentTypeEnum == null) {
438 BeEcompErrorManager.getInstance().logInvalidInputError(errorContext, "invalid component type", ErrorSeverity.INFO);
439 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
443 protected void validateCanWorkOnComponent(String componentId, ComponentTypeEnum componentTypeEnum, String userId,
444 Wrapper<ResponseFormat> errorWrapper) {
445 if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
446 log.info("Restricted operation for user {} on {} {}", userId, componentTypeEnum.getValue(), componentId);
447 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
451 void validateComponentLock(String componentId, ComponentTypeEnum componentTypeEnum, Wrapper<ResponseFormat> errorWrapper) {
452 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
453 if (lockStatus != StorageOperationStatus.OK) {
454 log.debug("Failed to lock {} {}", componentTypeEnum.getValue(), componentId);
455 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
459 protected ToscaPropertyType getType(String propertyType) {
460 return ToscaPropertyType.isValidType(propertyType);
463 void commitOrRollback(Either<?, ResponseFormat> result) {
464 if (result == null || result.isRight()) {
465 log.warn("operation failed. do rollback");
466 janusGraphDao.rollback();
468 log.debug("operation success. do commit");
469 janusGraphDao.commit();
473 protected Either<Boolean, ResponseFormat> lockComponentByName(String name, Component component, String ecompErrorContext) {
474 ComponentTypeEnum componentType = component.getComponentType();
475 NodeTypeEnum nodeType = componentType.getNodeType();
476 StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponentByName(name, nodeType);
477 if (lockResourceStatus == StorageOperationStatus.OK) {
478 return Either.left(true);
480 BeEcompErrorManager.getInstance().logBeFailedLockObjectError(ecompErrorContext, nodeType.getName(), name);
481 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(lockResourceStatus, componentType);
482 ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, component.getName());
483 log.debug(FAILED_TO_LOCK_COMPONENT_ERROR, name, actionStatus);
484 return Either.right(responseFormat);
488 protected Component validateComponentExistsByFilter(String componentId, ComponentTypeEnum componentType,
489 ComponentParametersView componentParametersView) {
490 return toscaOperationFacade.getToscaElement(componentId, componentParametersView).left()
491 .on(err -> handleGetComponentError(componentId, componentType, err));
494 private Component handleGetComponentError(String componentId, ComponentTypeEnum componentType, StorageOperationStatus getComponentError) {
495 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentError, componentType);
496 log.debug("error fetching component with id {}. error status: {}", componentId, getComponentError);
497 throw new ByActionStatusComponentException(actionStatus, componentId);
500 String validatePropValueBeforeCreate(IPropertyInputCommon property, String value, boolean isValidate,
501 Map<String, DataTypeDefinition> allDataTypes) {
502 String propertyType = property.getType();
503 String updatedInnerType = updateInnerType(property);
504 Either<Object, Boolean> isValid = validateAndUpdatePropertyValue(propertyType, value, isValidate, updatedInnerType, allDataTypes);
505 String newValue = value;
506 if (isValid.isRight()) {
507 Boolean res = isValid.right().value();
508 if (Boolean.FALSE.equals(res)) {
509 log.error(DATA_ERROR, this.getClass().getName(), "Dropping invalid value for property: {} , value: ", property, value);
513 Object object = isValid.left().value();
514 if (object != null) {
515 newValue = object.toString();
518 ImmutablePair<String, Boolean> pair = validateAndUpdateRules(propertyType, property.getRules(), updatedInnerType, allDataTypes, isValidate);
519 log.trace("After validateAndUpdateRules. pair = {}", pair);
520 if (Boolean.FALSE.equals(pair.getRight())) {
521 BeEcompErrorManager.getInstance().logBeInvalidValueError(ADD_PROPERTY_VALUE, pair.getLeft(), property.getName(), propertyType);
522 throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT));
527 private String updateInnerType(IPropertyInputCommon property) {
528 ToscaPropertyType type = ToscaPropertyType.isValidType(property.getType());
529 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
530 SchemaDefinition def = property.getSchema();
532 log.debug(SCHEMA_DOESN_T_EXISTS_FOR_PROPERTY_OF_TYPE, type);
533 failOnIllegalArgument();
535 PropertyDataDefinition propDef = def.getProperty();
536 if (propDef == null) {
537 log.debug(PROPERTY_IN_SCHEMA_DEFINITION_INSIDE_PROPERTY_OF_TYPE_DOESN_T_EXIST, type);
538 failOnIllegalArgument();
540 return propDef.getType();
545 private void failOnIllegalArgument() {
546 throw new ByActionStatusComponentException(componentsUtils
547 .convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
550 public Either<Object, Boolean> validateAndUpdatePropertyValue(String propertyType, String value, boolean isValidate, String innerType,
551 Map<String, DataTypeDefinition> dataTypes) {
552 log.trace("Going to validate property value and its type. type = {}, value = {}", propertyType, value);
553 ToscaPropertyType type = getType(propertyType);
556 DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
557 if (dataTypeDefinition == null) {
558 log.debug(INVALID_PROPERTY_TYPE, propertyType);
559 return Either.right(false);
561 ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter
562 .validateAndUpdate(value, dataTypeDefinition, dataTypes);
563 if (Boolean.FALSE.equals(validateResult.right)) {
564 log.debug(THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID, value, propertyType);
565 return Either.right(false);
567 JsonElement jsonElement = validateResult.left;
568 String valueFromJsonElement = getValueFromJsonElement(jsonElement);
569 return Either.left(valueFromJsonElement);
571 log.trace("before validating property type {}", propertyType);
572 boolean isValidProperty = isValidValue(type, value, innerType, dataTypes);
573 if (!isValidProperty) {
574 log.debug(THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID, value, type);
575 return Either.right(false);
578 Object convertedValue = value;
579 if (!isEmptyValue(value) && isValidate) {
580 PropertyValueConverter converter = type.getConverter();
581 convertedValue = converter.convert(value, innerType, dataTypes);
583 return Either.left(convertedValue);
586 private ImmutablePair<String, Boolean> validateAndUpdateRules(String propertyType, List<PropertyRule> rules, String innerType,
587 Map<String, DataTypeDefinition> dataTypes, boolean isValidate) {
588 if (rules == null || rules.isEmpty()) {
589 return ImmutablePair.of(null, true);
591 for (PropertyRule rule : rules) {
592 String value = rule.getValue();
593 Either<Object, Boolean> updateResult = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, dataTypes);
594 if (updateResult.isRight()) {
595 Boolean status = updateResult.right().value();
596 if (Boolean.FALSE.equals(status)) {
597 return ImmutablePair.of(value, status);
600 String newValue = null;
601 Object object = updateResult.left().value();
602 if (object != null) {
603 newValue = object.toString();
605 rule.setValue(newValue);
608 return ImmutablePair.of(null, true);
611 protected boolean isValidValue(ToscaPropertyType type, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
612 if (isEmptyValue(value)) {
615 PropertyTypeValidator validator = type.getValidator();
616 return validator.isValid(value, innerType, dataTypes);
619 public boolean isEmptyValue(String value) {
620 return value == null;
623 protected String getValueFromJsonElement(JsonElement jsonElement) {
624 if (jsonElement == null || jsonElement.isJsonNull()) {
627 if (jsonElement.toString().isEmpty()) {
630 return jsonElement.toString();
633 protected void rollbackWithException(ActionStatus actionStatus, String... params) {
634 janusGraphDao.rollback();
635 throw new ByActionStatusComponentException(actionStatus, params);
638 public <T extends ToscaDataDefinition> Either<List<T>, ResponseFormat> declareProperties(final String userId, final String componentId,
639 final ComponentTypeEnum componentTypeEnum,
640 final ComponentInstInputsMap componentInstInputsMap) {
641 return Either.left(new ArrayList<>());
644 public <T extends ToscaDataDefinition> Either<List<T>, ResponseFormat> declareAttributes(final String userId, final String componentId,
645 final ComponentTypeEnum componentTypeEnum,
646 final ComponentInstOutputsMap componentInstOutputsMap) {
647 return Either.left(new ArrayList<>());
650 public <T extends PropertyDataDefinition> List<PropertyConstraint> setInputConstraint(T inputDefinition) {
651 if (StringUtils.isNotBlank(inputDefinition.getParentPropertyType()) && StringUtils.isNotBlank(inputDefinition.getSubPropertyInputPath())) {
652 return setConstraint(inputDefinition);
654 return Collections.emptyList();
657 private <T extends PropertyDataDefinition> List<PropertyConstraint> setConstraint(T inputDefinition) {
658 List<PropertyConstraint> constraints = new ArrayList<>();
659 String[] inputPathArr = inputDefinition.getSubPropertyInputPath().split("#");
660 if (inputPathArr.length > 1) {
661 inputPathArr = ArrayUtils.remove(inputPathArr, 0);
663 final Map<String, DataTypeDefinition> dataTypeDefinitionMap =
664 componentsUtils.getAllDataTypes(applicationDataTypeCache, inputDefinition.getModel());
665 String propertyType = inputDefinition.getParentPropertyType();
666 for (String anInputPathArr : inputPathArr) {
667 if (ToscaType.isPrimitiveType(propertyType)) {
668 constraints.addAll(dataTypeDefinitionMap.get(propertyType).getConstraints());
669 } else if (!ToscaType.isCollectionType(propertyType)) {
670 propertyType = setConstraintForComplexType(dataTypeDefinitionMap, propertyType, anInputPathArr, constraints);
676 private String setConstraintForComplexType(Map<String, DataTypeDefinition> dataTypeDefinitionMap, String propertyType, String anInputPathArr,
677 List<PropertyConstraint> constraints) {
679 List<PropertyDefinition> propertyDefinitions = dataTypeDefinitionMap.get(propertyType).getProperties();
680 for (PropertyDefinition propertyDefinition : propertyDefinitions) {
681 if (propertyDefinition.getName().equals(anInputPathArr)) {
682 if (ToscaType.isPrimitiveType(propertyDefinition.getType())) {
683 constraints.addAll(propertyDefinition.safeGetConstraints());
685 type = propertyDefinition.getType();
693 protected void unlockRollbackWithException(Component component, RuntimeException e) {
694 janusGraphDao.rollback();
695 graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType().getNodeType());
699 protected void unlockWithCommit(Component component) {
700 ComponentTypeEnum componentType = component.getComponentType();
701 NodeTypeEnum nodeType = componentType.getNodeType();
702 janusGraphDao.commit();
703 graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
706 protected ComponentInstance componentInstanceException(StorageOperationStatus storageOperationStatus) {
707 throw new StorageException(storageOperationStatus);
710 protected Component componentException(StorageOperationStatus storageOperationStatus) {
711 throw new StorageException(storageOperationStatus);
714 protected PolicyDefinition componentExceptionPolicyDefinition(ResponseFormat responseFormat) {
715 throw new ByResponseFormatComponentException(responseFormat);
718 protected List<ComponentInstanceProperty> componentInstancePropertyListException(StorageOperationStatus storageOperationStatus) {
719 throw new StorageException(storageOperationStatus);
722 protected Component getComponent(final String componentId) throws BusinessLogicException {
723 final Either<Component, StorageOperationStatus> result = toscaOperationFacade.getToscaElement(componentId);
724 if (result.isRight()) {
725 final StorageOperationStatus errorStatus = result.right().value();
726 log.error(BUSINESS_PROCESS_ERROR, this.getClass().getName(), "Failed to fetch component information by component id, error {}",
728 throw new BusinessLogicException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
730 return result.left().value();
733 public String getComponentModelByComponentId(final String componentId) throws BusinessLogicException {
734 return getComponent(componentId).getModel();