fix ribbon.css
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / components / impl / BaseBusinessLogic.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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  * ================================================================================
21  */
22 package org.openecomp.sdc.be.components.impl;
23
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;
26
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;
33 import java.util.Map;
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;
100
101 public abstract class BaseBusinessLogic {
102
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();
130
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;
141     }
142
143     @SafeVarargs
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);
147     }
148
149     @Autowired
150     public void setUserAdmin(UserBusinessLogic userAdmin) {
151         this.userAdmin = userAdmin;
152     }
153
154     @Autowired
155     public void setUserValidations(UserValidations userValidations) {
156         this.userValidations = userValidations;
157     }
158
159     @Autowired
160     public void setComponentsUtils(ComponentsUtils componentsUtils) {
161         this.componentsUtils = componentsUtils;
162     }
163
164     @Autowired
165     public void setJanusGraphDao(JanusGraphDao janusGraphDao) {
166         this.janusGraphDao = janusGraphDao;
167     }
168
169     @Autowired
170     public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) {
171         this.applicationDataTypeCache = applicationDataTypeCache;
172     }
173
174     @Autowired
175     public void setJanusGraphGenericDao(JanusGraphGenericDao janusGraphGenericDao) {
176         this.janusGraphGenericDao = janusGraphGenericDao;
177     }
178
179     @Autowired
180     public void setGraphLockOperation(IGraphLockOperation graphLockOperation) {
181         this.graphLockOperation = graphLockOperation;
182     }
183
184     @Autowired
185     public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) {
186         this.toscaOperationFacade = toscaOperationFacade;
187     }
188
189     @Autowired
190     void setPolicyTypeOperation(PolicyTypeOperation policyTypeOperation) {
191         this.policyTypeOperation = policyTypeOperation;
192     }
193
194     @Autowired
195     public void setPropertyOperation(PropertyOperation propertyOperation) {
196         this.propertyOperation = propertyOperation;
197     }
198
199     @Autowired
200     public void setAttributeOperation(AttributeOperation attributeOperation) {
201         this.attributeOperation = attributeOperation;
202     }
203
204     User validateUserNotEmpty(User user, String ecompErrorContext) {
205         return userValidations.validateUserNotEmpty(user, ecompErrorContext);
206     }
207
208     protected User validateUserExists(String userId) {
209         return userValidations.validateUserExists(userId);
210     }
211
212     public User validateUserExists(User user) {
213         return userValidations.validateUserExists(user);
214     }
215
216     ActionStatus validateUserExistsActionStatus(String userId) {
217         return userValidations.validateUserExistsActionStatus(userId);
218     }
219
220     protected void validateUserRole(User user, List<Role> roles) {
221         userValidations.validateUserRole(user, roles);
222     }
223
224     protected void lockComponent(Component component, String ecompErrorContext) {
225         lockComponent(component.getUniqueId(), component, ecompErrorContext);
226     }
227
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())) {
232                 return true;
233             }
234         }
235         return false;
236     }
237
238     protected void lockComponent(Component component, boolean shouldLock, String ecompErrorContext) {
239         if (shouldLock) {
240             lockComponent(component.getUniqueId(), component, ecompErrorContext);
241         }
242     }
243
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());
248         }
249     }
250
251     protected void lockComponent(String componentId, Component component, boolean needLock, String ecompErrorContext) {
252         if (needLock) {
253             lockComponent(componentId, component, ecompErrorContext);
254         }
255     }
256
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);
260     }
261
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;
268         } else {
269             BeEcompErrorManager.getInstance().logBeFailedLockObjectError(ecompErrorContext, nodeType.getName(), componentId);
270             return componentsUtils.convertFromStorageResponse(lockResourceStatus, componentType);
271         }
272     }
273
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) {
279                 if (failed) {
280                     janusGraphDao.rollback();
281                 } else {
282                     janusGraphDao.commit();
283                 }
284             }
285             // unlock resource
286             graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
287         } else {
288             log.debug("component is NULL");
289         }
290     }
291
292     protected void unlockComponent(boolean failed, Component component) {
293         unlockComponent(failed, component, false);
294     }
295
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);
300         }
301     }
302
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);
307         } else {
308             return true;
309         }
310     }
311
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);
317         } else {
318             return componentTypeEnum;
319         }
320     }
321
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());
327         }
328         return validateComponentType(toscaElement.left().value(), componentType);
329     }
330
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));
335         }
336         return cmpt;
337     }
338
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));
347             }
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));
352             }
353             innerType = innerProperty.getType();
354         }
355         return innerType;
356     }
357
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());
364         }
365         if (component.getLifecycleState() != LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
366             log.debug("Component {} is not checked-out", component.getName());
367             throw new ByActionStatusComponentException(actionStatus);
368         }
369         // verify userId is not null
370         if (userId == null) {
371             log.debug("Current user userId is null");
372             throw new ByActionStatusComponentException(actionStatus);
373         }
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);
379         }
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);
384         }
385     }
386
387     ComponentTypeEnum getComponentTypeByParentComponentType(ComponentTypeEnum parentComponentType) {
388         switch (parentComponentType) {
389             case SERVICE:
390             case RESOURCE:
391                 return ComponentTypeEnum.RESOURCE;
392             case PRODUCT:
393                 return ComponentTypeEnum.SERVICE;
394             default:
395                 break;
396         }
397         return null;
398     }
399
400     Either<Boolean, ResponseFormat> validatePropertyDefaultValue(IComplexDefaultValue property, Map<String, DataTypeDefinition> dataTypes) {
401         String type;
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);
408         }
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(),
415                     dataTypes.size());
416                 ResponseFormat responseFormat = componentsUtils
417                     .getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
418                 return Either.right(responseFormat);
419             }
420         }
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());
427             } else {
428                 responseFormat = componentsUtils
429                     .getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type, property.getDefaultValue());
430             }
431             return Either.right(responseFormat);
432         }
433         return Either.left(true);
434     }
435
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));
440         }
441     }
442
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));
448         }
449     }
450
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)));
456         }
457     }
458
459     protected ToscaPropertyType getType(String propertyType) {
460         return ToscaPropertyType.isValidType(propertyType);
461     }
462
463     void commitOrRollback(Either<?, ResponseFormat> result) {
464         if (result == null || result.isRight()) {
465             log.warn("operation failed. do rollback");
466             janusGraphDao.rollback();
467         } else {
468             log.debug("operation success. do commit");
469             janusGraphDao.commit();
470         }
471     }
472
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);
479         } else {
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);
485         }
486     }
487
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));
492     }
493
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);
498     }
499
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);
510                 return "";
511             }
512         } else {
513             Object object = isValid.left().value();
514             if (object != null) {
515                 newValue = object.toString();
516             }
517         }
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));
523         }
524         return newValue;
525     }
526
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();
531             if (def == null) {
532                 log.debug(SCHEMA_DOESN_T_EXISTS_FOR_PROPERTY_OF_TYPE, type);
533                 failOnIllegalArgument();
534             }
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();
539             }
540             return propDef.getType();
541         }
542         return null;
543     }
544
545     private void failOnIllegalArgument() {
546         throw new ByActionStatusComponentException(componentsUtils
547             .convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
548     }
549
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);
554         if (isValidate) {
555             if (type == null) {
556                 DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
557                 if (dataTypeDefinition == null) {
558                     log.debug(INVALID_PROPERTY_TYPE, propertyType);
559                     return Either.right(false);
560                 }
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);
566                 }
567                 JsonElement jsonElement = validateResult.left;
568                 String valueFromJsonElement = getValueFromJsonElement(jsonElement);
569                 return Either.left(valueFromJsonElement);
570             }
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);
576             }
577         }
578         Object convertedValue = value;
579         if (!isEmptyValue(value) && isValidate) {
580             PropertyValueConverter converter = type.getConverter();
581             convertedValue = converter.convert(value, innerType, dataTypes);
582         }
583         return Either.left(convertedValue);
584     }
585
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);
590         }
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);
598                 }
599             } else {
600                 String newValue = null;
601                 Object object = updateResult.left().value();
602                 if (object != null) {
603                     newValue = object.toString();
604                 }
605                 rule.setValue(newValue);
606             }
607         }
608         return ImmutablePair.of(null, true);
609     }
610
611     protected boolean isValidValue(ToscaPropertyType type, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
612         if (isEmptyValue(value)) {
613             return true;
614         }
615         PropertyTypeValidator validator = type.getValidator();
616         return validator.isValid(value, innerType, dataTypes);
617     }
618
619     public boolean isEmptyValue(String value) {
620         return value == null;
621     }
622
623     protected String getValueFromJsonElement(JsonElement jsonElement) {
624         if (jsonElement == null || jsonElement.isJsonNull()) {
625             return EMPTY_VALUE;
626         }
627         if (jsonElement.toString().isEmpty()) {
628             return "";
629         }
630         return jsonElement.toString();
631     }
632
633     protected void rollbackWithException(ActionStatus actionStatus, String... params) {
634         janusGraphDao.rollback();
635         throw new ByActionStatusComponentException(actionStatus, params);
636     }
637
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<>());
642     }
643
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<>());
648     }
649
650     public <T extends PropertyDataDefinition> List<PropertyConstraint> setInputConstraint(T inputDefinition) {
651         if (StringUtils.isNotBlank(inputDefinition.getParentPropertyType()) && StringUtils.isNotBlank(inputDefinition.getSubPropertyInputPath())) {
652             return setConstraint(inputDefinition);
653         }
654         return Collections.emptyList();
655     }
656
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);
662         }
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);
671             }
672         }
673         return constraints;
674     }
675
676     private String setConstraintForComplexType(Map<String, DataTypeDefinition> dataTypeDefinitionMap, String propertyType, String anInputPathArr,
677                                                List<PropertyConstraint> constraints) {
678         String type = null;
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());
684                 } else {
685                     type = propertyDefinition.getType();
686                 }
687                 break;
688             }
689         }
690         return type;
691     }
692
693     protected void unlockRollbackWithException(Component component, RuntimeException e) {
694         janusGraphDao.rollback();
695         graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType().getNodeType());
696         throw e;
697     }
698
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);
704     }
705
706     protected ComponentInstance componentInstanceException(StorageOperationStatus storageOperationStatus) {
707         throw new StorageException(storageOperationStatus);
708     }
709
710     protected Component componentException(StorageOperationStatus storageOperationStatus) {
711         throw new StorageException(storageOperationStatus);
712     }
713
714     protected PolicyDefinition componentExceptionPolicyDefinition(ResponseFormat responseFormat) {
715         throw new ByResponseFormatComponentException(responseFormat);
716     }
717
718     protected List<ComponentInstanceProperty> componentInstancePropertyListException(StorageOperationStatus storageOperationStatus) {
719         throw new StorageException(storageOperationStatus);
720     }
721
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 {}",
727                 errorStatus);
728             throw new BusinessLogicException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
729         }
730         return result.left().value();
731     }
732
733     public String getComponentModelByComponentId(final String componentId) throws BusinessLogicException {
734         return getComponent(componentId).getModel();
735     }
736 }