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;
36 import org.apache.commons.lang3.ArrayUtils;
37 import org.apache.commons.lang3.StringUtils;
38 import org.apache.commons.lang3.tuple.ImmutablePair;
39 import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException;
40 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
41 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
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.JanusGraphDao;
47 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao;
48 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
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.ComponentInstOutputsMap;
61 import org.openecomp.sdc.be.model.ComponentInstance;
62 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
63 import org.openecomp.sdc.be.model.ComponentParametersView;
64 import org.openecomp.sdc.be.model.DataTypeDefinition;
65 import org.openecomp.sdc.be.model.IComplexDefaultValue;
66 import org.openecomp.sdc.be.model.IPropertyInputCommon;
67 import org.openecomp.sdc.be.model.LifecycleStateEnum;
68 import org.openecomp.sdc.be.model.PolicyDefinition;
69 import org.openecomp.sdc.be.model.PropertyConstraint;
70 import org.openecomp.sdc.be.model.PropertyDefinition;
71 import org.openecomp.sdc.be.model.User;
72 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
73 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
74 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
75 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
76 import org.openecomp.sdc.be.model.operations.StorageException;
77 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
78 import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
79 import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
80 import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
81 import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
82 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
83 import org.openecomp.sdc.be.model.operations.impl.AttributeOperation;
84 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
85 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
86 import org.openecomp.sdc.be.model.operations.impl.PolicyTypeOperation;
87 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
88 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
89 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
90 import org.openecomp.sdc.be.model.tosca.ToscaType;
91 import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter;
92 import org.openecomp.sdc.be.model.tosca.validators.DataTypeValidatorConverter;
93 import org.openecomp.sdc.be.model.tosca.validators.PropertyTypeValidator;
94 import org.openecomp.sdc.be.user.Role;
95 import org.openecomp.sdc.be.user.UserBusinessLogic;
96 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
97 import org.openecomp.sdc.common.datastructure.Wrapper;
98 import org.openecomp.sdc.common.log.wrappers.Logger;
99 import org.openecomp.sdc.exception.ResponseFormat;
100 import org.springframework.beans.factory.annotation.Autowired;
102 public abstract class BaseBusinessLogic {
104 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 private static final String INVALID_PROPERTY_TYPE = "The property type {} is invalid";
112 protected IGroupTypeOperation groupTypeOperation;
113 protected InterfaceOperation interfaceOperation;
114 protected IElementOperation elementDao;
115 protected ComponentsUtils componentsUtils;
116 protected UserBusinessLogic userAdmin;
117 protected IGraphLockOperation graphLockOperation;
118 protected JanusGraphDao janusGraphDao;
119 protected JanusGraphGenericDao janusGraphGenericDao;
120 protected PropertyOperation propertyOperation;
121 protected AttributeOperation attributeOperation;
123 protected ApplicationDataTypeCache applicationDataTypeCache;
124 protected ToscaOperationFacade toscaOperationFacade;
125 protected IGroupOperation groupOperation;
126 protected IGroupInstanceOperation groupInstanceOperation;
127 protected InterfaceLifecycleOperation interfaceLifecycleTypeOperation;
128 protected PolicyTypeOperation policyTypeOperation;
129 protected ArtifactsOperations artifactToscaOperation;
130 protected UserValidations userValidations;
131 private final DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance();
133 protected BaseBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
134 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 static <T extends Enum<T>> boolean enumHasValueFilter(String name, Function<String, T> enumGetter, T... enumValues) {
147 T enumFound = enumGetter.apply(name);
148 return Arrays.asList(enumValues).contains(enumFound);
152 public void setUserAdmin(UserBusinessLogic userAdmin) {
153 this.userAdmin = userAdmin;
157 public void setUserValidations(UserValidations userValidations) {
158 this.userValidations = userValidations;
162 public void setComponentsUtils(ComponentsUtils componentsUtils) {
163 this.componentsUtils = componentsUtils;
167 public void setJanusGraphDao(JanusGraphDao janusGraphDao) {
168 this.janusGraphDao = janusGraphDao;
172 public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) {
173 this.applicationDataTypeCache = applicationDataTypeCache;
177 public void setJanusGraphGenericDao(JanusGraphGenericDao janusGraphGenericDao) {
178 this.janusGraphGenericDao = janusGraphGenericDao;
182 public void setGraphLockOperation(IGraphLockOperation graphLockOperation) {
183 this.graphLockOperation = graphLockOperation;
187 public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) {
188 this.toscaOperationFacade = toscaOperationFacade;
192 void setPolicyTypeOperation(PolicyTypeOperation policyTypeOperation) {
193 this.policyTypeOperation = policyTypeOperation;
197 public void setPropertyOperation(PropertyOperation propertyOperation) {
198 this.propertyOperation = propertyOperation;
202 public void setAttributeOperation(AttributeOperation attributeOperation) {
203 this.attributeOperation = attributeOperation;
206 User validateUserNotEmpty(User user, String ecompErrorContext) {
207 return userValidations.validateUserNotEmpty(user, ecompErrorContext);
210 protected User validateUserExists(String userId) {
211 return userValidations.validateUserExists(userId);
214 public User validateUserExists(User user) {
215 return userValidations.validateUserExists(user);
218 ActionStatus validateUserExistsActionStatus(String userId) {
219 return userValidations.validateUserExistsActionStatus(userId);
222 protected void validateUserRole(User user, List<Role> roles) {
223 userValidations.validateUserRole(user, roles);
226 protected void lockComponent(Component component, String ecompErrorContext) {
227 lockComponent(component.getUniqueId(), component, ecompErrorContext);
230 protected boolean isVolumeGroup(List<String> artifactsInGroup, List<ArtifactDefinition> deploymentArtifacts) {
231 for (String artifactId : artifactsInGroup) {
232 ArtifactDefinition artifactDef = ArtifactUtils.findArtifactInList(deploymentArtifacts, artifactId);
233 if (artifactDef != null && 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);
268 if (lockResourceStatus == StorageOperationStatus.OK) {
269 return ActionStatus.OK;
271 BeEcompErrorManager.getInstance().logBeFailedLockObjectError(ecompErrorContext, nodeType.getName(), componentId);
272 return componentsUtils.convertFromStorageResponse(lockResourceStatus, componentType);
276 protected void unlockComponent(boolean failed, Component component, boolean inTransaction) {
277 if (component != null) {
278 ComponentTypeEnum componentType = component.getComponentType();
279 NodeTypeEnum nodeType = componentType.getNodeType();
280 if (!inTransaction) {
282 janusGraphDao.rollback();
284 janusGraphDao.commit();
288 graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
290 log.debug("component is NULL");
294 protected void unlockComponent(boolean failed, Component component) {
295 unlockComponent(failed, component, false);
298 void unlockComponentById(boolean failed, String componentId) {
299 Either<Component, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(componentId);
300 if (component.isLeft()) {
301 unlockComponent(failed, component.left().value(), false);
305 <T> Boolean validateJsonBody(T bodyObject, Class<T> clazz) {
306 if (bodyObject == null) {
307 log.debug("Invalid JSON received for object of type {}", clazz.getSimpleName());
308 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) {
325 Either<Component, StorageOperationStatus> toscaElement = toscaOperationFacade
326 .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 getInnerType(T property) {
342 ToscaPropertyType type = ToscaPropertyType.isValidType(property.getType());
343 log.debug("#getInnerType - The type of the property {} is {}", property.getUniqueId(), property.getType());
344 String innerType = null;
345 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
346 if (property.getSchema() == null) {
347 log.debug(SCHEMA_DOESN_T_EXISTS_FOR_PROPERTY_OF_TYPE, type);
348 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE));
350 PropertyDataDefinition innerProperty = property.getSchema().getProperty();
351 if (innerProperty == null) {
352 log.debug(PROPERTY_IN_SCHEMA_DEFINITION_INSIDE_PROPERTY_OF_TYPE_DOESN_T_EXIST, type);
353 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE));
355 innerType = innerProperty.getType();
360 public void validateCanWorkOnComponent(Component component, String userId) {
361 ActionStatus actionStatus = ActionStatus.RESTRICTED_OPERATION;
362 // verify resource is not archived
363 if (Boolean.TRUE.equals(component.isArchived())) {
364 actionStatus = ActionStatus.COMPONENT_IS_ARCHIVED;
365 throw new ByActionStatusComponentException(actionStatus, component.getName());
367 if (component.getLifecycleState() != LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
368 log.debug("Component {} is not checked-out", component.getName());
369 throw new ByActionStatusComponentException(actionStatus);
371 // verify userId is not null
372 if (userId == null) {
373 log.debug("Current user userId is null");
374 throw new ByActionStatusComponentException(actionStatus);
376 // verify component last update user is the current user
377 String lastUpdaterUserId = component.getLastUpdaterUserId();
378 if (!userValidations.isSameUser(userId, lastUpdaterUserId)) {
379 log.debug("Current user is not last updater, last updater userId: {}, current user userId: {}", lastUpdaterUserId, userId);
380 throw new ByActionStatusComponentException(actionStatus);
382 // verify resource is not deleted
383 if (Boolean.TRUE.equals(component.getIsDeleted())) {
384 log.debug("Component {} is marked as deleted", component.getUniqueId());
385 throw new ByActionStatusComponentException(actionStatus);
389 ComponentTypeEnum getComponentTypeByParentComponentType(ComponentTypeEnum parentComponentType) {
390 switch (parentComponentType) {
393 return ComponentTypeEnum.RESOURCE;
395 return ComponentTypeEnum.SERVICE;
402 Either<Boolean, ResponseFormat> validatePropertyDefaultValue(IComplexDefaultValue property, Map<String, DataTypeDefinition> dataTypes) {
404 String innerType = null;
405 if (!propertyOperation.isPropertyTypeValid(property, dataTypes)) {
406 log.info("Invalid type for property '{}' type '{}'", property.getName(), property.getType());
407 ResponseFormat responseFormat = componentsUtils
408 .getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
409 return Either.right(responseFormat);
411 type = property.getType();
412 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
413 ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property, dataTypes);
414 innerType = propertyInnerTypeValid.getLeft();
415 if (Boolean.FALSE.equals(propertyInnerTypeValid.getRight())) {
416 log.info("Invalid inner type for property '{}' type '{}', dataTypeCount '{}'", property.getName(), property.getType(),
418 ResponseFormat responseFormat = componentsUtils
419 .getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
420 return Either.right(responseFormat);
423 if (!propertyOperation.isPropertyDefaultValueValid(property, dataTypes)) {
424 log.info("Invalid default value for property '{}' type '{}'", property.getName(), property.getType());
425 ResponseFormat responseFormat;
426 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
427 responseFormat = componentsUtils
428 .getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, property.getName(), type, innerType, property.getDefaultValue());
430 responseFormat = componentsUtils
431 .getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type, property.getDefaultValue());
433 return Either.right(responseFormat);
435 return Either.left(true);
438 void validateComponentTypeEnum(ComponentTypeEnum componentTypeEnum, String errorContext, Wrapper<ResponseFormat> errorWrapper) {
439 if (componentTypeEnum == null) {
440 BeEcompErrorManager.getInstance().logInvalidInputError(errorContext, "invalid component type", ErrorSeverity.INFO);
441 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
445 protected void validateCanWorkOnComponent(String componentId, ComponentTypeEnum componentTypeEnum, String userId,
446 Wrapper<ResponseFormat> errorWrapper) {
447 if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
448 log.info("Restricted operation for user {} on {} {}", userId, componentTypeEnum.getValue(), componentId);
449 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
453 void validateComponentLock(String componentId, ComponentTypeEnum componentTypeEnum, Wrapper<ResponseFormat> errorWrapper) {
454 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
455 if (lockStatus != StorageOperationStatus.OK) {
456 log.debug("Failed to lock {} {}", componentTypeEnum.getValue(), componentId);
457 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
461 protected ToscaPropertyType getType(String propertyType) {
462 return ToscaPropertyType.isValidType(propertyType);
465 void commitOrRollback(Either<?, ResponseFormat> result) {
466 if (result == null || result.isRight()) {
467 log.warn("operation failed. do rollback");
468 janusGraphDao.rollback();
470 log.debug("operation success. do commit");
471 janusGraphDao.commit();
475 protected Either<Boolean, ResponseFormat> lockComponentByName(String name, Component component, String ecompErrorContext) {
476 ComponentTypeEnum componentType = component.getComponentType();
477 NodeTypeEnum nodeType = componentType.getNodeType();
478 StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponentByName(name, nodeType);
479 if (lockResourceStatus == StorageOperationStatus.OK) {
480 return Either.left(true);
482 BeEcompErrorManager.getInstance().logBeFailedLockObjectError(ecompErrorContext, nodeType.getName(), name);
483 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(lockResourceStatus, componentType);
484 ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, component.getName());
485 log.debug(FAILED_TO_LOCK_COMPONENT_ERROR, name, actionStatus);
486 return Either.right(responseFormat);
490 protected Component validateComponentExistsByFilter(String componentId, ComponentTypeEnum componentType,
491 ComponentParametersView componentParametersView) {
492 return toscaOperationFacade.getToscaElement(componentId, componentParametersView).left()
493 .on(err -> handleGetComponentError(componentId, componentType, err));
496 private Component handleGetComponentError(String componentId, ComponentTypeEnum componentType, StorageOperationStatus getComponentError) {
497 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentError, componentType);
498 log.debug("error fetching component with id {}. error status: {}", componentId, getComponentError);
499 throw new ByActionStatusComponentException(actionStatus, componentId);
502 String validatePropValueBeforeCreate(IPropertyInputCommon property, String value, boolean isValidate,
503 Map<String, DataTypeDefinition> allDataTypes) {
504 String propertyType = property.getType();
505 String updatedInnerType = updateInnerType(property);
506 Either<Object, Boolean> isValid = validateAndUpdatePropertyValue(propertyType, value, isValidate, updatedInnerType, allDataTypes);
507 String newValue = value;
508 if (isValid.isRight()) {
509 Boolean res = isValid.right().value();
510 if (Boolean.FALSE.equals(res)) {
511 log.error(DATA_ERROR, this.getClass().getName(), "Dropping invalid value for property: {} , value: ", property, value);
515 Object object = isValid.left().value();
516 if (object != null) {
517 newValue = object.toString();
520 ImmutablePair<String, Boolean> pair = validateAndUpdateRules(propertyType, property.getRules(), updatedInnerType, allDataTypes, isValidate);
521 log.trace("After validateAndUpdateRules. pair = {}", pair);
522 if (Boolean.FALSE.equals(pair.getRight())) {
523 BeEcompErrorManager.getInstance().logBeInvalidValueError(ADD_PROPERTY_VALUE, pair.getLeft(), property.getName(), propertyType);
524 throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT));
529 private String updateInnerType(IPropertyInputCommon property) {
530 ToscaPropertyType type = ToscaPropertyType.isValidType(property.getType());
531 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
532 SchemaDefinition def = property.getSchema();
534 log.debug(SCHEMA_DOESN_T_EXISTS_FOR_PROPERTY_OF_TYPE, type);
535 failOnIllegalArgument();
537 PropertyDataDefinition propDef = def.getProperty();
538 if (propDef == null) {
539 log.debug(PROPERTY_IN_SCHEMA_DEFINITION_INSIDE_PROPERTY_OF_TYPE_DOESN_T_EXIST, type);
540 failOnIllegalArgument();
542 return propDef.getType();
547 private void failOnIllegalArgument() {
548 throw new ByActionStatusComponentException(componentsUtils
549 .convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
552 public Either<Object, Boolean> validateAndUpdatePropertyValue(String propertyType, String value, boolean isValidate, String innerType,
553 Map<String, DataTypeDefinition> dataTypes) {
554 log.trace("Going to validate property value and its type. type = {}, value = {}", propertyType, value);
555 ToscaPropertyType type = getType(propertyType);
558 DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
559 if (dataTypeDefinition == null) {
560 log.debug(INVALID_PROPERTY_TYPE, propertyType);
561 return Either.right(false);
563 ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter
564 .validateAndUpdate(value, dataTypeDefinition, dataTypes);
565 if (Boolean.FALSE.equals(validateResult.right)) {
566 log.debug(THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID, value, propertyType);
567 return Either.right(false);
569 JsonElement jsonElement = validateResult.left;
570 String valueFromJsonElement = getValueFromJsonElement(jsonElement);
571 return Either.left(valueFromJsonElement);
573 log.trace("before validating property type {}", propertyType);
574 boolean isValidProperty = isValidValue(type, value, innerType, dataTypes);
575 if (!isValidProperty) {
576 log.debug(THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID, value, type);
577 return Either.right(false);
580 Object convertedValue = value;
581 if (!isEmptyValue(value) && isValidate) {
582 PropertyValueConverter converter = type.getConverter();
583 convertedValue = converter.convert(value, innerType, dataTypes);
585 return Either.left(convertedValue);
588 private ImmutablePair<String, Boolean> validateAndUpdateRules(String propertyType, List<PropertyRule> rules, String innerType,
589 Map<String, DataTypeDefinition> dataTypes, boolean isValidate) {
590 if (rules == null || rules.isEmpty()) {
591 return ImmutablePair.of(null, true);
593 for (PropertyRule rule : rules) {
594 String value = rule.getValue();
595 Either<Object, Boolean> updateResult = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, dataTypes);
596 if (updateResult.isRight()) {
597 Boolean status = updateResult.right().value();
598 if (Boolean.FALSE.equals(status)) {
599 return ImmutablePair.of(value, status);
602 String newValue = null;
603 Object object = updateResult.left().value();
604 if (object != null) {
605 newValue = object.toString();
607 rule.setValue(newValue);
610 return ImmutablePair.of(null, true);
613 protected boolean isValidValue(ToscaPropertyType type, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
614 if (isEmptyValue(value)) {
617 PropertyTypeValidator validator = type.getValidator();
618 return validator.isValid(value, innerType, dataTypes);
621 public boolean isEmptyValue(String value) {
622 return value == null;
625 protected String getValueFromJsonElement(JsonElement jsonElement) {
626 if (jsonElement == null || jsonElement.isJsonNull()) {
629 if (jsonElement.toString().isEmpty()) {
632 return jsonElement.toString();
635 protected void rollbackWithException(ActionStatus actionStatus, String... params) {
636 janusGraphDao.rollback();
637 throw new ByActionStatusComponentException(actionStatus, params);
640 public <T extends ToscaDataDefinition> Either<List<T>, ResponseFormat> declareProperties(final String userId, final String componentId,
641 final ComponentTypeEnum componentTypeEnum,
642 final ComponentInstInputsMap componentInstInputsMap) {
643 return Either.left(new ArrayList<>());
646 public <T extends ToscaDataDefinition> Either<List<T>, ResponseFormat> declareAttributes(final String userId, final String componentId,
647 final ComponentTypeEnum componentTypeEnum,
648 final ComponentInstOutputsMap componentInstOutputsMap) {
649 return Either.left(new ArrayList<>());
652 public <T extends PropertyDataDefinition> List<PropertyConstraint> setInputConstraint(T inputDefinition) {
653 if (StringUtils.isNotBlank(inputDefinition.getParentPropertyType()) && StringUtils.isNotBlank(inputDefinition.getSubPropertyInputPath())) {
654 return setConstraint(inputDefinition);
656 return Collections.emptyList();
659 private <T extends PropertyDataDefinition> List<PropertyConstraint> setConstraint(T inputDefinition) {
660 List<PropertyConstraint> constraints = new ArrayList<>();
661 String[] inputPathArr = inputDefinition.getSubPropertyInputPath().split("#");
662 if (inputPathArr.length > 1) {
663 inputPathArr = ArrayUtils.remove(inputPathArr, 0);
665 final Map<String, DataTypeDefinition> dataTypeDefinitionMap =
666 componentsUtils.getAllDataTypes(applicationDataTypeCache, inputDefinition.getModel());
667 String propertyType = inputDefinition.getParentPropertyType();
668 for (String anInputPathArr : inputPathArr) {
669 if (ToscaType.isPrimitiveType(propertyType)) {
670 constraints.addAll(dataTypeDefinitionMap.get(propertyType).getConstraints());
671 } else if (!ToscaType.isCollectionType(propertyType)) {
672 propertyType = setConstraintForComplexType(dataTypeDefinitionMap, propertyType, anInputPathArr, constraints);
678 private String setConstraintForComplexType(Map<String, DataTypeDefinition> dataTypeDefinitionMap, String propertyType, String anInputPathArr,
679 List<PropertyConstraint> constraints) {
681 List<PropertyDefinition> propertyDefinitions = dataTypeDefinitionMap.get(propertyType).getProperties();
682 for (PropertyDefinition propertyDefinition : propertyDefinitions) {
683 if (propertyDefinition.getName().equals(anInputPathArr)) {
684 if (ToscaType.isPrimitiveType(propertyDefinition.getType())) {
685 constraints.addAll(propertyDefinition.safeGetConstraints());
687 type = propertyDefinition.getType();
695 protected void unlockRollbackWithException(Component component, RuntimeException e) {
696 janusGraphDao.rollback();
697 graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType().getNodeType());
701 protected void unlockWithCommit(Component component) {
702 ComponentTypeEnum componentType = component.getComponentType();
703 NodeTypeEnum nodeType = componentType.getNodeType();
704 janusGraphDao.commit();
705 graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
708 protected ComponentInstance componentInstanceException(StorageOperationStatus storageOperationStatus) {
709 throw new StorageException(storageOperationStatus);
712 protected Component componentException(StorageOperationStatus storageOperationStatus) {
713 throw new StorageException(storageOperationStatus);
716 protected PolicyDefinition componentExceptionPolicyDefinition(ResponseFormat responseFormat) {
717 throw new ByResponseFormatComponentException(responseFormat);
720 protected List<ComponentInstanceProperty> componentInstancePropertyListException(StorageOperationStatus storageOperationStatus) {
721 throw new StorageException(storageOperationStatus);
724 protected Component getComponent(final String componentId) throws BusinessLogicException {
725 final Either<Component, StorageOperationStatus> result = toscaOperationFacade.getToscaElement(componentId);
726 if (result.isRight()) {
727 final StorageOperationStatus errorStatus = result.right().value();
728 log.error(BUSINESS_PROCESS_ERROR, this.getClass().getName(), "Failed to fetch component information by component id, error {}",
730 throw new BusinessLogicException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
732 return result.left().value();
735 public String getComponentModelByComponentId(final String componentId) throws BusinessLogicException {
736 return getComponent(componentId).getModel();