cd0f8a0f61acd0328db98c63b1d3ee4b8afa2bab
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / components / impl / ResourceBusinessLogic.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  */
20
21 package org.openecomp.sdc.be.components.impl;
22
23 import static java.util.stream.Collectors.joining;
24 import static java.util.stream.Collectors.toList;
25 import static java.util.stream.Collectors.toMap;
26 import static java.util.stream.Collectors.toSet;
27 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
28 import static org.apache.commons.collections.MapUtils.isEmpty;
29 import static org.apache.commons.collections.MapUtils.isNotEmpty;
30 import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaStringElement;
31 import static org.openecomp.sdc.be.components.impl.ImportUtils.getPropertyJsonStringValue;
32 import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN;
33 import static org.openecomp.sdc.common.api.Constants.DEFAULT_GROUP_VF_MODULE;
34
35 import com.google.common.annotations.VisibleForTesting;
36 import fj.data.Either;
37 import java.util.ArrayList;
38 import java.util.Collection;
39 import java.util.EnumMap;
40 import java.util.HashMap;
41 import java.util.HashSet;
42 import java.util.Iterator;
43 import java.util.List;
44 import java.util.ListIterator;
45 import java.util.Map;
46 import java.util.Map.Entry;
47 import java.util.Optional;
48 import java.util.Set;
49 import java.util.function.Function;
50 import java.util.regex.Pattern;
51 import java.util.stream.Collectors;
52 import javax.servlet.ServletContext;
53 import org.apache.commons.codec.binary.Base64;
54 import org.apache.commons.collections.CollectionUtils;
55 import org.apache.commons.collections.MapUtils;
56 import org.apache.commons.collections4.ListUtils;
57 import org.apache.commons.lang.StringUtils;
58 import org.apache.commons.lang3.tuple.ImmutablePair;
59 import org.openecomp.sdc.be.catalog.enums.ChangeTypeEnum;
60 import org.openecomp.sdc.be.components.csar.CsarArtifactsAndGroupsBusinessLogic;
61 import org.openecomp.sdc.be.components.csar.CsarBusinessLogic;
62 import org.openecomp.sdc.be.components.csar.CsarInfo;
63 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
64 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationInfo;
65 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
66 import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException;
67 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
68 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
69 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
70 import org.openecomp.sdc.be.components.impl.utils.CINodeFilterUtils;
71 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
72 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
73 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
74 import org.openecomp.sdc.be.components.merge.TopologyComparator;
75 import org.openecomp.sdc.be.components.merge.property.PropertyDataValueMergeBusinessLogic;
76 import org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic;
77 import org.openecomp.sdc.be.components.merge.utils.MergeInstanceUtils;
78 import org.openecomp.sdc.be.components.property.PropertyConstraintsUtils;
79 import org.openecomp.sdc.be.components.validation.component.ComponentContactIdValidator;
80 import org.openecomp.sdc.be.components.validation.component.ComponentDescriptionValidator;
81 import org.openecomp.sdc.be.components.validation.component.ComponentIconValidator;
82 import org.openecomp.sdc.be.components.validation.component.ComponentNameValidator;
83 import org.openecomp.sdc.be.components.validation.component.ComponentProjectCodeValidator;
84 import org.openecomp.sdc.be.components.validation.component.ComponentTagsValidator;
85 import org.openecomp.sdc.be.components.validation.component.ComponentValidator;
86 import org.openecomp.sdc.be.config.BeEcompErrorManager;
87 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
88 import org.openecomp.sdc.be.config.ConfigurationManager;
89 import org.openecomp.sdc.be.dao.api.ActionStatus;
90 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
91 import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
92 import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils;
93 import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
94 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
95 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
96 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
97 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
98 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
99 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
100 import org.openecomp.sdc.be.datatypes.elements.ToscaArtifactDataDefinition;
101 import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum;
102 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
103 import org.openecomp.sdc.be.datatypes.enums.CreatedFrom;
104 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
105 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
106 import org.openecomp.sdc.be.impl.ComponentsUtils;
107 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
108 import org.openecomp.sdc.be.info.NodeTypeInfoToUpdateArtifacts;
109 import org.openecomp.sdc.be.model.ArtifactDefinition;
110 import org.openecomp.sdc.be.model.CapabilityDefinition;
111 import org.openecomp.sdc.be.model.CapabilityRequirementRelationship;
112 import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
113 import org.openecomp.sdc.be.model.Component;
114 import org.openecomp.sdc.be.model.ComponentInstance;
115 import org.openecomp.sdc.be.model.ComponentInstanceInput;
116 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
117 import org.openecomp.sdc.be.model.ComponentParametersView;
118 import org.openecomp.sdc.be.model.DataTypeDefinition;
119 import org.openecomp.sdc.be.model.GroupDefinition;
120 import org.openecomp.sdc.be.model.InputDefinition;
121 import org.openecomp.sdc.be.model.InterfaceDefinition;
122 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
123 import org.openecomp.sdc.be.model.LifecycleStateEnum;
124 import org.openecomp.sdc.be.model.NodeTypeInfo;
125 import org.openecomp.sdc.be.model.Operation;
126 import org.openecomp.sdc.be.model.ParsedToscaYamlInfo;
127 import org.openecomp.sdc.be.model.PropertyDefinition;
128 import org.openecomp.sdc.be.model.RelationshipImpl;
129 import org.openecomp.sdc.be.model.RelationshipInfo;
130 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
131 import org.openecomp.sdc.be.model.RequirementDefinition;
132 import org.openecomp.sdc.be.model.Resource;
133 import org.openecomp.sdc.be.model.UploadArtifactInfo;
134 import org.openecomp.sdc.be.model.UploadCapInfo;
135 import org.openecomp.sdc.be.model.UploadComponentInstanceInfo;
136 import org.openecomp.sdc.be.model.UploadInfo;
137 import org.openecomp.sdc.be.model.UploadNodeFilterInfo;
138 import org.openecomp.sdc.be.model.UploadPropInfo;
139 import org.openecomp.sdc.be.model.UploadReqInfo;
140 import org.openecomp.sdc.be.model.UploadResourceInfo;
141 import org.openecomp.sdc.be.model.User;
142 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
143 import org.openecomp.sdc.be.model.category.CategoryDefinition;
144 import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
145 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
146 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
147 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.exception.ToscaOperationException;
148 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
149 import org.openecomp.sdc.be.model.operations.StorageException;
150 import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation;
151 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
152 import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
153 import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
154 import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
155 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
156 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
157 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
158 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
159 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
160 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
161 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
162 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
163 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
164 import org.openecomp.sdc.be.tosca.CsarUtils;
165 import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo;
166 import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
167 import org.openecomp.sdc.be.user.UserBusinessLogic;
168 import org.openecomp.sdc.be.utils.CommonBeUtils;
169 import org.openecomp.sdc.be.utils.TypeUtils;
170 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
171 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
172 import org.openecomp.sdc.common.api.Constants;
173 import org.openecomp.sdc.common.datastructure.Wrapper;
174 import org.openecomp.sdc.common.kpi.api.ASDCKpiApi;
175 import org.openecomp.sdc.common.log.elements.LoggerSupportability;
176 import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
177 import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions;
178 import org.openecomp.sdc.common.log.enums.StatusCode;
179 import org.openecomp.sdc.common.log.wrappers.Logger;
180 import org.openecomp.sdc.common.util.GeneralUtility;
181 import org.openecomp.sdc.common.util.ValidationUtils;
182 import org.openecomp.sdc.exception.ResponseFormat;
183 import org.springframework.beans.factory.annotation.Autowired;
184 import org.springframework.context.annotation.Lazy;
185 import org.springframework.web.context.WebApplicationContext;
186 import org.yaml.snakeyaml.DumperOptions;
187 import org.yaml.snakeyaml.Yaml;
188
189 @org.springframework.stereotype.Component("resourceBusinessLogic")
190 public class ResourceBusinessLogic extends ComponentBusinessLogic {
191
192         private static final String DELETE_RESOURCE = "Delete Resource";
193         private static final String IN_RESOURCE = "  in resource {} ";
194         private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
195         public static final String INITIAL_VERSION = "0.1";
196         private static final Logger log = Logger.getLogger(ResourceBusinessLogic.class);
197         private static final String CERTIFICATION_ON_IMPORT = "certification on import";
198         private static final String CREATE_RESOURCE = "Create Resource";
199         private static final String VALIDATE_DERIVED_BEFORE_UPDATE = "validate derived before update";
200         private static final String CATEGORY_IS_EMPTY = "Resource category is empty";
201         private static final String CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES = "Create Resource - validateCapabilityTypesCreate";
202         private static final String COMPONENT_INSTANCE_WITH_NAME = "component instance with name ";
203         private static final String COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE = "component instance with name {}  in resource {} ";
204         public LoggerSupportability loggerSupportability=LoggerSupportability.getLogger(ResourceBusinessLogic.class.getName());
205
206
207     private IInterfaceLifecycleOperation interfaceTypeOperation;
208     private LifecycleBusinessLogic lifecycleBusinessLogic;
209
210     private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
211     private final ResourceImportManager resourceImportManager;
212     private final InputsBusinessLogic inputsBusinessLogic;
213     private final CompositionBusinessLogic compositionBusinessLogic;
214     private final ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic;
215     private final CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic;
216     private final MergeInstanceUtils mergeInstanceUtils;
217     private final UiComponentDataConverter uiComponentDataConverter;
218     private final CsarBusinessLogic csarBusinessLogic;
219     private final PropertyBusinessLogic propertyBusinessLogic;
220
221         @Autowired
222     public ResourceBusinessLogic(IElementOperation elementDao,
223         IGroupOperation groupOperation,
224         IGroupInstanceOperation groupInstanceOperation,
225         IGroupTypeOperation groupTypeOperation,
226         GroupBusinessLogic groupBusinessLogic,
227         InterfaceOperation interfaceOperation,
228         InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
229         ArtifactsBusinessLogic artifactsBusinessLogic,
230         ComponentInstanceBusinessLogic componentInstanceBusinessLogic, @Lazy ResourceImportManager resourceImportManager,
231         InputsBusinessLogic inputsBusinessLogic, CompositionBusinessLogic compositionBusinessLogic,
232         ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic,
233         CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic, MergeInstanceUtils mergeInstanceUtils,
234         UiComponentDataConverter uiComponentDataConverter, CsarBusinessLogic csarBusinessLogic,
235         ArtifactsOperations artifactToscaOperation, PropertyBusinessLogic propertyBusinessLogic,
236                 ComponentContactIdValidator componentContactIdValidator,
237                 ComponentNameValidator componentNameValidator, ComponentTagsValidator componentTagsValidator,
238                 ComponentValidator componentValidator,
239                 ComponentIconValidator componentIconValidator,
240                 ComponentProjectCodeValidator componentProjectCodeValidator,
241                 ComponentDescriptionValidator componentDescriptionValidator) {
242         super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic,
243             interfaceOperation, interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation,
244                                 componentContactIdValidator, componentNameValidator, componentTagsValidator, componentValidator,
245                                 componentIconValidator, componentProjectCodeValidator, componentDescriptionValidator);
246         this.componentInstanceBusinessLogic = componentInstanceBusinessLogic;
247         this.resourceImportManager = resourceImportManager;
248         this.inputsBusinessLogic = inputsBusinessLogic;
249         this.compositionBusinessLogic = compositionBusinessLogic;
250         this.resourceDataMergeBusinessLogic = resourceDataMergeBusinessLogic;
251         this.csarArtifactsAndGroupsBusinessLogic = csarArtifactsAndGroupsBusinessLogic;
252         this.mergeInstanceUtils = mergeInstanceUtils;
253         this.uiComponentDataConverter = uiComponentDataConverter;
254         this.csarBusinessLogic = csarBusinessLogic;
255         this.propertyBusinessLogic = propertyBusinessLogic;
256     }
257
258         @Autowired
259         private ICapabilityTypeOperation capabilityTypeOperation;
260
261         @Autowired
262         private TopologyComparator topologyComparator;
263
264         @Autowired
265         private ComponentValidator componentValidator;
266
267         @Autowired
268         private PropertyDataValueMergeBusinessLogic propertyDataValueMergeBusinessLogic;
269
270         @Autowired
271         private SoftwareInformationBusinessLogic softwareInformationBusinessLogic;
272
273
274         public LifecycleBusinessLogic getLifecycleBusinessLogic() {
275                 return lifecycleBusinessLogic;
276         }
277
278     @Autowired
279     public void setLifecycleManager(LifecycleBusinessLogic lifecycleBusinessLogic) {
280         this.lifecycleBusinessLogic = lifecycleBusinessLogic;
281     }
282
283         @VisibleForTesting
284         protected void setComponentValidator(ComponentValidator componentValidator) {
285                 this.componentValidator = componentValidator;
286         }
287
288         public IElementOperation getElementDao() {
289                 return elementDao;
290         }
291
292         public void setElementDao(IElementOperation elementDao) {
293                 this.elementDao = elementDao;
294         }
295
296         public UserBusinessLogic getUserAdmin() {
297                 return this.userAdmin;
298         }
299
300         @Autowired
301         public void setUserAdmin(UserBusinessLogic userAdmin) {
302                 this.userAdmin = userAdmin;
303         }
304
305         public ComponentsUtils getComponentsUtils() {
306                 return this.componentsUtils;
307         }
308
309         @Autowired
310         public void setComponentsUtils(ComponentsUtils componentsUtils) {
311                 this.componentsUtils = componentsUtils;
312         }
313
314         public ArtifactsBusinessLogic getArtifactsManager() {
315                 return artifactsBusinessLogic;
316         }
317
318         public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) {
319                 this.artifactsBusinessLogic = artifactsManager;
320         }
321
322         public ApplicationDataTypeCache getApplicationDataTypeCache() {
323                 return applicationDataTypeCache;
324         }
325
326     @Autowired
327     public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) {
328         this.applicationDataTypeCache = applicationDataTypeCache;
329     }
330
331     @Autowired
332     public void setInterfaceTypeOperation(IInterfaceLifecycleOperation interfaceTypeOperation) {
333         this.interfaceTypeOperation = interfaceTypeOperation;
334     }
335
336         /**
337          * the method returns a list of all the resources that are certified, the
338          * returned resources are only abstract or only none abstract according to
339          * the given param
340          *
341          * @param getAbstract
342          * @param userId
343          *            TODO
344          * @return
345          */
346         public List<Resource> getAllCertifiedResources(boolean getAbstract, HighestFilterEnum highestFilter,
347                                                                                                    String userId) {
348                 User user = validateUserExists(userId);
349                 Boolean isHighest = null;
350                 switch (highestFilter) {
351                         case ALL:
352                                 break;
353                         case HIGHEST_ONLY:
354                                 isHighest = true;
355                                 break;
356                         case NON_HIGHEST_ONLY:
357                                 isHighest = false;
358                                 break;
359                         default:
360                                 break;
361                 }
362                 Either<List<Resource>, StorageOperationStatus> getResponse = toscaOperationFacade
363                                 .getAllCertifiedResources(getAbstract, isHighest);
364
365                 if (getResponse.isRight()) {
366                         throw new StorageException(getResponse.right()
367                                         .value());
368                 }
369
370                 return getResponse.left()
371                                 .value();
372         }
373
374         public Either<Map<String, Boolean>, ResponseFormat> validateResourceNameExists(String resourceName,
375                                                                                                                                                                    ResourceTypeEnum resourceTypeEnum, String userId) {
376
377                 validateUserExists(userId);
378
379                 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
380                                 .validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE);
381                 // DE242223
382         janusGraphDao.commit();
383
384                 if (dataModelResponse.isLeft()) {
385                         Map<String, Boolean> result = new HashMap<>();
386                         result.put("isValid", dataModelResponse.left()
387                                         .value());
388                         log.debug("validation was successfully performed.");
389                         return Either.left(result);
390                 }
391
392                 ResponseFormat responseFormat = componentsUtils
393                                 .getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right()
394                                                 .value()));
395
396                 return Either.right(responseFormat);
397         }
398
399         public Resource createResource(Resource resource, AuditingActionEnum auditingAction, User user,
400                                                                    Map<String, byte[]> csarUIPayload, String payloadName) {
401                 validateResourceBeforeCreate(resource, user, false);
402                 String csarUUID = payloadName == null ? resource.getCsarUUID() : payloadName;
403                 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Starting to create resource from CSAR by user {} ", user.getUserId());
404                 if (StringUtils.isNotEmpty(csarUUID)) {
405                         csarBusinessLogic.validateCsarBeforeCreate(resource, auditingAction, user, csarUUID);
406                         log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID);
407
408                         Resource createResourceFromCsar = createResourceFromCsar(resource, user, csarUIPayload, csarUUID);
409                         return updateCatalog(createResourceFromCsar, ChangeTypeEnum.LIFECYCLE).left()
410                                         .map(r -> (Resource) r)
411                                         .left()
412                                         .value();
413                 }
414
415                 final Resource createResourceByDao = createResourceByDao(resource, user, auditingAction, false, false);
416                 return updateCatalog(createResourceByDao, ChangeTypeEnum.LIFECYCLE).left()
417                                 .map(r -> (Resource) r)
418                                 .left()
419                                 .value();
420         }
421
422         public Resource validateAndUpdateResourceFromCsar(Resource resource, User user, Map<String, byte[]> csarUIPayload,
423                                                                                                           String payloadName, String resourceUniqueId) {
424                 String csarUUID = payloadName;
425                 String csarVersion = null;
426                 Resource updatedResource = null;
427                 if (payloadName == null) {
428                         csarUUID = resource.getCsarUUID();
429                         csarVersion = resource.getCsarVersion();
430                 }
431                 if (csarUUID != null && !csarUUID.isEmpty()) {
432                         Resource oldResource = getResourceByUniqueId(resourceUniqueId);
433                         validateCsarUuidMatching(oldResource, resource, csarUUID, resourceUniqueId, user);
434                         validateCsarIsNotAlreadyUsed(oldResource, resource, csarUUID, user);
435                         if (oldResource != null && ValidationUtils.hasBeenCertified(oldResource.getVersion())) {
436                                 overrideImmutableMetadata(oldResource, resource);
437                         }
438                         validateResourceBeforeCreate(resource, user, false);
439                         String oldCsarVersion = oldResource.getCsarVersion();
440                         log.debug("CsarUUID is {} - going to update resource with UniqueId {} from CSAR", csarUUID,
441                                         resourceUniqueId);
442                         // (on boarding flow): If the update includes same csarUUID and
443                         // same csarVersion as already in the VF - no need to import the
444                         // csar (do only metadata changes if there are).
445                         if (csarVersion != null && oldCsarVersion != null && oldCsarVersion.equals(csarVersion)) {
446                                 updatedResource = updateResourceMetadata(resourceUniqueId, resource, oldResource, user, false);
447                         } else {
448                                 updatedResource = updateResourceFromCsar(oldResource, resource, user,
449                                                 AuditingActionEnum.UPDATE_RESOURCE_METADATA, false, csarUIPayload, csarUUID);
450                         }
451                 } else {
452                         log.debug("Failed to update resource {}, csarUUID or payload name is missing", resource.getSystemName());
453                         ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CSAR_UUID,
454                                         resource.getName());
455                         componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.CREATE_RESOURCE);
456                         throw new ByActionStatusComponentException(ActionStatus.MISSING_CSAR_UUID, resource.getName());
457                 }
458                 return updatedResource;
459         }
460
461         private void validateCsarIsNotAlreadyUsed(Resource oldResource, Resource resource, String csarUUID, User user) {
462                 // (on boarding flow): If the update includes a csarUUID: verify this
463                 // csarUUID is not in use by another VF, If it is - use same error as
464                 // above:
465                 // "Error: The VSP with UUID %1 was already imported for VF %2. Please
466                 // select another or update the existing VF." %1 - csarUUID, %2 - VF
467                 // name
468                 Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = toscaOperationFacade
469                                 .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUUID, resource.getSystemName());
470                 if (resourceLinkedToCsarRes.isRight()) {
471                         if (StorageOperationStatus.NOT_FOUND != resourceLinkedToCsarRes.right().value()) {
472                                 log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID,
473                                                 resource.getSystemName());
474                                 throw new StorageException(resourceLinkedToCsarRes.right()
475                                                 .value());
476                         }
477                 } else if (!resourceLinkedToCsarRes.left()
478                                 .value()
479                                 .getUniqueId()
480                                 .equals(oldResource.getUniqueId())
481                                 && !resourceLinkedToCsarRes.left()
482                                 .value()
483                                 .getName()
484                                 .equals(oldResource.getName())) {
485                         ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID,
486                                         resourceLinkedToCsarRes.left()
487                                                         .value()
488                                                         .getName());
489                         componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
490                         throw new ByActionStatusComponentException(ActionStatus.VSP_ALREADY_EXISTS, csarUUID, resourceLinkedToCsarRes.left()
491                                         .value()
492                                         .getName());
493                 }
494         }
495
496         private void validateCsarUuidMatching(Resource resource, Resource oldResource, String csarUUID,
497                                                                                   String resourceUniqueId, User user) {
498                 // (on boarding flow): If the update includes csarUUID which is
499                 // different from the csarUUID of the VF - fail with
500                 // error: "Error: Resource %1 cannot be updated using since it is linked
501                 // to a different VSP" %1 - VF name
502                 String oldCsarUUID = oldResource.getCsarUUID();
503                 if (oldCsarUUID != null && !oldCsarUUID.isEmpty() && !csarUUID.equals(oldCsarUUID)) {
504                         log.debug(
505                                         "Failed to update resource with UniqueId {} using Csar {}, since the resource is linked to a different VSP {}",
506                                         resourceUniqueId, csarUUID, oldCsarUUID);
507                         ResponseFormat errorResponse = componentsUtils.getResponseFormat(
508                                         ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
509                         componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
510                         throw new ByActionStatusComponentException(ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID,
511                                         oldCsarUUID);
512                 }
513         }
514
515         private Resource getResourceByUniqueId(String resourceUniqueId) {
516                 Either<Resource, StorageOperationStatus> oldResourceRes = toscaOperationFacade
517                                 .getToscaFullElement(resourceUniqueId);
518                 if (oldResourceRes.isRight()) {
519                         log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId,
520                                         oldResourceRes.right()
521                                                         .value());
522                         throw new StorageException(oldResourceRes.right()
523                                         .value());
524                 }
525                 return oldResourceRes.left()
526                                 .value();
527         }
528
529         private void overrideImmutableMetadata(Resource oldResource, Resource resource) {
530                 resource.setName(oldResource.getName());
531                 resource.setIcon(oldResource.getIcon());
532                 resource.setTags(oldResource.getTags());
533                 resource.setCategories(oldResource.getCategories());
534                 resource.setDerivedFrom(oldResource.getDerivedFrom());
535         }
536
537         private Resource updateResourceFromCsar(Resource oldResource, Resource newResource, User user,
538                                                                                         AuditingActionEnum updateResource, boolean inTransaction, Map<String, byte[]> csarUIPayload,
539                                                                                         String csarUUID) {
540                 Resource updatedResource = null;
541                 validateLifecycleState(oldResource, user);
542                 String lockedResourceId = oldResource.getUniqueId();
543                 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
544                 CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(newResource, oldResource, user, csarUIPayload, csarUUID);
545                 lockComponent(lockedResourceId, oldResource, "update Resource From Csar");
546
547                 Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
548
549                 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
550                                 nodeTypesInfo, csarInfo, oldResource);
551                 if (findNodeTypesArtifactsToHandleRes.isRight()) {
552                         log.debug("failed to find node types for update with artifacts during import csar {}. ",
553                                         csarInfo.getCsarUUID());
554                         throw new ByResponseFormatComponentException(findNodeTypesArtifactsToHandleRes.right()
555                                         .value());
556                 }
557                 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes
558                                 .left()
559                                 .value();
560                 try {
561                         updatedResource = updateResourceFromYaml(oldResource, newResource, updateResource, createdArtifacts,
562                                         csarInfo.getMainTemplateName(), csarInfo.getMainTemplateContent(), csarInfo, nodeTypesInfo,
563                                         nodeTypesArtifactsToHandle, null, false);
564
565                 } catch (ComponentException | StorageException e) {
566                         rollback(inTransaction, newResource, createdArtifacts, null);
567                         throw e;
568         }
569         finally {
570             janusGraphDao.commit();
571                         log.debug("unlock resource {}", lockedResourceId);
572                         graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
573                 }
574                 return updatedResource;
575
576         }
577
578         private void validateLifecycleState(Resource oldResource, User user) {
579                 if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT == oldResource.getLifecycleState()
580                                 && !oldResource.getLastUpdaterUserId()
581                                 .equals(user.getUserId())) {
582                         log.debug(
583                                         "#validateLifecycleState - Current user is not last updater, last updater userId: {}, current user userId: {}",
584                                         oldResource.getLastUpdaterUserId(), user.getUserId());
585                         throw new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION);
586                 }
587         }
588
589         private Resource updateResourceFromYaml(Resource oldResource, Resource newResource, AuditingActionEnum actionEnum,
590                                                                                         List<ArtifactDefinition> createdArtifacts, String yamlFileName, String yamlFileContent, CsarInfo csarInfo,
591                                                                                         Map<String, NodeTypeInfo> nodeTypesInfo,
592                                                                                         Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
593                                                                                         String nodeName, boolean isNested) {
594                 boolean inTransaction = true;
595                 boolean shouldLock = false;
596                 Resource preparedResource = null;
597                 ParsedToscaYamlInfo uploadComponentInstanceInfoMap;
598                 try {
599                         uploadComponentInstanceInfoMap = csarBusinessLogic.getParsedToscaYamlInfo(yamlFileContent, yamlFileName,
600                                         nodeTypesInfo, csarInfo, nodeName);
601                         Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.getInstances();
602             if (MapUtils.isEmpty(instances) && newResource.getResourceType() != ResourceTypeEnum.PNF) {
603                 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlFileName);
604             }
605             preparedResource = updateExistingResourceByImport(newResource, oldResource, csarInfo.getModifier(),
606                                         inTransaction, shouldLock, isNested).left;
607                         log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent);
608                         handleResourceGenericType(preparedResource);
609                         handleNodeTypes(yamlFileName, preparedResource, yamlFileContent, shouldLock, nodeTypesArtifactsToHandle,
610                                         createdArtifacts, nodeTypesInfo, csarInfo, nodeName);
611                         preparedResource = createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs());
612                         Map<String, Resource> existingNodeTypesByResourceNames = new HashMap<>();
613                         preparedResource = createResourceInstances(yamlFileName, preparedResource, oldResource, instances, csarInfo.getCreatedNodes(), existingNodeTypesByResourceNames);
614                         preparedResource = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, oldResource, instances, existingNodeTypesByResourceNames);
615                 } catch (ComponentException e) {
616                         ResponseFormat responseFormat = e.getResponseFormat() == null
617                                         ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
618                         log.debug("#updateResourceFromYaml - failed to update newResource from yaml {} .The error is {}", yamlFileName,
619                                         responseFormat);
620                         componentsUtils.auditResource(responseFormat, csarInfo.getModifier(),
621                                         preparedResource == null ? oldResource : preparedResource, actionEnum);
622                         throw e;
623                 } catch (StorageException e) {
624                         ResponseFormat responseFormat = componentsUtils
625                                         .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
626                         log.debug("#updateResourceFromYaml - failed to update newResource from yaml {} .The error is {}", yamlFileName,
627                                         responseFormat);
628                         componentsUtils.auditResource(responseFormat, csarInfo.getModifier(),
629                                         preparedResource == null ? oldResource : preparedResource, actionEnum);
630                         throw e;
631                 }
632                 Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
633                                 .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.getGroups(),
634                                                 preparedResource.getSystemName());
635                 if (validateUpdateVfGroupNamesRes.isRight()) {
636
637                         throw new ByResponseFormatComponentException(validateUpdateVfGroupNamesRes.right()
638                                         .value());
639                 }
640                 // add groups to newResource
641                 Map<String, GroupDefinition> groups;
642
643                 if (!validateUpdateVfGroupNamesRes.left()
644                                 .value()
645                                 .isEmpty()) {
646                         groups = validateUpdateVfGroupNamesRes.left()
647                                         .value();
648                 } else {
649                         groups = uploadComponentInstanceInfoMap.getGroups();
650                 }
651                 handleGroupsProperties(preparedResource, groups);
652                 Either<Boolean, ActionStatus> isTopologyChanged = topologyComparator.isTopologyChanged(oldResource, preparedResource);
653
654                 preparedResource = updateGroupsOnResource(preparedResource, groups);
655
656                 NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
657                                 nodeTypesArtifactsToHandle);
658
659                 Either<Resource, ResponseFormat> updateArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.UPDATE,
660                                 createdArtifacts, yamlFileName, csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts,
661                                 inTransaction, shouldLock);
662                 if (updateArtifactsEither.isRight()) {
663                         log.debug("failed to update artifacts {}", updateArtifactsEither.right()
664                                         .value());
665                         throw new ByResponseFormatComponentException(updateArtifactsEither.right()
666                                         .value());
667                 }
668                 preparedResource = getResourceWithGroups(updateArtifactsEither.left()
669                                 .value()
670                                 .getUniqueId());
671
672                 updateGroupsName(oldResource, preparedResource, isTopologyChanged.left().value());
673                 updateResourceInstancesNames(oldResource, csarInfo, preparedResource, isTopologyChanged.left().value());
674
675                 preparedResource = getResourceWithGroups(preparedResource.getUniqueId());
676
677                 updateVolumeGroup(preparedResource);
678
679                 ActionStatus mergingPropsAndInputsStatus = resourceDataMergeBusinessLogic.mergeResourceEntities(oldResource, preparedResource);
680                 if (mergingPropsAndInputsStatus != ActionStatus.OK) {
681                         ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus,
682                                         preparedResource);
683                         throw new ByResponseFormatComponentException(responseFormat);
684                 }
685                 compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier()
686                                 .getUserId());
687                 return preparedResource;
688         }
689
690         protected void updateVolumeGroup(Resource preparedResource) {
691                 List<GroupDefinition> groups = preparedResource.safeGetGroups();
692                 for (GroupDefinition group : groups) {
693                         Map<String, ArtifactDefinition> createdNewArtifacts = preparedResource.getDeploymentArtifacts();
694                         if (DEFAULT_GROUP_VF_MODULE.equals(group.getType())) {
695                                 List<PropertyDataDefinition> volumePropList = group.getProperties().stream().filter(p -> "volume_group".equals(p.getName())).collect(Collectors.toList());
696                                 if (!volumePropList.isEmpty()) {
697                                         PropertyDataDefinition volumeProp = volumePropList.get(0);
698                                         if (volumeProp != null) {
699                                                 boolean isVolumeGroup = isVolumeGroup(group.getArtifacts(), new ArrayList<>(createdNewArtifacts.values()));
700
701                                                 if (!volumePropList.get(0).getValue().equals(String.valueOf(isVolumeGroup))) {
702                                                         volumeProp.setValue(String.valueOf(isVolumeGroup));
703                                                         volumeProp.setDefaultValue(String.valueOf(isVolumeGroup));
704                                                 }
705                                         }
706                                 }
707                         }
708                 }
709         }
710
711         private void updateGroupsName(Resource oldResource, Resource preparedResource,  boolean isTopologyChanged) {
712                 if (CollectionUtils.isNotEmpty(oldResource.getGroups())
713                                 && CollectionUtils.isNotEmpty(preparedResource.getGroups())) {
714                         Map<String, String> oldGroups = oldResource.getGroups()
715                                         .stream()
716                                         .collect(toMap(GroupDataDefinition::getInvariantName, GroupDataDefinition::getName));
717
718                         List<GroupDefinition> updatedGroups = preparedResource.getGroups()
719                                         .stream()
720                                         .filter(group -> oldGroups.containsKey(group.getInvariantName()) && !group.getName()
721                                                         .equals(oldGroups.get(group.getInvariantName())))
722                                         .collect(toList());
723
724                         if (CollectionUtils.isNotEmpty(updatedGroups)) {
725                                 if (isTopologyChanged) {
726                                         updatedGroups.stream().filter(group -> !group.isVspOriginated())
727                                                         .forEach(group -> group.setName(oldGroups.get(group.getInvariantName())));
728                                 } else {
729                                         updatedGroups.forEach(group -> group.setName(oldGroups.get(group.getInvariantName())));
730                                 }
731                                 groupBusinessLogic.updateGroups(preparedResource, updatedGroups, false);
732                         }
733                 }
734         }
735
736         private void updateResourceInstancesNames(Resource oldResource, CsarInfo csarInfo, Resource preparedResource, boolean isTopologyChanged) {
737                 if(CollectionUtils.isNotEmpty(oldResource.getComponentInstances())){
738                         Map<String, String> oldInstances = oldResource.getComponentInstances()
739                                         .stream()
740                                         .collect(toMap(ComponentInstance::getInvariantName, ComponentInstance::getName));
741                         List<ComponentInstance> updatedInstances = preparedResource.getComponentInstances()
742                                         .stream()
743                                         .filter(i -> oldInstances.containsKey(i.getInvariantName()) && !i.getName()
744                                                         .equals(oldInstances.get(i.getInvariantName())))
745                                         .collect(toList());
746                         if (CollectionUtils.isNotEmpty(updatedInstances)) {
747                                 if(isTopologyChanged) {
748                                         updatedInstances.stream().filter(i -> !i.isCreatedFromCsar())
749                                                         .forEach(i -> i.setName(oldInstances.get(i.getInvariantName())));
750                                 }
751                                 else{
752                                         updatedInstances.forEach(i -> i.setName(oldInstances.get(i.getInvariantName())));
753                                 }
754                         }
755
756                 }
757                 componentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME,
758                                 null, preparedResource.getUniqueId(), csarInfo.getModifier()
759                                                 .getUserId(),
760                                 preparedResource.getComponentInstances(), false);
761         }
762
763         private Either<Resource, ResponseFormat> createOrUpdateArtifacts(ArtifactOperationEnum operation,
764                                                                                                                                          List<ArtifactDefinition> createdArtifacts, String yamlFileName, CsarInfo csarInfo,
765                                                                                                                                          Resource preparedResource, NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts,
766                                                                                                                                          boolean inTransaction, boolean shouldLock) {
767
768                 String nodeName = nodeTypeInfoToUpdateArtifacts.getNodeName();
769                 Resource resource = preparedResource;
770
771                 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts
772                                 .getNodeTypesArtifactsToHandle();
773                 if (preparedResource.getResourceType() == ResourceTypeEnum.CVFC) {
774                         if (nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null
775                                         && !nodeTypesArtifactsToHandle.get(nodeName)
776                                         .isEmpty()) {
777                                 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = handleNodeTypeArtifacts(
778                                                 preparedResource, nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts,
779                                                 csarInfo.getModifier(), inTransaction, true);
780                                 if (handleNodeTypeArtifactsRes.isRight()) {
781                                         return Either.right(handleNodeTypeArtifactsRes.right()
782                                                         .value());
783                                 }
784                         }
785                 } else {
786                         Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource,
787                                         csarInfo, createdArtifacts,
788                                         artifactsBusinessLogic.new ArtifactOperationInfo(false, false, operation), shouldLock,
789                                         inTransaction);
790                         log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
791                         if (createdCsarArtifactsEither.isRight()) {
792                                 return createdCsarArtifactsEither;
793
794                         }
795                         resource = createdCsarArtifactsEither.left()
796                                         .value();
797                 }
798                 return Either.left(resource);
799         }
800
801         private Resource handleResourceGenericType(Resource resource) {
802                 Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
803                 if (resource.shouldGenerateInputs()) {
804                         generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
805                 }
806                 return genericResource;
807         }
808
809         private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(
810                 final Map<String, NodeTypeInfo> nodeTypesInfo, final CsarInfo csarInfo, final Resource oldResource) {
811
812                 final Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
813                 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat>
814                         nodeTypesArtifactsToHandleRes = Either.left(nodeTypesArtifactsToHandle);
815
816                 try {
817                         final Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils
818                                 .extractVfcsArtifactsFromCsar(csarInfo.getCsar());
819                         final Map<String, ImmutablePair<String, String>> extractedVfcToscaNames = extractVfcToscaNames(
820                                 nodeTypesInfo, oldResource.getName(), csarInfo);
821                         log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ",
822                                 oldResource.getName(), csarInfo.getCsarUUID());
823                         extractedVfcToscaNames.forEach((namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo,
824                                 nodeTypesArtifactsToHandle, oldResource, extractedVfcsArtifacts, namespace, vfcToscaNames));
825                 } catch (Exception e) {
826                         final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
827                         nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
828                         log.debug("Exception occurred when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e);
829                 }
830                 return nodeTypesArtifactsToHandleRes;
831         }
832
833         private void findAddNodeTypeArtifactsToHandle(CsarInfo csarInfo,
834                                                                                                   Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
835                                                                                                   Resource resource, Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts, String namespace,
836                                                                                                   ImmutablePair<String, String> vfcToscaNames) {
837
838                 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
839                 log.debug("Going to fetch node type with tosca name {}. ", vfcToscaNames.getLeft());
840                 Resource curNodeType = findVfcResource(csarInfo, resource, vfcToscaNames.getLeft(), vfcToscaNames.getRight(),
841                                 null);
842                 if (!isEmpty(extractedVfcsArtifacts)) {
843                         List<ArtifactDefinition> currArtifacts = new ArrayList<>();
844                         if (extractedVfcsArtifacts.containsKey(namespace)) {
845                                 handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(namespace));
846                         }
847                         curNodeTypeArtifactsToHandle = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
848                 } else if (curNodeType != null) {
849                         // delete all artifacts if have not received artifacts from
850                         // csar
851                         curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
852                         List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
853                         // delete all informational artifacts
854                         artifactsToDelete.addAll(curNodeType.getArtifacts()
855                                         .values()
856                                         .stream()
857                                         .filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
858                                         .collect(toList()));
859                         // delete all deployment artifacts
860                         artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts()
861                                         .values());
862                         if (!artifactsToDelete.isEmpty()) {
863                                 curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
864                         }
865                 }
866                 if (isNotEmpty(curNodeTypeArtifactsToHandle)) {
867                         nodeTypesArtifactsToHandle.put(namespace, curNodeTypeArtifactsToHandle);
868                 }
869         }
870
871         private Resource findVfcResource(CsarInfo csarInfo, Resource resource, String currVfcToscaName,
872                                                                          String previousVfcToscaName, StorageOperationStatus status) {
873                 if (status != null && status != StorageOperationStatus.NOT_FOUND) {
874                         log.debug("Error occurred during fetching node type with tosca name {}, error: {}", currVfcToscaName,
875                                         status);
876                         ResponseFormat responseFormat = componentsUtils
877                                         .getResponseFormat(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
878                         componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
879                                         AuditingActionEnum.CREATE_RESOURCE);
880                         throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
881                 } else if (StringUtils.isNotEmpty(currVfcToscaName)) {
882                         return (Resource) toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName)
883                                         .left()
884                                         .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st));
885                 }
886                 return null;
887         }
888
889         private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> findNodeTypeArtifactsToHandle(Resource curNodeType,
890                                                                                                                                                                                                    List<ArtifactDefinition> extractedArtifacts) {
891
892                 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
893                 try {
894                         List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
895                         List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
896                         List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
897                         processExistingNodeTypeArtifacts(extractedArtifacts, artifactsToUpload, artifactsToUpdate,
898                                         artifactsToDelete, collectExistingArtifacts(curNodeType));
899                         nodeTypeArtifactsToHandle = putFoundArtifacts(artifactsToUpload, artifactsToUpdate, artifactsToDelete);
900                 } catch (Exception e) {
901                         log.debug("Exception occurred when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
902                         throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
903                 }
904                 return nodeTypeArtifactsToHandle;
905         }
906
907         private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> putFoundArtifacts(
908                         List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate,
909                         List<ArtifactDefinition> artifactsToDelete) {
910                 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
911                 if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
912                         nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
913                         if (!artifactsToUpload.isEmpty()) {
914                                 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
915                         }
916                         if (!artifactsToUpdate.isEmpty()) {
917                                 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
918                         }
919                         if (!artifactsToDelete.isEmpty()) {
920                                 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
921                         }
922                 }
923                 return nodeTypeArtifactsToHandle;
924         }
925
926         private void processExistingNodeTypeArtifacts(List<ArtifactDefinition> extractedArtifacts,
927                                                                                                   List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate,
928                                                                                                   List<ArtifactDefinition> artifactsToDelete, Map<String, ArtifactDefinition> existingArtifacts) {
929                 if (!existingArtifacts.isEmpty()) {
930                         extractedArtifacts.stream()
931                                         .forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a));
932                         artifactsToDelete.addAll(existingArtifacts.values());
933                 }
934         }
935
936         private void processNodeTypeArtifact(List<ArtifactDefinition> artifactsToUpload,
937                                                                                  List<ArtifactDefinition> artifactsToUpdate, Map<String, ArtifactDefinition> existingArtifacts,
938                                                                                  ArtifactDefinition currNewArtifact) {
939                 Optional<ArtifactDefinition> foundArtifact = existingArtifacts.values()
940                                 .stream()
941                                 .filter(a -> a.getArtifactName()
942                                                 .equals(currNewArtifact.getArtifactName()))
943                                 .findFirst();
944                 if (foundArtifact.isPresent()) {
945                         if (foundArtifact.get()
946                                         .getArtifactType()
947                                         .equals(currNewArtifact.getArtifactType())) {
948                                 updateFoundArtifact(artifactsToUpdate, currNewArtifact, foundArtifact.get());
949                                 existingArtifacts.remove(foundArtifact.get()
950                                                 .getArtifactLabel());
951                                 artifactsToUpload.remove(currNewArtifact);
952                         } else {
953                                 log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
954                                 throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
955                                                 currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(), foundArtifact.get()
956                                                 .getArtifactType());
957                         }
958                 }
959         }
960
961         private void updateFoundArtifact(List<ArtifactDefinition> artifactsToUpdate, ArtifactDefinition currNewArtifact,
962                                                                          ArtifactDefinition foundArtifact) {
963                 if (!foundArtifact.getArtifactChecksum()
964                                 .equals(currNewArtifact.getArtifactChecksum())) {
965                         foundArtifact.setPayload(currNewArtifact.getPayloadData());
966                         foundArtifact.setPayloadData(Base64.encodeBase64String(currNewArtifact.getPayloadData()));
967                         foundArtifact.setArtifactChecksum(
968                                         GeneralUtility.calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
969                         artifactsToUpdate.add(foundArtifact);
970                 }
971         }
972
973         private Map<String, ArtifactDefinition> collectExistingArtifacts(Resource curNodeType) {
974                 Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>();
975                 if (curNodeType == null) {
976                         return existingArtifacts;
977                 }
978                 if (MapUtils.isNotEmpty(curNodeType.getDeploymentArtifacts())) {
979                         existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
980                 }
981                 if (MapUtils.isNotEmpty(curNodeType.getArtifacts())) {
982                         existingArtifacts.putAll(curNodeType.getArtifacts()
983                                         .entrySet()
984                                         .stream()
985                                         .filter(e -> e.getValue()
986                                                         .getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
987                                         .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
988                 }
989                 return existingArtifacts;
990         }
991
992         /**
993          * Changes resource life cycle state to checked out
994          *
995          * @param resource
996          * @param user
997          * @param inTransaction
998          * @return
999          */
1000         private Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) {
1001                 Either<Resource, ResponseFormat> checkoutResourceRes;
1002                 try {
1003                         if (!resource.getComponentMetadataDefinition()
1004                                         .getMetadataDataDefinition()
1005                                         .getState()
1006                                         .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
1007                                 log.debug(
1008                                                 "************* Going to change life cycle state of resource {} to not certified checked out. ",
1009                                                 resource.getName());
1010                                 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(
1011                                                 resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
1012                                                 new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1013                                                                 LifecycleChanceActionEnum.CREATE_FROM_CSAR),
1014                                                 inTransaction, true);
1015                                 if (checkoutRes.isRight()) {
1016                                         log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ",
1017                                                         resource.getComponentType()
1018                                                                         .getNodeType(),
1019                                                         resource.getUniqueId(), checkoutRes.right()
1020                                                                         .value()
1021                                                                         .getStatus());
1022                                         checkoutResourceRes = Either.right(checkoutRes.right()
1023                                                         .value());
1024                                 } else {
1025                                         checkoutResourceRes = Either.left((Resource) checkoutRes.left()
1026                                                         .value());
1027                                 }
1028                         } else {
1029                                 checkoutResourceRes = Either.left(resource);
1030                         }
1031                 } catch (Exception e) {
1032                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1033                         checkoutResourceRes = Either.right(responseFormat);
1034                         log.debug("Exception occurred when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(),
1035                                         e);
1036                 }
1037                 return checkoutResourceRes;
1038         }
1039
1040         /**
1041          * Handles Artifacts of NodeType
1042          *
1043          * @param nodeTypeResource
1044          * @param nodeTypeArtifactsToHandle
1045          * @param user
1046          * @param inTransaction
1047          * @return
1048          */
1049         public Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource,
1050                                                                                                                                                                         Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1051                                                                                                                                                                         List<ArtifactDefinition> createdArtifacts, User user, boolean inTransaction, boolean ignoreLifecycleState) {
1052                 List<ArtifactDefinition> handleNodeTypeArtifactsRequestRes;
1053                 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null;
1054                 Either<Resource, ResponseFormat> changeStateResponse;
1055                 try {
1056                         changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction);
1057                         if (changeStateResponse.isRight()) {
1058                                 return Either.right(changeStateResponse.right()
1059                                                 .value());
1060                         }
1061                         nodeTypeResource = changeStateResponse.left()
1062                                         .value();
1063
1064                         List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>();
1065                         log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName());
1066                         for (Entry<ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle
1067                                         .entrySet()) {
1068                                 ArtifactOperationEnum curOperation = curOperationEntry.getKey();
1069                                 List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue();
1070                                 if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) {
1071                                         log.debug("************* Going to {} artifact to vfc {}", curOperation.name(),
1072                                                         nodeTypeResource.getName());
1073                                         handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic
1074                                                         .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user,
1075                                                                         createdArtifacts, artifactsBusinessLogic.new ArtifactOperationInfo(false,
1076                                                                                         ignoreLifecycleState, curOperation),
1077                                                                         false, inTransaction);
1078                                         if (ArtifactOperationEnum.isCreateOrLink(curOperation)) {
1079                                                 createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes);
1080                                         }
1081                                         handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes);
1082                                 }
1083                         }
1084                         if (handleNodeTypeArtifactsRes == null) {
1085                                 handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts);
1086                         }
1087                 } catch (Exception e) {
1088                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1089                         handleNodeTypeArtifactsRes = Either.right(responseFormat);
1090                         log.debug("Exception occurred when handleVfcArtifacts, error is:{}", e.getMessage(), e);
1091                 }
1092                 return handleNodeTypeArtifactsRes;
1093         }
1094
1095         private Map<String, ImmutablePair<String, String>> extractVfcToscaNames(final Map<String, NodeTypeInfo> nodeTypesInfo,
1096                                                                                                                                                         final String vfResourceName,
1097                                                                                                                                                         final CsarInfo csarInfo) {
1098                 final Map<String, ImmutablePair<String, String>> vfcToscaNames = new HashMap<>();
1099
1100                 final Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo);
1101                 if (!nodes.isEmpty()) {
1102                         final Iterator<Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator();
1103                         while (nodesNameEntry.hasNext()) {
1104                                 final Entry<String, Object> nodeType = nodesNameEntry.next();
1105                                 final ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName(
1106                                         ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey());
1107                                 vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
1108                         }
1109                 }
1110                 for (final NodeTypeInfo cvfc : nodeTypesInfo.values()) {
1111                         vfcToscaNames.put(cvfc.getType(), buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(),
1112                                 vfResourceName, cvfc.getType()));
1113                 }
1114                 return vfcToscaNames;
1115         }
1116
1117         private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
1118                 Map<String, Object> nodes = new HashMap<>();
1119                 for (NodeTypeInfo nodeTypeInfo : nodeTypesInfo.values()) {
1120                         extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate());
1121                 }
1122                 extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate());
1123                 return nodes;
1124         }
1125
1126         private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) {
1127                 Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils
1128                                 .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
1129                 if (eitherNodeTypes.isLeft()) {
1130                         nodes.putAll(eitherNodeTypes.left()
1131                                         .value());
1132                 }
1133         }
1134
1135         public Resource createResourceFromCsar(Resource resource, User user, Map<String, byte[]> csarUIPayload,
1136                                                                                    String csarUUID) {
1137                 log.trace("************* created successfully from YAML, resource TOSCA ");
1138                 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,StatusCode.STARTED,"Starting to create Resource From Csar by user {}", user.getUserId() );
1139                 CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(resource, null, user, csarUIPayload, csarUUID);
1140                 Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
1141                 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
1142                                 nodeTypesInfo, csarInfo, resource);
1143                 if (findNodeTypesArtifactsToHandleRes.isRight()) {
1144                         log.debug("failed to find node types for update with artifacts during import csar {}. ",
1145                                         csarInfo.getCsarUUID());
1146                         loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(),
1147                                         StatusCode.ERROR,"error: {}",findNodeTypesArtifactsToHandleRes.right().value());
1148                         throw new ByResponseFormatComponentException(findNodeTypesArtifactsToHandleRes.right().value());
1149                 }
1150                 Resource vfResource = createResourceFromYaml(resource, csarInfo.getMainTemplateContent(),
1151                                 csarInfo.getMainTemplateName(), nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left()
1152                                                 .value(),
1153                                 true, false, null);
1154                 log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}",
1155                                 vfResource.getToscaResourceName());
1156                 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,StatusCode.COMPLETE,"Ended create Resource From Csar by user {}", user.getUserId() );
1157                 return vfResource;
1158         }
1159
1160         private Resource validateResourceBeforeCreate(Resource resource, User user, boolean inTransaction) {
1161                 log.trace("validating resource before create");
1162                 user.copyData(validateUser(user, CREATE_RESOURCE, resource, AuditingActionEnum.CREATE_RESOURCE, false));
1163                 // validate user role
1164                 validateUserRole(user, resource, new ArrayList<>(), AuditingActionEnum.CREATE_RESOURCE, null);
1165                 // VF / PNF "derivedFrom" should be null (or ignored)
1166                 if (ModelConverter.isAtomicComponent(resource)) {
1167                         validateDerivedFromNotEmpty(user, resource, AuditingActionEnum.CREATE_RESOURCE);
1168                 }
1169                 return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction, null);
1170
1171         }
1172
1173         // resource, yamlFileContents, yamlFileName, nodeTypesInfo,csarInfo,
1174         // nodeTypesArtifactsToCreate, true, false, null
1175         private Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml, String yamlName,
1176                                                                                         Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1177                                                                                         Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1178                                                                                         boolean shouldLock, boolean inTransaction, String nodeName) {
1179
1180                 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
1181                 Resource createdResource;
1182                 try {
1183             ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic.getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName);
1184             if (MapUtils.isEmpty(parsedToscaYamlInfo.getInstances()) && resource.getResourceType() != ResourceTypeEnum.PNF) {
1185                 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
1186             }
1187                         log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", resource.getName());
1188                         loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(),
1189                                         StatusCode.STARTED,"");
1190                         createdResource = createResourceAndRIsFromYaml(yamlName, resource, parsedToscaYamlInfo,
1191                                         AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml, nodeTypesInfo,
1192                                         csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
1193                         log.debug("#createResourceFromYaml - The resource {} has been created ", resource.getName());
1194                         loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(),
1195                                         StatusCode.COMPLETE,"The resource has been created: {}",resource.getName());
1196                 } catch (ComponentException e) {
1197                         ResponseFormat responseFormat = e.getResponseFormat() == null
1198                                         ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
1199                         componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
1200                                         AuditingActionEnum.IMPORT_RESOURCE);
1201                         throw e;
1202                 } catch (StorageException e) {
1203                         ResponseFormat responseFormat = componentsUtils
1204                                         .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
1205                         componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
1206                                         AuditingActionEnum.IMPORT_RESOURCE);
1207                         throw e;
1208                 }
1209                 return createdResource;
1210
1211         }
1212
1213         public Map<String, Resource> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource,
1214                                                                                                                                           Map<String, Object> mappedToscaTemplate, boolean needLock,
1215                                                                                                                                           Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1216                                                                                                                                           List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
1217                                                                                                                                           CsarInfo csarInfo) {
1218
1219                 Either<String, ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate,
1220                                 TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
1221                 if (toscaVersion.isRight()) {
1222                         throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE);
1223                 }
1224                 Map<String, Object> mapToConvert = new HashMap<>();
1225                 mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left()
1226                                 .value());
1227                 Map<String, Object> nodeTypes = getNodeTypesFromTemplate(mappedToscaTemplate);
1228                 createNodeTypes(yamlName, resource, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts,
1229                                 nodeTypesInfo, csarInfo, mapToConvert, nodeTypes);
1230                 return csarInfo.getCreatedNodes();
1231         }
1232
1233         private Map<String, Object> getNodeTypesFromTemplate(Map<String, Object> mappedToscaTemplate) {
1234                 return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES)
1235                                 .left()
1236                                 .orValue(HashMap::new);
1237         }
1238
1239         private void createNodeTypes(String yamlName, Resource resource, boolean needLock,
1240                                                                  Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1241                                                                  List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
1242                                                                  CsarInfo csarInfo, Map<String, Object> mapToConvert, Map<String, Object> nodeTypes) {
1243                 Iterator<Entry<String, Object>> nodesNameValueIter = nodeTypes.entrySet()
1244                                 .iterator();
1245                 Resource vfcCreated = null;
1246                 while (nodesNameValueIter.hasNext()) {
1247                         Entry<String, Object> nodeType = nodesNameValueIter.next();
1248                         Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null
1249                                         || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey());
1250
1251                         if (nodeTypesInfo.containsKey(nodeType.getKey())) {
1252                                 log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
1253                                 vfcCreated = handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts,
1254                                                 nodeTypesInfo, csarInfo, nodeType.getKey());
1255                                 log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
1256                         } else if (csarInfo.getCreatedNodesToscaResourceNames() != null
1257                                         && !csarInfo.getCreatedNodesToscaResourceNames()
1258                                         .containsKey(nodeType.getKey())) {
1259                                 log.trace("************* Going to create node {}", nodeType.getKey());
1260                                 ImmutablePair<Resource, ActionStatus> resourceCreated = createNodeTypeResourceFromYaml(yamlName,
1261                                                 nodeType, csarInfo.getModifier(), mapToConvert, resource, needLock, nodeTypeArtifactsToHandle,
1262                                                 nodeTypesNewCreatedArtifacts, true, csarInfo, true);
1263                                 log.debug("************* Finished to create node {}", nodeType.getKey());
1264
1265                                 vfcCreated = resourceCreated.getLeft();
1266                                 csarInfo.getCreatedNodesToscaResourceNames()
1267                                                 .put(nodeType.getKey(), vfcCreated.getToscaResourceName());
1268                         }
1269                         if (vfcCreated != null) {
1270                                 csarInfo.getCreatedNodes()
1271                                                 .put(nodeType.getKey(), vfcCreated);
1272                         }
1273                         mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName());
1274                 }
1275         }
1276
1277         private Resource handleNestedVfc(Resource resource,
1278                                                                          Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1279                                                                          List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1280                                                                          String nodeName) {
1281
1282                 String yamlName = nodesInfo.get(nodeName)
1283                                 .getTemplateFileName();
1284                 Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName)
1285                                 .getMappedToscaTemplate();
1286
1287                 log.debug("************* Going to create node types from yaml {}", yamlName);
1288                 createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false, nodesArtifactsToHandle,
1289                                 createdArtifacts, nodesInfo, csarInfo);
1290                 log.debug("************* Finished to create node types from yaml {}", yamlName);
1291
1292                 if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
1293                         log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
1294                         resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo,
1295                                         nodeName, yamlName);
1296                 }
1297                 return resource;
1298         }
1299
1300         private Resource handleComplexVfc(final Resource resource,
1301                                                                           final Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>
1302                                                                                   nodesArtifactsToHandle,
1303                                                                           final List<ArtifactDefinition>
1304                                                                                   createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1305                                                                           final String nodeName, final String yamlName) {
1306
1307                 Resource oldComplexVfc = null;
1308                 Resource newComplexVfc = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo);
1309                 Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade
1310                         .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
1311                 if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
1312                         oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
1313                                         buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName).getRight());
1314                 }
1315                 if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
1316                         log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ",
1317                                 newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value());
1318                         throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
1319                 } else if (oldComplexVfcRes.isLeft()) {
1320                         log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
1321                         final Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(
1322                                         oldComplexVfcRes.left().value(),
1323                                         newComplexVfc, ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
1324                         if (eitherValidation.isLeft()) {
1325                                 oldComplexVfc = oldComplexVfcRes.left().value();
1326                         }
1327                 }
1328                 newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName,
1329                         yamlName, oldComplexVfc, newComplexVfc);
1330                 csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
1331                 final LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1332                         LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1333                 log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
1334                 final Resource result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc,
1335                                 lifecycleChangeInfo, true, false, true);
1336                 csarInfo.getCreatedNodes().put(nodeName, result);
1337                 csarInfo.removeNodeFromQueue();
1338                 return result;
1339         }
1340
1341         private Resource handleComplexVfc(
1342                         Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1343                         List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1344                         String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) {
1345
1346                 Resource handleComplexVfcRes;
1347                 Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName)
1348                                 .getMappedToscaTemplate();
1349                 String yamlContent = new String(csarInfo.getCsar()
1350                                 .get(yamlName));
1351                 Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet()
1352                                 .stream()
1353                                 .collect(toMap(Entry::getKey, e -> e.getValue()
1354                                                 .getUnmarkedCopy()));
1355                 CsarInfo.markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
1356                 if (oldComplexVfc == null) {
1357                         handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo,
1358                                         csarInfo, nodesArtifactsToHandle, false, true, nodeName);
1359                 } else {
1360                         handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc,
1361                                         AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, yamlContent, yamlName, csarInfo,
1362                                         newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true);
1363                 }
1364                 return handleComplexVfcRes;
1365         }
1366
1367         private Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName,
1368                                                                                   Map<String, NodeTypeInfo> nodesInfo) {
1369
1370                 Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo);
1371                 log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
1372                 csarInfo.addNodeToQueue(nodeName);
1373                 return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE,
1374                                 true, csarInfo);
1375         }
1376
1377         private String getNodeTypeActualName(final String nodeTypefullName, final String nodeTypeNamePrefix) {
1378
1379                 final String nameWithouNamespacePrefix = nodeTypefullName.substring(nodeTypeNamePrefix.length());
1380                 final String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1381                 final String resourceType = findTypes[0];
1382                 return nameWithouNamespacePrefix.substring(resourceType.length());
1383         }
1384
1385         private ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(final String yamlName,
1386                                                                                                                                                                  final Entry<String, Object> nodeNameValue,
1387                                                                                                                                                                  User user,
1388                                                                                                                                                                  final Map<String, Object> mapToConvert,
1389                                                                                                                                                                  final Resource resourceVf,
1390                                                                                                                                                                  final boolean needLock,
1391                                                                                                                                                                  final Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1392                                                                                                                                                                  final List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1393                                                                                                                                                                  final boolean forceCertificationAllowed,
1394                                                                                                                                                                  final CsarInfo csarInfo,
1395                                                                                                                                                                  final boolean isNested) {
1396
1397                 final UploadResourceInfo resourceMetaData = fillResourceMetadata(
1398                         yamlName, resourceVf, nodeNameValue.getKey(), user);
1399
1400                 final String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.getResourceType(), csarInfo);
1401                 user = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
1402                 return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock,
1403                                 nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo,
1404                                 nodeNameValue.getKey(), isNested);
1405         }
1406
1407         private String buildNodeTypeYaml(final Entry<String, Object> nodeNameValue,
1408                                                                          final Map<String, Object> mapToConvert,
1409                                                                          final String nodeResourceType,
1410                                                                          final CsarInfo csarInfo) {
1411                 // We need to create a Yaml from each node_types in order to create
1412                 // resource from each node type using import normative flow.
1413                 final DumperOptions options = new DumperOptions();
1414                 options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
1415                 final Yaml yaml = new Yaml(options);
1416
1417                 final Map<String, Object> node = new HashMap<>();
1418                 node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey())
1419                                 .getLeft(), nodeNameValue.getValue());
1420                 mapToConvert.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
1421
1422                 return yaml.dumpAsMap(mapToConvert);
1423         }
1424
1425         public Boolean validateResourceCreationFromNodeType(Resource resource, User creator) {
1426                 validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
1427                 return true;
1428         }
1429
1430         public ImmutablePair<Resource, ActionStatus> createResourceFromNodeType(String nodeTypeYaml,
1431                                                                                                                                                         UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock,
1432                                                                                                                                                         Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1433                                                                                                                                                         List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
1434                                                                                                                                                         String nodeName, boolean isNested) {
1435
1436                 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1437                                 LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1438                 Function<Resource, Boolean> validator = resource -> validateResourceCreationFromNodeType(
1439                                 resource, creator);
1440                 return resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator,
1441                                 lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle,
1442                                 nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested);
1443         }
1444
1445         /**
1446          * Validates if a given node type name has a valid prefix.
1447          *
1448          * @param nodeName node name from definition file
1449          * @param definedResourceNamespaceList is a list of all node type name prefix allowed
1450          * @return a valid node type name prefix if it`s found
1451          */
1452         public Optional<String> validateNodeTypeNamePrefix(final String nodeName,
1453                                                                                                            final List<String> definedResourceNamespaceList) {
1454                 for (final String validNamespace : definedResourceNamespaceList) {
1455                         if (nodeName.startsWith(validNamespace)) {
1456                                 return Optional.of(validNamespace);
1457                         }
1458                 }
1459                 return Optional.empty();
1460         }
1461
1462         private List<String> getDefinedNodeTypeNamespaceList() {
1463                 return ConfigurationManager.getConfigurationManager().getConfiguration().getDefinedResourceNamespace();
1464         }
1465
1466         private UploadResourceInfo fillResourceMetadata(final String yamlName, final Resource resourceVf,
1467                                                                                                         final String nodeName, final User user) {
1468
1469                 final UploadResourceInfo resourceMetaData = new UploadResourceInfo();
1470
1471                 final String nodeTypeNamePrefix = getNodeTypeNamePrefix(nodeName);
1472                 log.debug("Node type Name prefix {}", nodeTypeNamePrefix);
1473
1474                 if (!nodeName.startsWith(nodeTypeNamePrefix)) {
1475                         log.debug("invalid nodeName:{} does not start with {}.", nodeName, getDefinedNodeTypeNamespaceList());
1476                         throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName,
1477                                 resourceMetaData.getName(), nodeName);
1478                 }
1479
1480                 final String actualName = this.getNodeTypeActualName(nodeName, nodeTypeNamePrefix);
1481                 final String namePrefix = nodeName.replace(actualName, "");
1482                 String resourceType = namePrefix.substring(nodeTypeNamePrefix.length());
1483                 log.debug("initial  namePrefix:{} resourceType {}. nodeName {} , actualName {} prefix {}", namePrefix,
1484                         resourceType, nodeName, actualName, nodeTypeNamePrefix);
1485
1486                 // if we import from csar, the node_type name can be
1487                 // org.openecomp.resource.abstract.node_name - in this case we always
1488                 // create a vfc
1489                 if (resourceType.equals(Constants.ABSTRACT)) {
1490                         resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
1491                 }
1492
1493                 if (!ResourceTypeEnum.containsIgnoreCase(resourceType)) {
1494                         resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
1495                 }
1496
1497                 // validating type
1498                 if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
1499                         log.debug("invalid resourceType:{} the type is not one of the valide types:{}.",
1500                                 resourceType.toUpperCase(),     ResourceTypeEnum.values());
1501                         throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName,
1502                                 resourceMetaData.getName(), nodeName);
1503                 }
1504
1505                 // Setting name
1506                 resourceMetaData.setName(new StringBuilder(resourceVf.getSystemName()).append(actualName).toString());
1507
1508                 // Setting type from name
1509                 final String type = resourceType.toUpperCase();
1510                 resourceMetaData.setResourceType(type);
1511
1512                 resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
1513                 resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1514                 resourceMetaData.setContactId(user.getUserId());
1515                 resourceMetaData.setVendorName(resourceVf.getVendorName());
1516                 resourceMetaData.setVendorRelease(resourceVf.getVendorRelease());
1517
1518                 // Setting tag
1519                 final List<String> tags = new ArrayList<>();
1520                 tags.add(resourceMetaData.getName());
1521                 resourceMetaData.setTags(tags);
1522
1523                 // Setting category
1524                 final CategoryDefinition category = new CategoryDefinition();
1525                 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1526                 final SubCategoryDefinition subCategory = new SubCategoryDefinition();
1527                 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1528                 category.addSubCategory(subCategory);
1529                 final List<CategoryDefinition> categories = new ArrayList<>();
1530                 categories.add(category);
1531                 resourceMetaData.setCategories(categories);
1532
1533                 return resourceMetaData;
1534         }
1535
1536         private Resource buildComplexVfcMetadata(final Resource resourceVf,
1537                                                                                          final CsarInfo csarInfo,
1538                                                                                          final String nodeName,
1539                                                                                          final Map<String, NodeTypeInfo> nodesInfo) {
1540                 final Resource cvfc = new Resource();
1541                 final NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
1542                 cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
1543                 cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
1544                 cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
1545                 cvfc.setResourceType(ResourceTypeEnum.CVFC);
1546                 cvfc.setAbstract(true);
1547                 cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
1548                 cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION);
1549                 cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1550                 cvfc.setContactId(csarInfo.getModifier()
1551                                 .getUserId());
1552                 cvfc.setCreatorUserId(csarInfo.getModifier()
1553                                 .getUserId());
1554                 cvfc.setVendorName(resourceVf.getVendorName());
1555                 cvfc.setVendorRelease(resourceVf.getVendorRelease());
1556                 cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
1557                 cvfc.setToscaResourceName(buildNestedToscaResourceName(
1558                         ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName).getLeft());
1559                 cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
1560
1561                 final List<String> tags = new ArrayList<>();
1562                 tags.add(cvfc.getName());
1563                 cvfc.setTags(tags);
1564
1565                 final CategoryDefinition category = new CategoryDefinition();
1566                 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1567                 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1568                 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1569                 category.addSubCategory(subCategory);
1570                 final List<CategoryDefinition> categories = new ArrayList<>();
1571                 categories.add(category);
1572                 cvfc.setCategories(categories);
1573
1574                 cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
1575                 cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
1576                 cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
1577
1578                 return cvfc;
1579         }
1580
1581         private String buildCvfcName(final String resourceVfName, final String nodeName) {
1582
1583                 String nameWithouNamespacePrefix =
1584                         nodeName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1585                 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1586                 String resourceType = findTypes[0];
1587                 String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1);
1588                 return addCvfcSuffixToResourceName(resourceName);
1589         }
1590
1591         private Resource createResourceAndRIsFromYaml(final String yamlName,
1592                                                                                                   Resource resource,
1593                                                                                                   final ParsedToscaYamlInfo parsedToscaYamlInfo,
1594                                                                                                   final AuditingActionEnum actionEnum,
1595                                                                                                   final boolean isNormative,
1596                                                                                                   final List<ArtifactDefinition> createdArtifacts,
1597                                                                                                   final String topologyTemplateYaml,
1598                                                                                                   final Map<String, NodeTypeInfo> nodeTypesInfo,
1599                                                                                                   final CsarInfo csarInfo,
1600                                                                                                   final Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1601                                                                                                   final boolean shouldLock,
1602                                                                                                   final boolean inTransaction,
1603                                                                                                   final String nodeName) {
1604
1605                 final List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
1606
1607         if (shouldLock) {
1608             final Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
1609                     CREATE_RESOURCE);
1610             if (lockResult.isRight()) {
1611                 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1612                 throw new ByResponseFormatComponentException(lockResult.right().value());
1613             }
1614             log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
1615         }
1616         try {
1617             log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
1618             loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Starting to add inputs from yaml: {}",yamlName);
1619             final Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
1620             resource = createResourceTransaction(resource, csarInfo.getModifier(), isNormative);
1621             log.trace("************* createResourceFromYaml after full create resource {}", yamlName);
1622             log.trace("************* Going to add inputs from yaml {}", yamlName);
1623             if (resource.shouldGenerateInputs())
1624                 generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
1625
1626             final Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
1627             resource = createInputsOnResource(resource, inputs);
1628             log.trace("************* Finish to add inputs from yaml {}", yamlName);
1629             loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,
1630                                 resource.getComponentMetadataForSupportLog(),
1631                                 StatusCode.COMPLETE,"Finish to add inputs from yaml: {}",yamlName);
1632             if (resource.getResourceType() == ResourceTypeEnum.PNF) {
1633                 log.trace("************* Adding generic properties to PNF");
1634                 resource = (Resource) propertyBusinessLogic.copyPropertyToComponent(resource,
1635                                         genericResource.getProperties());
1636                 log.trace("************* Adding software information to PNF");
1637                 softwareInformationBusinessLogic.setSoftwareInformation(resource, csarInfo);
1638                 log.trace("************* Removing non-mano software information file from PNF");
1639                 if (csarInfo.getSoftwareInformationPath().isPresent() &&
1640                         !softwareInformationBusinessLogic.removeSoftwareInformationFile(csarInfo)) {
1641                     log.warn(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR , ResourceBusinessLogic.class.getName(),
1642                             "catalog-be", "Could not remove the software information file.");
1643                 }
1644             }
1645
1646             final Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo
1647                                 .getInstances();
1648             log.trace("************* Going to create nodes, RI's and Relations  from yaml {}", yamlName);
1649             loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Start create nodes, RI and Relations  from yaml: {}",yamlName);
1650             resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap,
1651                                 topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate,
1652                                 nodeName);
1653             log.trace("************* Finished to create nodes, RI and Relation  from yaml {}", yamlName);
1654             loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,
1655                                 resource.getComponentMetadataForSupportLog(),
1656                                 StatusCode.COMPLETE,"Finished to create nodes, RI and Relation  from yaml: {}",yamlName);
1657             // validate update vf module group names
1658             final Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
1659                                 .validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName());
1660             if (validateUpdateVfGroupNamesRes.isRight()) {
1661                 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1662                 throw new ByResponseFormatComponentException(validateUpdateVfGroupNamesRes.right().value());
1663             }
1664             // add groups to resource
1665             final Map<String, GroupDefinition> groups;
1666             log.trace("************* Going to add groups from yaml {}", yamlName);
1667             loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS,resource.getComponentMetadataForSupportLog(),
1668                                 StatusCode.STARTED,"Start to add groups from yaml: {}",yamlName);
1669             if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
1670                 groups = validateUpdateVfGroupNamesRes.left().value();
1671             } else {
1672                 groups = parsedToscaYamlInfo.getGroups();
1673             }
1674
1675                         final Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource, groups);
1676                         if (createGroupsOnResource.isRight()) {
1677                                 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1678                                 loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS,
1679                                         resource.getComponentMetadataForSupportLog(),
1680                                         StatusCode.ERROR,"ERROR while adding groups from yaml: {}",yamlName);
1681                                 throw new ByResponseFormatComponentException(createGroupsOnResource.right().value());
1682                         }
1683                         resource = createGroupsOnResource.left().value();
1684                         log.trace("************* Finished to add groups from yaml {}", yamlName);
1685                         loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS,
1686                                 resource.getComponentMetadataForSupportLog(),
1687                                 StatusCode.COMPLETE,"Finished to add groups from yaml: {}", yamlName);
1688                         log.trace("************* Going to add artifacts from yaml {}", yamlName);
1689                         loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS,
1690                                 resource.getComponentMetadataForSupportLog(),
1691                                 StatusCode.STARTED,"Started to add artifacts from yaml: {}",yamlName);
1692
1693                         final NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts =
1694                                 new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToCreate);
1695
1696                         final Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(
1697                                 ArtifactOperationEnum.CREATE, createdArtifacts, yamlName, csarInfo, resource,
1698                                 nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
1699                         if (createArtifactsEither.isRight()) {
1700                                 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1701                                 loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS,
1702                                         resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"error happened {}",
1703                                         createArtifactsEither.right().value());
1704                                 throw new ByResponseFormatComponentException(createArtifactsEither.right().value());
1705                         }
1706                         loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS,
1707                                 resource.getComponentMetadataForSupportLog(),
1708                                 StatusCode.COMPLETE,"Finished to add artifacts from yaml: "+resource.getToscaResourceName());
1709                         final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
1710                         componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum);
1711                         ASDCKpiApi.countCreatedResourcesKPI();
1712                         return resource;
1713
1714         } catch (final ComponentException | StorageException e) {
1715             rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1716             throw e;
1717         } catch (final ToscaOperationException e) {
1718             log.error("An error has occurred during resource and resource instance creation", e);
1719             rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1720             log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, ResourceBusinessLogic.class.getName(),
1721                                 "catalog-be", e.getMessage());
1722             throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
1723         } catch (final BusinessLogicException e) {
1724             log.error("An error has occurred during resource and resource instance creation", e);
1725             rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1726             throw new ByResponseFormatComponentException(e.getResponseFormat());
1727         } finally {
1728             if (!inTransaction) {
1729                 janusGraphDao.commit();
1730                         }
1731                         if (shouldLock) {
1732                                 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
1733                                         NodeTypeEnum.Resource);
1734                         }
1735                 }
1736         }
1737
1738         private void rollback(boolean inTransaction, Resource resource, List<ArtifactDefinition> createdArtifacts,
1739                                                   List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
1740                 if (!inTransaction) {
1741             janusGraphDao.rollback();
1742                 }
1743                 if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) {
1744                         createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
1745                         log.debug("Found {} newly created artifacts to deleted, the component name: {}", createdArtifacts.size(),
1746                                         resource.getName());
1747                 }
1748         }
1749
1750         private Resource getResourceWithGroups(String resourceId) {
1751
1752                 ComponentParametersView filter = new ComponentParametersView();
1753                 filter.setIgnoreGroups(false);
1754                 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId,
1755                                 filter);
1756                 if (updatedResource.isRight()) {
1757                         rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right()
1758                                         .value()), resourceId);
1759                 }
1760                 return updatedResource.left()
1761                                 .value();
1762         }
1763
1764         private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource,
1765                                                                                                                                         Map<String, GroupDefinition> groups) {
1766                 if (groups != null && !groups.isEmpty()) {
1767                         List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
1768                         handleGroupsProperties(resource, groups);
1769                         fillGroupsFinalFields(groupsAsList);
1770                         Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource,
1771                                         groupsAsList, true);
1772                         if (createGroups.isRight()) {
1773                                 return Either.right(createGroups.right()
1774                                                 .value());
1775                         }
1776                 }
1777                 return Either.left(resource);
1778         }
1779
1780         private void handleGroupsProperties(Resource resource, Map<String, GroupDefinition> groups) {
1781                 List<InputDefinition> inputs = resource.getInputs();
1782                 if (MapUtils.isNotEmpty(groups)) {
1783                         groups.values()
1784                                         .stream()
1785                                         .filter(g -> isNotEmpty(g.getProperties()))
1786                                         .flatMap(g -> g.getProperties()
1787                                                         .stream())
1788                                         .forEach(p -> handleGetInputs(p, inputs));
1789                 }
1790         }
1791
1792         private void handleGetInputs(PropertyDataDefinition property, List<InputDefinition> inputs) {
1793                 if (isNotEmpty(property.getGetInputValues())) {
1794                         if (inputs == null || inputs.isEmpty()) {
1795                                 log.debug("Failed to add property {} to group. Inputs list is empty ", property);
1796                                 rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
1797                                                 .stream()
1798                                                 .map(GetInputValueDataDefinition::getInputName)
1799                                                 .collect(toList())
1800                                                 .toString());
1801                         }
1802                         ListIterator<GetInputValueDataDefinition> getInputValuesIter = property.getGetInputValues()
1803                                         .listIterator();
1804                         while (getInputValuesIter.hasNext()) {
1805                                 GetInputValueDataDefinition getInput = getInputValuesIter.next();
1806                                 InputDefinition input = findInputByName(inputs, getInput);
1807                                 getInput.setInputId(input.getUniqueId());
1808                                 if (getInput.getGetInputIndex() != null) {
1809                                         GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
1810                                         input = findInputByName(inputs, getInputIndex);
1811                                         getInputIndex.setInputId(input.getUniqueId());
1812                                         getInputValuesIter.add(getInputIndex);
1813                                 }
1814                         }
1815                 }
1816         }
1817
1818         private InputDefinition findInputByName(List<InputDefinition> inputs, GetInputValueDataDefinition getInput) {
1819                 Optional<InputDefinition> inputOpt = inputs.stream()
1820                                 .filter(p -> p.getName()
1821                                                 .equals(getInput.getInputName()))
1822                                 .findFirst();
1823                 if (!inputOpt.isPresent()) {
1824                         log.debug("#findInputByName - Failed to find the input {} ", getInput.getInputName());
1825                         rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, getInput.getInputName());
1826                 }
1827                 return inputOpt.get();
1828         }
1829
1830         private void fillGroupsFinalFields(List<GroupDefinition> groupsAsList) {
1831                 groupsAsList.forEach(groupDefinition -> {
1832                         groupDefinition.setInvariantName(groupDefinition.getName());
1833                         groupDefinition.setCreatedFrom(CreatedFrom.CSAR);
1834                 });
1835         }
1836
1837         private Resource updateGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
1838                 if (isEmpty(groups)) {
1839                         return resource;
1840                 }
1841                 return updateOrCreateGroups(resource, groups);
1842         }
1843
1844         private Resource updateOrCreateGroups(Resource resource, Map<String, GroupDefinition> groups) {
1845                 List<GroupDefinition> groupsFromResource = resource.getGroups();
1846                 List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
1847                 List<GroupDefinition> groupsToUpdate = new ArrayList<>();
1848                 List<GroupDefinition> groupsToDelete = new ArrayList<>();
1849                 List<GroupDefinition> groupsToCreate = new ArrayList<>();
1850                 if (isNotEmpty(groupsFromResource)) {
1851                         addGroupsToCreateOrUpdate(groupsFromResource, groupsAsList, groupsToUpdate, groupsToCreate);
1852                         addGroupsToDelete(groupsFromResource, groupsAsList, groupsToDelete);
1853                 } else {
1854                         groupsToCreate.addAll(groupsAsList);
1855                 }
1856                 if (isNotEmpty(groupsToCreate)) {
1857                         fillGroupsFinalFields(groupsToCreate);
1858                         if (isNotEmpty(groupsFromResource)) {
1859                                 groupBusinessLogic.addGroups(resource, groupsToCreate, true)
1860                                                 .left()
1861                                                 .on(this::throwComponentException);
1862                         } else {
1863                                 groupBusinessLogic.createGroups(resource, groupsToCreate, true)
1864                                                 .left()
1865                                                 .on(this::throwComponentException);
1866                         }
1867                 }
1868                 if (isNotEmpty(groupsToDelete)) {
1869                         groupBusinessLogic.deleteGroups(resource, groupsToDelete)
1870                                         .left()
1871                                         .on(this::throwComponentException);
1872                 }
1873                 if (isNotEmpty(groupsToUpdate)) {
1874                         groupBusinessLogic.updateGroups(resource, groupsToUpdate, true)
1875                                         .left()
1876                                         .on(this::throwComponentException);
1877                 }
1878                 return resource;
1879
1880         }
1881
1882         private void addGroupsToDelete(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
1883                                                                    List<GroupDefinition> groupsToDelete) {
1884                 for (GroupDefinition group : groupsFromResource) {
1885                         Optional<GroupDefinition> op = groupsAsList.stream()
1886                                         .filter(p -> p.getInvariantName()
1887                                                         .equalsIgnoreCase(group.getInvariantName()))
1888                                         .findAny();
1889                         if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts()
1890                                         .isEmpty())) {
1891                                 groupsToDelete.add(group);
1892                         }
1893                 }
1894         }
1895
1896         private void addGroupsToCreateOrUpdate(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
1897                                                                                    List<GroupDefinition> groupsToUpdate, List<GroupDefinition> groupsToCreate) {
1898                 for (GroupDefinition group : groupsAsList) {
1899                         Optional<GroupDefinition> op = groupsFromResource.stream()
1900                                         .filter(p -> p.getInvariantName()
1901                                                         .equalsIgnoreCase(group.getInvariantName()))
1902                                         .findAny();
1903                         if (op.isPresent()) {
1904                                 GroupDefinition groupToUpdate = op.get();
1905                                 groupToUpdate.setMembers(group.getMembers());
1906                                 groupToUpdate.setCapabilities(group.getCapabilities());
1907                                 groupToUpdate.setProperties(group.getProperties());
1908                                 groupsToUpdate.add(groupToUpdate);
1909                         } else {
1910                                 groupsToCreate.add(group);
1911                         }
1912                 }
1913         }
1914
1915         private Resource createInputsOnResource(Resource resource, Map<String, InputDefinition> inputs) {
1916                 List<InputDefinition> resourceProperties = resource.getInputs();
1917                 if (MapUtils.isNotEmpty(inputs) || isNotEmpty(resourceProperties)) {
1918
1919                         Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs,
1920                                         resource);
1921                         if (createInputs.isRight()) {
1922                                 loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,resource.getComponentMetadataForSupportLog(),
1923                                                 StatusCode.ERROR,"failed to add inputs from yaml: {}",createInputs.right()
1924                                                                 .value());
1925                                 throw new ByResponseFormatComponentException(createInputs.right()
1926                                                 .value());
1927                         }
1928                         resource.setInputs(createInputs.left().value());
1929                 }
1930                 return resource;
1931         }
1932
1933         private List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups,
1934                                                                                                                                    Resource component) {
1935
1936                 List<GroupDefinition> result = new ArrayList<>();
1937                 List<ComponentInstance> componentInstances = component.getComponentInstances();
1938
1939                 if (groups != null) {
1940                         Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups);
1941                         if (validateCyclicGroupsDependencies.isRight()) {
1942                                 throw new ByResponseFormatComponentException(validateCyclicGroupsDependencies.right().value());
1943                         }
1944                         for (Entry<String, GroupDefinition> entry : groups.entrySet()) {
1945                                 String groupName = entry.getKey();
1946                                 GroupDefinition groupDefinition = entry.getValue();
1947                                 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
1948                                 updatedGroupDefinition.setMembers(null);
1949                                 Map<String, String> members = groupDefinition.getMembers();
1950                                 if (members != null) {
1951                                         updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName,
1952                                                         members);
1953                                 }
1954                                 result.add(updatedGroupDefinition);
1955                         }
1956                 }
1957                 return result;
1958         }
1959
1960         private void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition,
1961                                                                         Resource component, List<ComponentInstance> componentInstances, String groupName,
1962                                                                         Map<String, String> members) {
1963                 Set<String> compInstancesNames = members.keySet();
1964
1965                 if (CollectionUtils.isEmpty(componentInstances)) {
1966                         String membersAstString = compInstancesNames.stream()
1967                                         .collect(joining(","));
1968                         log.debug(
1969                                         "The members: {}, in group: {}, cannot be found in component {}. There are no component instances.",
1970                                         membersAstString, groupName, component.getNormalizedName());
1971                         throw new ByActionStatusComponentException(
1972                                         ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString,
1973                                         groupName, component.getNormalizedName(), getComponentTypeForResponse(component));
1974                 }
1975                 // Find all component instances with the member names
1976                 Map<String, String> memberNames = componentInstances.stream()
1977                                 .collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
1978                 memberNames.putAll(groups.keySet()
1979                                 .stream()
1980                                 .collect(toMap(g -> g, g -> "")));
1981                 Map<String, String> relevantInstances = memberNames.entrySet()
1982                                 .stream()
1983                                 .filter(n -> compInstancesNames.contains(n.getKey()))
1984                                 .collect(toMap(Entry::getKey, Entry::getValue));
1985
1986                 if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
1987
1988                         List<String> foundMembers = new ArrayList<>();
1989                         if (relevantInstances != null) {
1990                                 foundMembers = relevantInstances.keySet()
1991                                                 .stream()
1992                                                 .collect(toList());
1993                         }
1994                         compInstancesNames.removeAll(foundMembers);
1995                         String membersAstString = compInstancesNames.stream()
1996                                         .collect(joining(","));
1997                         log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, groupName,
1998                                         component.getNormalizedName());
1999                         throw new ByActionStatusComponentException(
2000                                         ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString,
2001                                         groupName, component.getNormalizedName(), getComponentTypeForResponse(component));
2002                 }
2003                 updatedGroupDefinition.setMembers(relevantInstances);
2004         }
2005
2006         /**
2007          * This Method validates that there is no cyclic group dependencies. meaning
2008          * group A as member in group B which is member in group A
2009          *
2010          * @param allGroups
2011          * @return
2012          */
2013         private Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) {
2014
2015                 Either<Boolean, ResponseFormat> result = Either.left(true);
2016                 try {
2017                         Iterator<Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet()
2018                                         .iterator();
2019                         while (allGroupsItr.hasNext() && result.isLeft()) {
2020                                 Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next();
2021                                 // Fetches a group member A
2022                                 String groupAName = groupAEntry.getKey();
2023                                 // Finds all group members in group A
2024                                 Set<String> allGroupAMembersNames = new HashSet<>();
2025                                 fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames);
2026                                 // If A is a group member of itself found cyclic dependency
2027                                 if (allGroupAMembersNames.contains(groupAName)) {
2028                                         ResponseFormat responseFormat = componentsUtils
2029                                                         .getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
2030                                         result = Either.right(responseFormat);
2031                                 }
2032                         }
2033                 } catch (Exception e) {
2034                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2035                         result = Either.right(responseFormat);
2036                         log.debug("Exception occurred when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e);
2037                 }
2038                 return result;
2039         }
2040
2041         /**
2042          * This Method fills recursively the set groupMembers with all the members
2043          * of the given group which are also of type group.
2044          *
2045          * @param groupName
2046          * @param allGroups
2047          * @param allGroupMembers
2048          * @return
2049          */
2050         private void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups,
2051                                                                                                 Set<String> allGroupMembers) {
2052
2053                 // Found Cyclic dependency
2054                 if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) {
2055                         return;
2056                 }
2057                 GroupDefinition groupDefinition = allGroups.get(groupName);
2058                 // All Members Of Current Group Resource Instances & Other Groups
2059                 Set<String> currGroupMembers = groupDefinition.getMembers()
2060                                 .keySet();
2061                 // Filtered Members Of Current Group containing only members which
2062                 // are groups
2063                 List<String> currGroupFilteredMembers = currGroupMembers.stream()
2064                                 .
2065                                 // Keep Only Elements of type group and not Resource Instances
2066                                                 filter(allGroups::containsKey)
2067                                 .
2068                                 // Add Filtered Elements to main Set
2069                                                 peek(allGroupMembers::add)
2070                                 .
2071                                 // Collect results
2072                                                 collect(toList());
2073
2074                 // Recursively call the method for all the filtered group members
2075                 for (String innerGroupName : currGroupFilteredMembers) {
2076                         fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers);
2077                 }
2078
2079         }
2080
2081         private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups,
2082                                                                                                                            Set<String> allGroupMembers) {
2083
2084                 boolean stop = false;
2085                 // In Case Not Group Stop
2086                 if (!allGroups.containsKey(groupName)) {
2087                         stop = true;
2088                 }
2089                 // In Case Group Has no members stop
2090                 if (!stop) {
2091                         GroupDefinition groupDefinition = allGroups.get(groupName);
2092                         stop = isEmpty(groupDefinition.getMembers());
2093
2094                 }
2095                 // In Case all group members already contained stop
2096                 if (!stop) {
2097                         final Set<String> allMembers = allGroups.get(groupName)
2098                                         .getMembers()
2099                                         .keySet();
2100                         Set<String> membersOfTypeGroup = allMembers.stream()
2101                                         .
2102                                         // Filter In Only Group members
2103                                                         filter(allGroups::containsKey)
2104                                         .
2105                                         // Collect
2106                                                         collect(toSet());
2107                         stop = allGroupMembers.containsAll(membersOfTypeGroup);
2108                 }
2109                 return stop;
2110         }
2111
2112         private Resource createRIAndRelationsFromYaml(String yamlName, Resource resource,
2113                                                                                                   Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap, String topologyTemplateYaml,
2114                                                                                                   List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
2115                                                                                                   CsarInfo csarInfo,
2116                                                                                                   Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
2117                                                                                                   String nodeName) {
2118
2119                 log.debug("************* Going to create all nodes {}", yamlName);
2120                 handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate,
2121                                 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeName);
2122                 log.debug("************* Finished to create all nodes {}", yamlName);
2123                 log.debug("************* Going to create all resource instances {}", yamlName);
2124                 Map<String, Resource> existingNodeTypesByResourceNames = new HashMap<>();
2125                 resource = createResourceInstances(yamlName, resource, null, uploadComponentInstanceInfoMap,
2126                                 csarInfo.getCreatedNodes(), existingNodeTypesByResourceNames);
2127                 log.debug("************* Finished to create all resource instances {}", yamlName);
2128                 log.debug("************* Going to create all relations {}", yamlName);
2129                 resource = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, null, uploadComponentInstanceInfoMap, existingNodeTypesByResourceNames);
2130                 log.debug("************* Finished to create all relations {}", yamlName);
2131                 log.debug("************* Going to create positions {}", yamlName);
2132                 compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier()
2133                                 .getUserId());
2134                 log.debug("************* Finished to set positions {}", yamlName);
2135                 return resource;
2136         }
2137
2138         private void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts,
2139                                                                                                         List<ArtifactDefinition> artifactsToAdd) {
2140                 List<String> vfcArtifactNames = vfcArtifacts.stream()
2141                                 .map(ArtifactDataDefinition::getArtifactName)
2142                                 .collect(toList());
2143                 artifactsToAdd.stream()
2144                                 .forEach(a -> {
2145                                         if (!vfcArtifactNames.contains(a.getArtifactName())) {
2146                                                 vfcArtifacts.add(a);
2147                                         } else {
2148                                                 log.debug("Can't upload two artifact with the same name {}. ", a.getArtifactName());
2149                                         }
2150                                 });
2151
2152         }
2153
2154         @SuppressWarnings("unchecked")
2155         private void handleNodeTypes(String yamlName, Resource resource, String topologyTemplateYaml, boolean needLock,
2156                                                                  Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
2157                                                                  List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
2158                                                                  CsarInfo csarInfo, String nodeName) {
2159                 try {
2160                         for (Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
2161                                 if (nodeTypeEntry.getValue()
2162                                                 .isNested()) {
2163
2164                                         handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo,
2165                                                         csarInfo, nodeTypeEntry.getKey());
2166                                         log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
2167                                 }
2168                         }
2169                         Map<String, Object> mappedToscaTemplate = null;
2170                         if (StringUtils.isNotEmpty(nodeName) && isNotEmpty(nodeTypesInfo) && nodeTypesInfo.containsKey(nodeName)) {
2171                                 mappedToscaTemplate = nodeTypesInfo.get(nodeName)
2172                                                 .getMappedToscaTemplate();
2173                         }
2174                         if (isEmpty(mappedToscaTemplate)) {
2175                                 mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
2176                         }
2177                         createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock,
2178                                         nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
2179                 } catch (ComponentException e) {
2180                         ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat()
2181                                         : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
2182                         componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
2183                                         AuditingActionEnum.IMPORT_RESOURCE);
2184                         throw e;
2185                 } catch (StorageException e) {
2186                         ResponseFormat responseFormat = componentsUtils
2187                                         .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
2188                         componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
2189                                         AuditingActionEnum.IMPORT_RESOURCE);
2190                         throw e;
2191                 }
2192         }
2193
2194         private Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo,
2195                                                                                                                                    List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock,
2196                                                                                                                                    boolean inTransaction) {
2197
2198                 if (csarInfo.getCsar() != null) {
2199                         String vendorLicenseModelId = null;
2200                         String vfLicenseModelId = null;
2201
2202                         if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE) {
2203                                 Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts();
2204                                 if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
2205                                         for (Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
2206                                                 if (artifactEntry.getValue()
2207                                                                 .getArtifactName()
2208                                                                 .equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) {
2209                                                         vendorLicenseModelId = artifactEntry.getValue()
2210                                                                         .getUniqueId();
2211                                                 }
2212                                                 if (artifactEntry.getValue()
2213                                                                 .getArtifactName()
2214                                                                 .equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) {
2215                                                         vfLicenseModelId = artifactEntry.getValue()
2216                                                                         .getUniqueId();
2217                                                 }
2218                                         }
2219                                 }
2220
2221                         }
2222                         // Specific Behavior for license artifacts
2223                         createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
2224                                         CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL,
2225                                         ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
2226                                         Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME,
2227                                         Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, true,
2228                                         shouldLock, inTransaction);
2229                         createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
2230                                         CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
2231                                         ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL,
2232                                         Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId,
2233                                         artifactOperation, null, true, shouldLock, inTransaction);
2234
2235                         Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource,
2236                                         createdArtifacts, shouldLock, inTransaction, artifactOperation);
2237                         if (eitherCreateResult.isRight()) {
2238                                 return Either.right(eitherCreateResult.right()
2239                                                 .value());
2240                         }
2241
2242                         Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils
2243                                         .getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
2244
2245                         if (artifacsMetaCsarStatus.isLeft()) {
2246                                 String artifactsFileName = artifacsMetaCsarStatus.left()
2247                                                 .value()
2248                                                 .getKey();
2249                                 String artifactsContents = artifacsMetaCsarStatus.left()
2250                                                 .value()
2251                                                 .getValue();
2252                                 Either<Resource, ResponseFormat> createArtifactsFromCsar;
2253                                 if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
2254                                         createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.createResourceArtifactsFromCsar(
2255                                                         csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts);
2256                                 } else {
2257                                         createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.updateResourceArtifactsFromCsar(
2258                                                         csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock,
2259                                                         inTransaction);
2260                                 }
2261
2262                                 if (createArtifactsFromCsar.isRight()) {
2263                                         log.debug("Couldn't create artifacts from artifacts.meta");
2264                                         return Either.right(createArtifactsFromCsar.right()
2265                                                         .value());
2266                                 }
2267
2268                                 return Either.left(createArtifactsFromCsar.left()
2269                                                 .value());
2270                         } else {
2271
2272                                 return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(resource, csarInfo, shouldLock,
2273                                                 inTransaction);
2274
2275                         }
2276                 }
2277                 return Either.left(resource);
2278         }
2279
2280         private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, CsarInfo csarInfo,
2281                                                                                                                                                                 String artifactPath, String artifactFileName, String artifactType, ArtifactGroupTypeEnum artifactGroupType,
2282                                                                                                                                                                 String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId,
2283                                                                                                                                                                 ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, boolean isFromCsar,
2284                                                                                                                                                                 boolean shouldLock, boolean inTransaction) {
2285                 byte[] artifactFileBytes = null;
2286
2287                 if (csarInfo.getCsar()
2288                                 .containsKey(artifactPath)) {
2289                         artifactFileBytes = csarInfo.getCsar()
2290                                         .get(artifactPath);
2291                 }
2292                 Either<Boolean, ResponseFormat> result = Either.left(true);
2293                 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE
2294                                 || operation.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE) {
2295                         if (isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) {
2296                                 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic
2297                                                 .handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(),
2298                                                                 AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource, shouldLock,
2299                                                                 inTransaction);
2300                                 if (handleDelete.isRight()) {
2301                                         result = Either.right(handleDelete.right()
2302                                                         .value());
2303                                 } else {
2304                                         Either<ArtifactDefinition, Operation> value = handleDelete.left().value();
2305                                         if (value.isLeft()) {
2306                                                 String updatedArtifactId = value.left().value().getUniqueId();
2307                                                 if (artifactGroupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
2308                                                         resource.getDeploymentArtifacts().remove(updatedArtifactId);
2309                                                 } else {
2310                                                         resource.getArtifacts().remove(updatedArtifactId);
2311                                                 }
2312                                         }
2313                                 }
2314                                 return result;
2315                         }
2316
2317                         if (StringUtils.isEmpty(artifactId) && artifactFileBytes != null) {
2318                                 operation = artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
2319                                                 ArtifactOperationEnum.CREATE);
2320                         }
2321
2322                 }
2323                 if (artifactFileBytes != null) {
2324                         Map<String, Object> vendorLicenseModelJson = ArtifactUtils.buildJsonForUpdateArtifact(artifactId,
2325                                         artifactFileName, artifactType, artifactGroupType, artifactLabel, artifactDisplayName,
2326                                         artifactDescription, artifactFileBytes, null, isFromCsar);
2327                         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic
2328                                         .createOrUpdateCsarArtifactFromJson(resource, csarInfo.getModifier(), vendorLicenseModelJson,
2329                                                         operation);
2330                         addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
2331                         if (eitherNonMetaArtifacts.isRight()) {
2332                                 BeEcompErrorManager.getInstance()
2333                                                 .logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: "
2334                                                                                 + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(),
2335                                                                 ErrorSeverity.WARNING);
2336                                 return Either.right(eitherNonMetaArtifacts.right()
2337                                                 .value());
2338                         }
2339                         ArtifactDefinition artifactDefinition = eitherNonMetaArtifacts.left().value().left().value();
2340                         createOrUpdateResourceWithUpdatedArtifact(artifactDefinition,resource, artifactGroupType);
2341                 }
2342
2343                 return result;
2344         }
2345
2346         private void createOrUpdateResourceWithUpdatedArtifact(ArtifactDefinition artifact, Resource resource, ArtifactGroupTypeEnum groupTypeEnum) {
2347                 if (groupTypeEnum == ArtifactGroupTypeEnum.DEPLOYMENT) {
2348                         resource.getDeploymentArtifacts().put(artifact.getArtifactLabel(), artifact);
2349                 } else {
2350                         resource.getArtifacts().put(artifact.getArtifactLabel(), artifact);
2351                 }
2352         }
2353
2354         private boolean isArtifactDeletionRequired(String artifactId, byte[] artifactFileBytes, boolean isFromCsar) {
2355                 return !StringUtils.isEmpty(artifactId) && artifactFileBytes == null && isFromCsar;
2356         }
2357
2358         private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation,
2359                                                                                                                          List<ArtifactDefinition> createdArtifacts,
2360                                                                                                                          Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
2361                 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && createdArtifacts != null
2362                                 && eitherNonMetaArtifacts.isLeft()) {
2363                         Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left()
2364                                         .value();
2365                         if (eitherResult.isLeft()) {
2366                                 createdArtifacts.add(eitherResult.left()
2367                                                 .value());
2368                         }
2369                 }
2370         }
2371
2372         private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource,
2373                                                                                                                                                         List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
2374                                                                                                                                                         ArtifactOperationInfo artifactOperation) {
2375
2376                 Either<Resource, ResponseFormat> resStatus = null;
2377                 Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
2378
2379                 try {
2380                         Either<List<NonMetaArtifactInfo>, String> artifactPathAndNameList = getValidArtifactNames(csarInfo,
2381                                         collectedWarningMessages);
2382                         if (artifactPathAndNameList.isRight()) {
2383                                 return Either.right(getComponentsUtils().getResponseFormatByArtifactId(
2384                                                 ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right()
2385                                                                 .value()));
2386                         }
2387                         EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
2388
2389                         if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
2390                                 vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
2391                                 vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left()
2392                                                 .value());
2393                         } else {
2394                                 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(
2395                                                 resource, artifactPathAndNameList.left()
2396                                                                 .value(),
2397                                                 csarInfo.getModifier());
2398
2399                                 if (findVfCsarArtifactsToHandleRes.isRight()) {
2400                                         resStatus = Either.right(findVfCsarArtifactsToHandleRes.right()
2401                                                         .value());
2402                                 }
2403                                 if (resStatus == null) {
2404                                         vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left()
2405                                                         .value();
2406                                 }
2407                         }
2408                         if (resStatus == null && vfCsarArtifactsToHandle != null) {
2409                                 resStatus = processCsarArtifacts(csarInfo, resource, createdArtifacts, shouldLock, inTransaction,
2410                                                 resStatus, vfCsarArtifactsToHandle);
2411                         }
2412                         if (resStatus == null) {
2413                                 resStatus = Either.left(resource);
2414                         }
2415                 } catch (Exception e) {
2416                         resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2417                         log.debug("Exception occurred in createNonMetaArtifacts, message:{}", e.getMessage(), e);
2418                 } finally {
2419                         CsarUtils.handleWarningMessages(collectedWarningMessages);
2420                 }
2421                 return resStatus;
2422         }
2423
2424         private Either<Resource, ResponseFormat> processCsarArtifacts(CsarInfo csarInfo, Resource resource,
2425                                                                                                                                   List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
2426                                                                                                                                   Either<Resource, ResponseFormat> resStatus,
2427                                                                                                                                   EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle) {
2428                 for (Entry<ArtifactOperationEnum, List<NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle
2429                                 .entrySet()) {
2430
2431                         Optional<ResponseFormat> optionalCreateInDBError =
2432                                         // Stream of artifacts to be created
2433                                         currArtifactOperationPair.getValue()
2434                                                         .stream()
2435                                                         // create each artifact
2436                                                         .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(),
2437                                                                         e.getArtifactName(), e.getArtifactType()
2438                                                                                         .getType(),
2439                                                                         e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
2440                                                                         CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(),
2441                                                                         artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
2442                                                                                         currArtifactOperationPair.getKey()),
2443                                                                         createdArtifacts, e.isFromCsar(), shouldLock, inTransaction))
2444                                                         // filter in only error
2445                                                         .filter(Either::isRight)
2446                                                         .
2447                                                         // Convert the error from either to
2448                                                         // ResponseFormat
2449                                                                         map(e -> e.right()
2450                                                                         .value())
2451                                                         .
2452                                                         // Check if an error occurred
2453                                                                         findAny();
2454                         // Error found on artifact Creation
2455                         if (optionalCreateInDBError.isPresent()) {
2456                                 resStatus = Either.right(optionalCreateInDBError.get());
2457                                 break;
2458                         }
2459                 }
2460                 return resStatus;
2461         }
2462
2463         private Either<List<NonMetaArtifactInfo>, String> getValidArtifactNames(CsarInfo csarInfo,
2464                                                                                                                                                         Map<String, Set<List<String>>> collectedWarningMessages) {
2465                 List<NonMetaArtifactInfo> artifactPathAndNameList =
2466                                 // Stream of file paths contained in csar
2467                                 csarInfo.getCsar()
2468                                                 .entrySet()
2469                                                 .stream()
2470                                                 // Filter in only VF artifact path location
2471                                                 .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN)
2472                                                                 .matcher(e.getKey())
2473                                                                 .matches())
2474                                                 // Validate and add warnings
2475                                                 .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), collectedWarningMessages))
2476                                                 // Filter in Non Warnings
2477                                                 .filter(Either::isLeft)
2478                                                 // Convert from Either to NonMetaArtifactInfo
2479                                                 .map(e -> e.left()
2480                                                                 .value())
2481                                                 // collect to List
2482                                                 .collect(toList());
2483                 Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
2484                 for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
2485                         if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName())
2486                                         .matches()) {
2487                                 return Either.right(nonMetaArtifactInfo.getArtifactName());
2488                         }
2489                 }
2490                 return Either.left(artifactPathAndNameList);
2491         }
2492
2493         private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(
2494                         Resource resource, List<NonMetaArtifactInfo> artifactPathAndNameList, User user) {
2495
2496                 List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
2497                 // collect all Deployment and Informational artifacts of VF
2498                 if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts()
2499                                 .isEmpty()) {
2500                         existingArtifacts.addAll(resource.getDeploymentArtifacts()
2501                                         .values());
2502                 }
2503                 if (resource.getArtifacts() != null && !resource.getArtifacts()
2504                                 .isEmpty()) {
2505                         existingArtifacts.addAll(resource.getArtifacts()
2506                                         .values());
2507                 }
2508                 existingArtifacts = existingArtifacts.stream()
2509                                 // filter MANDATORY artifacts, LICENSE artifacts and artifacts
2510                                 // was created from HEAT.meta
2511                                 .filter(this::isNonMetaArtifact)
2512                                 .collect(toList());
2513
2514                 List<String> artifactsToIgnore = new ArrayList<>();
2515                 // collect IDs of Artifacts of VF which belongs to any group
2516                 if (resource.getGroups() != null) {
2517                         resource.getGroups()
2518                                         .stream()
2519                                         .forEach(g -> {
2520                                                 if (g.getArtifacts() != null && !g.getArtifacts()
2521                                                                 .isEmpty()) {
2522                                                         artifactsToIgnore.addAll(g.getArtifacts());
2523                                                 }
2524                                         });
2525                 }
2526                 existingArtifacts = existingArtifacts.stream()
2527                                 // filter artifacts which belongs to any group
2528                                 .filter(a -> !artifactsToIgnore.contains(a.getUniqueId()))
2529                                 .collect(toList());
2530                 return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user);
2531         }
2532
2533         private boolean isNonMetaArtifact(ArtifactDefinition artifact) {
2534                 boolean result = true;
2535                 if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) {
2536                         result = false;
2537                 }
2538                 return result;
2539         }
2540
2541         private boolean isValidArtifactType(ArtifactDefinition artifact) {
2542                 boolean result = true;
2543                 if (artifact.getArtifactType() == null
2544                                 || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE
2545                                 || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) {
2546                         result = false;
2547                 }
2548                 return result;
2549         }
2550
2551         private Resource createResourceInstancesRelations(User user, String yamlName, Resource resource, Resource oldResource,
2552                                                                                                           Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, Map<String, Resource> existingNodeTypesByResourceNames) {
2553                 log.debug("#createResourceInstancesRelations - Going to create relations ");
2554                 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),     StatusCode.STARTED,"Start to create relations");
2555                 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
2556                 if (isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)  &&
2557                 resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances {
2558                         log.debug(
2559                                         "#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ",
2560                                         resource.getUniqueId(), yamlName);
2561                         loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),     StatusCode.ERROR,"No instances found in the resource: {}, is empty, yaml template file name: {}",resource.getName(),yamlName);
2562                         BeEcompErrorManager.getInstance()
2563                                         .logInternalDataError("createResourceInstancesRelations",
2564                                                         "No instances found in a resource or nn yaml template. ", ErrorSeverity.ERROR);
2565                         throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2566                 }
2567                 Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
2568                 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
2569                 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
2570                 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
2571                 Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
2572                 Map<String, List<PropertyDefinition>> instAttributes = new HashMap<>();
2573                 List<RequirementCapabilityRelDef> relations = new ArrayList<>();
2574                 Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
2575
2576                 log.debug("#createResourceInstancesRelations - Before get all datatypes. ");
2577         Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll();
2578                 if (allDataTypes.isRight()) {
2579                         JanusGraphOperationStatus status = allDataTypes.right()
2580                                         .value();
2581                         BeEcompErrorManager.getInstance()
2582                                         .logInternalFlowError("UpdatePropertyValueOnComponentInstance",
2583                                                         "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
2584                         loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),
2585                                         StatusCode.ERROR,"ERROR while update property value on instance. Status is: "+status);
2586                         throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(
2587                                         DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)), yamlName);
2588
2589                 }
2590                 Resource finalResource = resource;
2591                 uploadResInstancesMap.values()
2592                                 .forEach(i -> processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes,
2593                                                 instProperties, instCapabilities, instRequirements, instDeploymentArtifacts, instArtifacts,
2594                                                 instAttributes, existingNodeTypesByResourceNames, instInputs, i));
2595                 resource.getComponentInstances()
2596                                 .stream()
2597                                 .filter(i -> !i.isCreatedFromCsar())
2598                                 .forEach(i->processUiComponentInstance(oldResource, i, instCapabilities, instRequirements, instDeploymentArtifacts, instArtifacts, instProperties, instInputs, instAttributes));
2599
2600                 associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties);
2601                 associateComponentInstanceInputsToComponent(yamlName, resource, instInputs);
2602                 associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts);
2603                 associateArtifactsToInstances(yamlName, resource, instArtifacts);
2604                 associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements);
2605                 associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes);
2606                 addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations);
2607                 associateResourceInstances(yamlName, resource, relations);
2608                 handleSubstitutionMappings(resource, uploadResInstancesMap);
2609                 log.debug("************* in create relations, getResource start");
2610                 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),     StatusCode.COMPLETE,"create relations");
2611                 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
2612                                 .getToscaFullElement(resource.getUniqueId());
2613                 log.debug("************* in create relations, getResource end");
2614                 if (eitherGetResource.isRight()) {
2615                         loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),
2616                                         StatusCode.ERROR,"ERROR while create relations");
2617                         throw new ByResponseFormatComponentException(componentsUtils
2618                                         .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right()
2619                                                         .value()), resource));
2620                 }
2621                 return eitherGetResource.left()
2622                                 .value();
2623         }
2624
2625         private void processUiComponentInstance(Resource oldResource, ComponentInstance instance,
2626                                                                                         Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
2627                                                                                         Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements,
2628                                                                                         Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
2629                                                                                         Map<String, Map<String, ArtifactDefinition>> instArtifacts, Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, List<ComponentInstanceInput>> instInputs, Map<String, List<PropertyDefinition>> instAttributes) {
2630                 Optional<ComponentInstance> foundInstance = findInstance(oldResource, instance);
2631                 if(foundInstance.isPresent()){
2632                         if(MapUtils.isNotEmpty(foundInstance.get().getCapabilities())){
2633                                 instCapabilities.put(instance, foundInstance.get().getCapabilities());
2634                         }
2635                         if(MapUtils.isNotEmpty(foundInstance.get().getRequirements())){
2636                                 instRequirements.put(instance, foundInstance.get().getRequirements());
2637                         }
2638                         if(MapUtils.isNotEmpty(foundInstance.get().getDeploymentArtifacts())){
2639                                 instDeploymentArtifacts.put(instance.getUniqueId(), foundInstance.get().getDeploymentArtifacts());
2640                         }
2641                         if(MapUtils.isNotEmpty(foundInstance.get().getArtifacts())){
2642                                 instArtifacts.put(instance.getUniqueId(), foundInstance.get().getArtifacts());
2643                         }
2644                         if(MapUtils.isNotEmpty(oldResource.getComponentInstancesProperties()) &&
2645                                         CollectionUtils.isNotEmpty(oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId()))){
2646                                 instProperties.put(instance.getUniqueId(), oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId()));
2647                         }
2648                         if(MapUtils.isNotEmpty(oldResource.getComponentInstancesInputs()) &&
2649                                         CollectionUtils.isNotEmpty(oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId()))){
2650                                 instInputs.put(instance.getUniqueId(), oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId()));
2651                         }
2652                         if(MapUtils.isNotEmpty(oldResource.getComponentInstancesAttributes()) &&
2653                                         CollectionUtils.isNotEmpty(oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()))){
2654                                 instAttributes.put(instance.getUniqueId(), oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()).stream().map(PropertyDefinition::new).collect(toList()));
2655                         }
2656                 }
2657         }
2658
2659         private Optional<ComponentInstance> findInstance(Resource oldResource, ComponentInstance instance) {
2660                 if(oldResource != null && CollectionUtils.isNotEmpty(oldResource.getComponentInstances())) {
2661                         return oldResource.getComponentInstances().stream().filter(i -> i.getName().equals(instance.getName())).findFirst();
2662                 }
2663                 return Optional.empty();
2664         }
2665
2666         private void associateResourceInstances(String yamlName, Resource resource,
2667                                                                                         List<RequirementCapabilityRelDef> relations) {
2668                 Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> relationsEither = toscaOperationFacade.associateResourceInstances(resource, resource.getUniqueId(), relations);
2669
2670                 if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) {
2671                         StorageOperationStatus status = relationsEither.right().value();
2672                         log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(),
2673                                         status);
2674                         throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), yamlName);
2675                 } else {
2676                         setResourceInstanceRelationsOnComponent(resource, relationsEither.left().value());
2677                 }
2678         }
2679
2680         private void associateInstAttributeToComponentToInstances(String yamlName, Resource resource,
2681                                                                                                                           Map<String, List<PropertyDefinition>> instAttributes) {
2682                 StorageOperationStatus addArtToInst;
2683                 addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes,
2684                                 resource);
2685                 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2686                         log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
2687                                         addArtToInst);
2688                         throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
2689                 }
2690         }
2691
2692         private void associateOrAddCalculatedCapReq(String yamlName, Resource resource,
2693                                                                                                 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
2694                                                                                                 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
2695                 StorageOperationStatus addArtToInst;
2696                 addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements,
2697                                 resource);
2698                 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2699                         log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(),
2700                                         addArtToInst);
2701                         throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
2702                 }
2703         }
2704
2705         private void associateArtifactsToInstances(String yamlName, Resource resource,
2706                                                                                            Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
2707                 StorageOperationStatus addArtToInst;
2708
2709                 addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource);
2710                 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2711                         log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2712                         throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
2713                 }
2714         }
2715
2716         private void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource,
2717                                                                                                                  Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
2718                 StorageOperationStatus addArtToInst = toscaOperationFacade
2719                                 .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user);
2720                 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2721                         log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2722                         throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
2723                 }
2724         }
2725
2726         private void associateComponentInstanceInputsToComponent(String yamlName, Resource resource,
2727                                                                                                                          Map<String, List<ComponentInstanceInput>> instInputs) {
2728                 if (MapUtils.isNotEmpty(instInputs)) {
2729                         Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
2730                                         .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
2731                         if (addInputToInst.isRight()) {
2732
2733                                 StorageOperationStatus addInputToInstError = addInputToInst.right().value();
2734                                 log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(),
2735                                                 addInputToInstError);
2736                                 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addInputToInstError), yamlName);
2737                         }
2738                         setComponentInstanceInputsOnComponent(resource, instInputs);
2739                 }
2740         }
2741
2742         private void setComponentInstanceInputsOnComponent(Resource resource, Map<String, List<ComponentInstanceInput>> instInputs) {
2743                 Map<String, List<ComponentInstanceInput>> componentInstancesInputs = resource.getComponentInstancesInputs();
2744                 if (componentInstancesInputs == null)
2745                         componentInstancesInputs = new HashMap<>();
2746                 componentInstancesInputs.putAll(instInputs);
2747                 resource.setComponentInstancesInputs(componentInstancesInputs);
2748         }
2749
2750         private void associateComponentInstancePropertiesToComponent(String yamlName, Resource resource,
2751                                                                                                                                  Map<String, List<ComponentInstanceProperty>> instProperties) {
2752                 Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
2753                                 .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
2754                 if (addPropToInst.isRight()) {
2755                         loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),
2756                                         StatusCode.ERROR,"ERROR while  associate compnent insatnce properties of resource: {} status is: {}",resource.getName(),addPropToInst.right().value());
2757                         StorageOperationStatus storageOperationStatus = addPropToInst.right().value();
2758                         log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(),
2759                                         storageOperationStatus);
2760                         throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageOperationStatus), yamlName);
2761                 }
2762                 setComponentInstancePropertiesOnComponent(resource, instProperties);
2763         }
2764
2765         private void setComponentInstancePropertiesOnComponent(Resource resource, Map<String, List<ComponentInstanceProperty>> instProperties) {
2766                 Map<String, List<ComponentInstanceProperty>> componentInstanceProps = resource.getComponentInstancesProperties();
2767                 if (componentInstanceProps == null )
2768                         componentInstanceProps = new HashMap<>();
2769                 componentInstanceProps.putAll(instProperties);
2770                 resource.setComponentInstancesProperties(componentInstanceProps);
2771         }
2772
2773         private void handleSubstitutionMappings(Resource resource,
2774                                                                                         Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2775                 if (resource.getResourceType() == ResourceTypeEnum.CVFC) {
2776                         Either<Resource, StorageOperationStatus> getResourceRes =
2777                                         updateCalculatedCapReqWithSubstitutionMappings(resource, uploadResInstancesMap);
2778                         if (getResourceRes.isRight()) {
2779                                 ResponseFormat responseFormat = componentsUtils
2780                                                 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResourceRes.right()
2781                                                                 .value()), resource);
2782                                 throw new ByResponseFormatComponentException(responseFormat);
2783                         }
2784                 }
2785         }
2786
2787         private void addRelationsToRI(String yamlName, Resource resource,
2788                                                                   Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2789                                                                   List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) {
2790                 for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
2791                         UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
2792                         ComponentInstance currentCompInstance = null;
2793                         for (ComponentInstance compInstance : componentInstancesList) {
2794
2795                                 if (compInstance.getName()
2796                                                 .equals(uploadComponentInstanceInfo.getName())) {
2797                                         currentCompInstance = compInstance;
2798                                         break;
2799                                 }
2800
2801                         }
2802                         if (currentCompInstance == null) {
2803                                 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
2804                                                 resource.getUniqueId());
2805                                 BeEcompErrorManager.getInstance()
2806                                                 .logInternalDataError(
2807                                                                 COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
2808                                                                 resource.getUniqueId(), ErrorSeverity.ERROR);
2809                                 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2810                         }
2811
2812                         ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
2813                         if (addRelationToRiRes.getStatus() != 200) {
2814                                 throw new ByResponseFormatComponentException(addRelationToRiRes);
2815                         }
2816                 }
2817
2818         }
2819
2820         private void setResourceInstanceRelationsOnComponent(Resource resource, List<RequirementCapabilityRelDef> relations) {
2821                 if (resource.getComponentInstancesRelations() != null) {
2822                         /*Map<String, RequirementCapabilityRelDef> relationsMapByUid = resource.getComponentInstancesRelations().stream().collect(Collectors.toMap(r -> r.getUid(), r -> r));
2823                         Map<String, RequirementCapabilityRelDef> updatedRelationsByUid = relations.stream().collect(Collectors.toMap(r -> r.getUid(), r -> r));
2824                         relationsMapByUid.putAll(updatedRelationsByUid);
2825                         resource.setComponentInstancesRelations(new ArrayList<>(relationsMapByUid.values()));*/
2826                         resource.getComponentInstancesRelations().addAll(relations);
2827                 } else {
2828                         resource.setComponentInstancesRelations(relations);
2829                 }
2830         }
2831
2832         private void processComponentInstance(String yamlName, Resource resource,
2833                                                                                   List<ComponentInstance> componentInstancesList,
2834                                                                                   Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
2835                                                                                   Map<String, List<ComponentInstanceProperty>> instProperties,
2836                                                                                   Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
2837                                                                                   Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements,
2838                                                                                   Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
2839                                                                                   Map<String, Map<String, ArtifactDefinition>> instArtifacts,
2840                                                                                   Map<String, List<PropertyDefinition>> instAttributes, Map<String, Resource> originCompMap,
2841                                                                                   Map<String, List<ComponentInstanceInput>> instInputs,
2842                                                                                   UploadComponentInstanceInfo uploadComponentInstanceInfo) {
2843                 Optional<ComponentInstance> currentCompInstanceOpt = componentInstancesList.stream()
2844                                 .filter(i -> i.getName()
2845                                                 .equals(uploadComponentInstanceInfo.getName()))
2846                                 .findFirst();
2847                 if (!currentCompInstanceOpt.isPresent()) {
2848                         log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
2849                                         resource.getUniqueId());
2850                         BeEcompErrorManager.getInstance()
2851                                         .logInternalDataError(
2852                                                         COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
2853                                                         resource.getUniqueId(), ErrorSeverity.ERROR);
2854                         throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2855                 }
2856                 ComponentInstance currentCompInstance = currentCompInstanceOpt.get();
2857                 String resourceInstanceId = currentCompInstance.getUniqueId();
2858                 Resource originResource = getOriginResource(originCompMap, currentCompInstance);
2859                 if (isNotEmpty(originResource.getRequirements())) {
2860                         instRequirements.put(currentCompInstance, originResource.getRequirements());
2861                 }
2862                 if (isNotEmpty(originResource.getCapabilities())) {
2863                         processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo,
2864                                         currentCompInstance, originResource);
2865                 }
2866                 if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts()
2867                                 .isEmpty()) {
2868                         instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
2869                 }
2870                 if (originResource.getArtifacts() != null && !originResource.getArtifacts()
2871                                 .isEmpty()) {
2872                         instArtifacts.put(resourceInstanceId, originResource.getArtifacts());
2873                 }
2874                 if (originResource.getAttributes() != null && !originResource.getAttributes()
2875                                 .isEmpty()) {
2876                         instAttributes.put(resourceInstanceId, originResource.getAttributes());
2877                 }
2878                 if (originResource.getResourceType() != ResourceTypeEnum.CVFC) {
2879                         ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource,
2880                                         originResource, currentCompInstance, instProperties, allDataTypes.left()
2881                                                         .value());
2882                         if (addPropertiesValueToRiRes.getStatus() != 200) {
2883                                 throw new ByResponseFormatComponentException(addPropertiesValueToRiRes);
2884                         }
2885                 } else {
2886                         addInputsValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, instInputs,
2887                                         allDataTypes.left()
2888                                                         .value());
2889                 }
2890         }
2891
2892         private Resource getOriginResource(Map<String, Resource> originCompMap, ComponentInstance currentCompInstance) {
2893                 Resource originResource;
2894                 if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
2895                         Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade
2896                                         .getToscaFullElement(currentCompInstance.getComponentUid());
2897                         if (getOriginResourceRes.isRight()) {
2898                                 log.debug("failed to fetch resource with uniqueId {} and tosca component name {} status is {}",
2899                                                 currentCompInstance.getComponentUid(), currentCompInstance.getToscaComponentName(),
2900                                                 getOriginResourceRes);
2901                                 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getOriginResourceRes.right()
2902                                                 .value()), currentCompInstance.getComponentUid());
2903                         }
2904                         originResource = getOriginResourceRes.left()
2905                                         .value();
2906                         originCompMap.put(originResource.getUniqueId(), originResource);
2907                 } else {
2908                         originResource = originCompMap.get(currentCompInstance.getComponentUid());
2909                 }
2910                 return originResource;
2911         }
2912
2913         private void processComponentInstanceCapabilities(
2914                         Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
2915                         Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
2916                         UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance,
2917                         Resource originResource) {
2918                 Map<String, List<CapabilityDefinition>> originCapabilities;
2919                 if (isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) {
2920                         originCapabilities = new HashMap<>();
2921                         Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>();
2922                         originResource.getCapabilities()
2923                                         .forEach((k, v) -> addCapabilities(originCapabilities, k, v));
2924                         uploadComponentInstanceInfo.getCapabilities()
2925                                         .values()
2926                                         .forEach(l -> addCapabilitiesProperties(newPropertiesMap, l));
2927                         updateCapabilityPropertiesValues(allDataTypes, originCapabilities, newPropertiesMap);
2928                 } else {
2929                         originCapabilities = originResource.getCapabilities();
2930                 }
2931                 instCapabilties.put(currentCompInstance, originCapabilities);
2932         }
2933
2934         private void updateCapabilityPropertiesValues(
2935                         Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
2936                         Map<String, List<CapabilityDefinition>> originCapabilities,
2937                         Map<String, Map<String, UploadPropInfo>> newPropertiesMap) {
2938                 originCapabilities.values()
2939                                 .stream()
2940                                 .flatMap(Collection::stream)
2941                                 .filter(c -> newPropertiesMap.containsKey(c.getName()))
2942                                 .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()),
2943                                                 allDataTypes.left()
2944                                                                 .value()));
2945         }
2946
2947         private void addCapabilitiesProperties(Map<String, Map<String, UploadPropInfo>> newPropertiesMap,
2948                                                                                    List<UploadCapInfo> capabilities) {
2949                 for (UploadCapInfo capability : capabilities) {
2950                         if (isNotEmpty(capability.getProperties())) {
2951                                 newPropertiesMap.put(capability.getName(), capability.getProperties()
2952                                                 .stream()
2953                                                 .collect(toMap(UploadInfo::getName, p -> p)));
2954                         }
2955                 }
2956         }
2957
2958         private void addCapabilities(Map<String, List<CapabilityDefinition>> originCapabilities, String type,
2959                                                                  List<CapabilityDefinition> capabilities) {
2960                 List<CapabilityDefinition> list = capabilities.stream()
2961                                 .map(CapabilityDefinition::new)
2962                                 .collect(toList());
2963                 originCapabilities.put(type, list);
2964         }
2965
2966         private void updatePropertyValues(List<ComponentInstanceProperty> properties,
2967                                                                           Map<String, UploadPropInfo> newProperties, Map<String, DataTypeDefinition> allDataTypes) {
2968                 properties.forEach(p -> updatePropertyValue(p, newProperties.get(p.getName()), allDataTypes));
2969         }
2970
2971         private String updatePropertyValue(ComponentInstanceProperty property, UploadPropInfo propertyInfo,
2972                                                                            Map<String, DataTypeDefinition> allDataTypes) {
2973                 String value = null;
2974                 List<GetInputValueDataDefinition> getInputs = null;
2975                 boolean isValidate = true;
2976                 if (null != propertyInfo && propertyInfo.getValue() != null) {
2977                         getInputs = propertyInfo.getGet_input();
2978                         isValidate = getInputs == null || getInputs.isEmpty();
2979                         if (isValidate) {
2980                                 value = getPropertyJsonStringValue(propertyInfo.getValue(), property.getType());
2981                         } else {
2982                                 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2983                                                 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
2984                         }
2985                 }
2986                 property.setValue(value);
2987         return validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
2988         }
2989
2990         private Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource,
2991                                                                                                                                                                                                         Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2992                 Either<Resource, StorageOperationStatus> updateRes = null;
2993                 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>();
2994                 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>();
2995                 StorageOperationStatus status = toscaOperationFacade
2996                                 .deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId());
2997                 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2998                         log.debug(
2999                                         "Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}",
3000                                         resource.getUniqueId(), status);
3001                         updateRes = Either.right(status);
3002                 }
3003                 if (updateRes == null) {
3004                         fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap,
3005                                         updatedInstCapabilities, updatedInstRequirements);
3006                         status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities,
3007                                         updatedInstRequirements, resource);
3008                         if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
3009                                 log.debug(
3010                                                 "Failed to associate capabilities and requirementss of resource {}, updated according to a substitution mapping. Status is {}",
3011                                                 resource.getUniqueId(), status);
3012                                 updateRes = Either.right(status);
3013                         }
3014                 }
3015                 if (updateRes == null) {
3016                         updateRes = Either.left(resource);
3017                 }
3018                 return updateRes;
3019         }
3020
3021         private void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances,
3022                                                                                                                  Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
3023                                                                                                                  Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities,
3024                                                                                                                  Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) {
3025
3026                 componentInstances.stream()
3027                                 .forEach(i -> {
3028                                         fillUpdatedInstCapabilities(updatedInstCapabilities, i, uploadResInstancesMap.get(i.getName())
3029                                                         .getCapabilitiesNamesToUpdate());
3030                                         fillUpdatedInstRequirements(updatedInstRequirements, i, uploadResInstancesMap.get(i.getName())
3031                                                         .getRequirementsNamesToUpdate());
3032                                 });
3033         }
3034
3035         private void fillUpdatedInstRequirements(
3036                         Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements,
3037                         ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
3038                 Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
3039                 Set<String> updatedReqNames = new HashSet<>();
3040                 if (isNotEmpty(requirementsNamesToUpdate)) {
3041                         for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements()
3042                                         .entrySet()) {
3043                                 updatedRequirements.put(requirements.getKey(), requirements.getValue()
3044                                                 .stream()
3045                                                 .filter(r -> requirementsNamesToUpdate.containsKey(r.getName())
3046                                                                 && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
3047                                                 .map(r -> {
3048                                                         r.setParentName(r.getName());
3049                                                         r.setName(requirementsNamesToUpdate.get(r.getName()));
3050                                                         updatedReqNames.add(r.getName());
3051                                                         return r;
3052                                                 })
3053                                                 .collect(toList()));
3054                         }
3055                 }
3056                 if (isNotEmpty(updatedRequirements)) {
3057                         updatedInstRequirements.put(instance, updatedRequirements);
3058                 }
3059         }
3060
3061         private void fillUpdatedInstCapabilities(
3062                         Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties,
3063                         ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
3064                 Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
3065                 Set<String> updatedCapNames = new HashSet<>();
3066                 if (isNotEmpty(capabilitiesNamesToUpdate)) {
3067                         for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities()
3068                                         .entrySet()) {
3069                                 updatedCapabilities.put(requirements.getKey(), requirements.getValue()
3070                                                 .stream()
3071                                                 .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName())
3072                                                                 && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
3073                                                 .map(c -> {
3074                                                         c.setParentName(c.getName());
3075                                                         c.setName(capabilitiesNamesToUpdate.get(c.getName()));
3076                                                         updatedCapNames.add(c.getName());
3077                                                         return c;
3078                                                 })
3079                                                 .collect(toList()));
3080                         }
3081                 }
3082                 if (isNotEmpty(updatedCapabilities)) {
3083                         updatedInstCapabilties.put(instance, updatedCapabilities);
3084                 }
3085         }
3086
3087         private ResponseFormat addRelationToRI(String yamlName, Resource resource,
3088                                                                                    UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
3089                 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
3090
3091                 ComponentInstance currentCompInstance = null;
3092
3093                 for (ComponentInstance compInstance : componentInstancesList) {
3094
3095                         if (compInstance.getName()
3096                                         .equals(nodesInfoValue.getName())) {
3097                                 currentCompInstance = compInstance;
3098                                 break;
3099                         }
3100
3101                 }
3102
3103                 if (currentCompInstance == null) {
3104                         log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), resource.getUniqueId());
3105                         BeEcompErrorManager.getInstance()
3106                                         .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE,
3107                                                         resource.getUniqueId(), ErrorSeverity.ERROR);
3108                         return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3109                 }
3110                 String resourceInstanceId = currentCompInstance.getUniqueId();
3111
3112                 Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
3113
3114                 if (regMap != null) {
3115                         Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet()
3116                                         .iterator();
3117
3118                         while (nodesRegValue.hasNext()) {
3119                                 Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
3120
3121                                 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
3122                                 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
3123                                         log.debug("Going to create  relation {}", uploadRegInfo.getName());
3124                                         loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),     StatusCode.STARTED,"Started to create relations on instance: {}",uploadRegInfo.getName());
3125                                         String regName = uploadRegInfo.getName();
3126                                         RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
3127                                         regCapRelDef.setFromNode(resourceInstanceId);
3128                                         log.debug("try to find available requirement {} ", regName);
3129                                         Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName,
3130                                                         yamlName, nodesInfoValue, currentCompInstance, uploadRegInfo.getCapabilityName());
3131                                         if (eitherReqStatus.isRight()) {
3132                                                 log.debug("failed to find available requirement {} status is {}", regName,
3133                                                                 eitherReqStatus.right()
3134                                                                                 .value());
3135                                                 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),     StatusCode.ERROR,"ERROR while search available requirement {} status is: {}",regName,eitherReqStatus.right().value());
3136                                                 return eitherReqStatus.right()
3137                                                                 .value();
3138                                         }
3139
3140                                         RequirementDefinition validReq = eitherReqStatus.left()
3141                                                         .value();
3142                                         List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef
3143                                                         .getRelationships();
3144                                         if (reqAndRelationshipPairList == null) {
3145                                                 reqAndRelationshipPairList = new ArrayList<>();
3146                                         }
3147                                         RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
3148                                         reqAndRelationshipPair.setRequirement(regName);
3149                                         reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
3150                                         reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
3151                                         RelationshipImpl relationship = new RelationshipImpl();
3152                                         relationship.setType(validReq.getCapability());
3153                                         reqAndRelationshipPair.setRelationships(relationship);
3154
3155                                         ComponentInstance currentCapCompInstance = null;
3156                                         for (ComponentInstance compInstance : componentInstancesList) {
3157                                                 if (compInstance.getName()
3158                                                                 .equals(uploadRegInfo.getNode())) {
3159                                                         currentCapCompInstance = compInstance;
3160                                                         break;
3161                                                 }
3162                                         }
3163
3164                                         if (currentCapCompInstance == null) {
3165                                                 log.debug("The component instance  with name {} not found on resource {} ",
3166                                                                 uploadRegInfo.getNode(), resource.getUniqueId());
3167                                                 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR component instance  with name: {} not found on resource: {}",uploadRegInfo.getNode(),resource.getUniqueId());
3168                                                 BeEcompErrorManager.getInstance()
3169                                                                 .logInternalDataError(
3170                                                                                 COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE,
3171                                                                                 resource.getUniqueId(), ErrorSeverity.ERROR);
3172                                                 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3173                                         }
3174                                         regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
3175                                         log.debug("try to find aviable Capability  req name is {} ", validReq.getName());
3176                                         CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq,
3177                                                         currentCapCompInstance, uploadRegInfo);
3178                                         reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
3179                                         reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
3180                                         reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
3181                                         if (aviableCapForRel == null) {
3182                                                 log.debug("aviable capability was not found. req name is {} component instance is {}",
3183                                                                 validReq.getName(), currentCapCompInstance.getUniqueId());
3184                                                 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),     StatusCode.ERROR,"ERROR available capability was not found. req name is: {} component instance is: {}",validReq.getName(),currentCapCompInstance.getUniqueId());
3185                                                 BeEcompErrorManager.getInstance()
3186                                                                 .logInternalDataError(
3187                                                                                 "aviable capability was not found. req name is " + validReq.getName()
3188                                                                                                 + " component instance is " + currentCapCompInstance.getUniqueId(),
3189                                                                                 resource.getUniqueId(), ErrorSeverity.ERROR);
3190                                                 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3191                                         }
3192                                         CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
3193                                         capReqRel.setRelation(reqAndRelationshipPair);
3194                                         reqAndRelationshipPairList.add(capReqRel);
3195                                         regCapRelDef.setRelationships(reqAndRelationshipPairList);
3196                                         relations.add(regCapRelDef);
3197                                 }
3198                         }
3199                 } else if (resource.getResourceType() != ResourceTypeEnum.CVFC) {
3200                         return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
3201                 }
3202                 return componentsUtils.getResponseFormat(ActionStatus.OK);
3203         }
3204
3205         private void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource,
3206                                                                          Resource originResource, ComponentInstance currentCompInstance,
3207                                                                          Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) {
3208                 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
3209                 if (MapUtils.isNotEmpty(propMap)) {
3210                         Map<String, InputDefinition> currPropertiesMap = new HashMap<>();
3211                         List<ComponentInstanceInput> instPropList = new ArrayList<>();
3212
3213                         if (CollectionUtils.isEmpty(originResource.getInputs())) {
3214                                 log.debug("failed to find properties ");
3215                                 loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,resource.getComponentMetadataForSupportLog(),StatusCode.ERROR,"ERROR while try to find properties");
3216                                 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND);
3217                         }
3218                         originResource.getInputs()
3219                                         .forEach(p -> addInput(currPropertiesMap, p));
3220                         for (List<UploadPropInfo> propertyList : propMap.values()) {
3221                                 processProperty(resource, currentCompInstance, allDataTypes, currPropertiesMap, instPropList,
3222                                                 propertyList);
3223                         }
3224                         currPropertiesMap.values()
3225                                         .forEach(p -> instPropList.add(new ComponentInstanceInput(p)));
3226                         instInputs.put(currentCompInstance.getUniqueId(), instPropList);
3227                 }
3228         }
3229
3230         private void processProperty(Resource resource, ComponentInstance currentCompInstance,
3231                                                                  Map<String, DataTypeDefinition> allDataTypes, Map<String, InputDefinition> currPropertiesMap,
3232                                                                  List<ComponentInstanceInput> instPropList, List<UploadPropInfo> propertyList) {
3233                 UploadPropInfo propertyInfo = propertyList.get(0);
3234                 String propName = propertyInfo.getName();
3235                 if (!currPropertiesMap.containsKey(propName)) {
3236                         loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
3237                                         StatusCode.ERROR,"ERROR failed to find property: {}",propName);
3238                         log.debug("failed to find property {} ", propName);
3239                         throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, propName);
3240                 }
3241                 InputDefinition curPropertyDef = currPropertiesMap.get(propName);
3242                 ComponentInstanceInput property = null;
3243
3244                 String value = null;
3245                 List<GetInputValueDataDefinition> getInputs = null;
3246                 boolean isValidate = true;
3247                 if (propertyInfo.getValue() != null) {
3248                         getInputs = propertyInfo.getGet_input();
3249                         isValidate = getInputs == null || getInputs.isEmpty();
3250                         if (isValidate) {
3251                                 value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
3252                         } else {
3253                                 value = getPropertyJsonStringValue(propertyInfo.getValue(),
3254                                                 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
3255                         }
3256                 }
3257                 String innerType = null;
3258                 property = new ComponentInstanceInput(curPropertyDef, value, null);
3259
3260         String validPropertyVAlue = validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
3261
3262                 property.setValue(validPropertyVAlue);
3263
3264                 if (isNotEmpty(getInputs)) {
3265                         List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
3266                         for (GetInputValueDataDefinition getInput : getInputs) {
3267                                 List<InputDefinition> inputs = resource.getInputs();
3268                                 if (CollectionUtils.isEmpty(inputs)) {
3269                                         loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
3270                                                         StatusCode.ERROR,"ERROR Failed to add property: "+propName+" to resource instance: {}. Inputs list is empty ",currentCompInstance.getUniqueId());
3271                                         log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property,
3272                                                         currentCompInstance.getUniqueId());
3273                                         throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
3274                                 }
3275
3276                                 Optional<InputDefinition> optional = inputs.stream()
3277                                                 .filter(p -> p.getName()
3278                                                                 .equals(getInput.getInputName()))
3279                                                 .findAny();
3280                                 if (!optional.isPresent()) {
3281                                         loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
3282                                                         StatusCode.ERROR,"ERROR Failed to find input: "+getInput.getInputName());
3283                                         log.debug("Failed to find input {} ", getInput.getInputName());
3284                                         // @@TODO error message
3285                                         throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
3286                                 }
3287                                 InputDefinition input = optional.get();
3288                                 getInput.setInputId(input.getUniqueId());
3289                                 getInputValues.add(getInput);
3290
3291                                 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
3292                                 processGetInput(getInputValues, inputs, getInputIndex);
3293                         }
3294                         property.setGetInputValues(getInputValues);
3295                 }
3296                 instPropList.add(property);
3297                 // delete overriden property
3298                 currPropertiesMap.remove(property.getName());
3299         }
3300
3301         private void processGetInput(List<GetInputValueDataDefinition> getInputValues, List<InputDefinition> inputs,
3302                                                                  GetInputValueDataDefinition getInputIndex) {
3303                 Optional<InputDefinition> optional;
3304                 if (getInputIndex != null) {
3305                         optional = inputs.stream()
3306                                         .filter(p -> p.getName()
3307                                                         .equals(getInputIndex.getInputName()))
3308                                         .findAny();
3309                         if (!optional.isPresent()) {
3310                                 log.debug("Failed to find input {} ", getInputIndex.getInputName());
3311                                 // @@TODO error message
3312                                 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
3313                         }
3314                         InputDefinition inputIndex = optional.get();
3315                         getInputIndex.setInputId(inputIndex.getUniqueId());
3316                         getInputValues.add(getInputIndex);
3317                 }
3318         }
3319
3320         private void addInput(Map<String, InputDefinition> currPropertiesMap, InputDefinition prop) {
3321                 String propName = prop.getName();
3322                 if (!currPropertiesMap.containsKey(propName)) {
3323                         currPropertiesMap.put(propName, prop);
3324                 }
3325         }
3326
3327         private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
3328                                                                                                  Resource resource, Resource originResource, ComponentInstance currentCompInstance,
3329                                                                                                  Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) {
3330
3331                 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
3332                 Map<String, PropertyDefinition> currPropertiesMap = new HashMap<>();
3333
3334                 List<PropertyDefinition> listFromMap = originResource.getProperties();
3335                 if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) {
3336                         loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
3337                                         StatusCode.ERROR,"ERROR Failed to find properties");
3338                         log.debug("failed to find properties");
3339                         return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
3340                 }
3341                 if (listFromMap == null || listFromMap.isEmpty()) {
3342                         return componentsUtils.getResponseFormat(ActionStatus.OK);
3343                 }
3344                 for (PropertyDefinition prop : listFromMap) {
3345                         String propName = prop.getName();
3346                         if (!currPropertiesMap.containsKey(propName)) {
3347                                 currPropertiesMap.put(propName, prop);
3348                         }
3349                 }
3350                 List<ComponentInstanceProperty> instPropList = new ArrayList<>();
3351                 if (propMap != null && propMap.size() > 0) {
3352                         for (List<UploadPropInfo> propertyList : propMap.values()) {
3353
3354                                 UploadPropInfo propertyInfo = propertyList.get(0);
3355                                 String propName = propertyInfo.getName();
3356                                 if (!currPropertiesMap.containsKey(propName)) {
3357                                         log.debug("failed to find property {} ", propName);
3358                                         loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR Failed to find property: {}",propName);
3359                                         return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
3360                                 }
3361                                 PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
3362                                 ComponentInstanceProperty property = null;
3363
3364                                 String value = null;
3365                                 List<GetInputValueDataDefinition> getInputs = null;
3366                                 boolean isValidate = true;
3367                                 if (propertyInfo.getValue() != null) {
3368                                         getInputs = propertyInfo.getGet_input();
3369                                         isValidate = getInputs == null || getInputs.isEmpty();
3370                                         if (isValidate) {
3371                                                 value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
3372                                         } else {
3373                                                 value = getPropertyJsonStringValue(propertyInfo.getValue(),
3374                                                                 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
3375                                         }
3376                                 }
3377                                 String innerType = null;
3378                                 property = new ComponentInstanceProperty(curPropertyDef, value, null);
3379
3380                 String validatePropValue = validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
3381                                 property.setValue(validatePropValue);
3382
3383                                 if (getInputs != null && !getInputs.isEmpty()) {
3384                                         List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
3385                                         for (GetInputValueDataDefinition getInput : getInputs) {
3386                                                 List<InputDefinition> inputs = resource.getInputs();
3387                                                 if (inputs == null || inputs.isEmpty()) {
3388                                                         log.debug("Failed to add property {} to instance. Inputs list is empty ", property);
3389                                                         loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"Failed to add property: {} to instance. Inputs list is empty",propName);
3390                                                         rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
3391                                                                         .stream()
3392                                                                         .map(GetInputValueDataDefinition::getInputName)
3393                                                                         .collect(toList())
3394                                                                         .toString());
3395                                                 }
3396                                                 InputDefinition input = findInputByName(inputs, getInput);
3397                                                 getInput.setInputId(input.getUniqueId());
3398                                                 getInputValues.add(getInput);
3399
3400                                                 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
3401                                                 if (getInputIndex != null) {
3402                                                         input = findInputByName(inputs, getInputIndex);
3403                                                         getInputIndex.setInputId(input.getUniqueId());
3404                                                         getInputValues.add(getInputIndex);
3405
3406                                                 }
3407
3408                                         }
3409                                         property.setGetInputValues(getInputValues);
3410                                 }
3411                                 instPropList.add(property);
3412                                 // delete overriden property
3413                                 currPropertiesMap.remove(property.getName());
3414                         }
3415                 }
3416                 // add rest of properties
3417                 if (!currPropertiesMap.isEmpty()) {
3418                         for (PropertyDefinition value : currPropertiesMap.values()) {
3419                                 instPropList.add(new ComponentInstanceProperty(value));
3420                         }
3421                 }
3422                 instProperties.put(currentCompInstance.getUniqueId(), instPropList);
3423                 return componentsUtils.getResponseFormat(ActionStatus.OK);
3424         }
3425
3426         // US740820 Relate RIs according to capability name
3427         private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq,
3428                                                                                                                                          ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
3429                 if (null == uploadReqInfo.getCapabilityName() || validReq.getCapability()
3430                                 .equals(uploadReqInfo.getCapabilityName())) {// get
3431                         // by
3432                         // capability
3433                         // type
3434                         return findAvailableCapability(validReq, currentCapCompInstance);
3435                 }
3436                 return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo);
3437         }
3438
3439         private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq,
3440                                                                                                                  ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
3441                 CapabilityDefinition cap = null;
3442                 Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
3443                 if (!capMap.containsKey(validReq.getCapability())) {
3444                         return null;
3445                 }
3446                 Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability())
3447                                 .stream()
3448                                 .filter(p -> p.getName()
3449                                                 .equals(uploadReqInfo.getCapabilityName()))
3450                                 .findAny();
3451                 if (!capByName.isPresent()) {
3452                         return null;
3453                 }
3454                 cap = capByName.get();
3455
3456                 if (isBoundedByOccurrences(cap)) {
3457                         String leftOccurrences = cap.getLeftOccurrences();
3458                         int left = Integer.parseInt(leftOccurrences);
3459                         if (left > 0) {
3460                                 --left;
3461                                 cap.setLeftOccurrences(String.valueOf(left));
3462
3463                         }
3464
3465                 }
3466                 return cap;
3467         }
3468
3469         private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance instance) {
3470                 Map<String, List<CapabilityDefinition>> capMap = instance.getCapabilities();
3471                 if (capMap.containsKey(validReq.getCapability())) {
3472                         List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
3473
3474                         for (CapabilityDefinition cap : capList) {
3475                                 if (isBoundedByOccurrences(cap)) {
3476                                         String leftOccurrences = cap.getLeftOccurrences() != null ? cap.getLeftOccurrences()
3477                                                         : cap.getMaxOccurrences();
3478                                         int left = Integer.parseInt(leftOccurrences);
3479                                         if (left > 0) {
3480                                                 --left;
3481                                                 cap.setLeftOccurrences(String.valueOf(left));
3482                                                 return cap;
3483                                         }
3484                                 } else {
3485                                         return cap;
3486                                 }
3487                         }
3488                 }
3489                 return null;
3490         }
3491
3492         private boolean isBoundedByOccurrences(CapabilityDefinition cap) {
3493                 return cap.getMaxOccurrences() != null && !cap.getMaxOccurrences()
3494                                 .equals(CapabilityDataDefinition.MAX_OCCURRENCES);
3495         }
3496
3497         private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName,
3498                                                                                                                                                                 UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance,
3499                                                                                                                                                                 String capName) {
3500                 Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
3501                 List<RequirementDefinition> list = comInstRegDefMap.get(capName);
3502                 RequirementDefinition validRegDef = null;
3503                 if (list == null) {
3504                         for (Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
3505                                 for (RequirementDefinition reqDef : entry.getValue()) {
3506                                         if (reqDef.getName()
3507                                                         .equals(regName)) {
3508                                                 if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences()
3509                                                                 .equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
3510                                                         String leftOccurrences = reqDef.getLeftOccurrences();
3511                                                         if (leftOccurrences == null) {
3512                                                                 leftOccurrences = reqDef.getMaxOccurrences();
3513                                                         }
3514                                                         int left = Integer.parseInt(leftOccurrences);
3515                                                         if (left > 0) {
3516                                                                 --left;
3517                                                                 reqDef.setLeftOccurrences(String.valueOf(left));
3518                                                                 validRegDef = reqDef;
3519                                                                 break;
3520                                                         } else {
3521                                                                 continue;
3522                                                         }
3523                                                 } else {
3524                                                         validRegDef = reqDef;
3525                                                         break;
3526                                                 }
3527
3528                                         }
3529                                 }
3530                                 if (validRegDef != null) {
3531                                         break;
3532                                 }
3533                         }
3534                 } else {
3535                         for (RequirementDefinition reqDef : list) {
3536                                 if (reqDef.getName()
3537                                                 .equals(regName)) {
3538                                         if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences()
3539                                                         .equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
3540                                                 String leftOccurrences = reqDef.getLeftOccurrences();
3541                                                 if (leftOccurrences == null) {
3542                                                         leftOccurrences = reqDef.getMaxOccurrences();
3543                                                 }
3544                                                 int left = Integer.parseInt(leftOccurrences);
3545                                                 if (left > 0) {
3546                                                         --left;
3547                                                         reqDef.setLeftOccurrences(String.valueOf(left));
3548                                                         validRegDef = reqDef;
3549                                                         break;
3550                                                 } else {
3551                                                         continue;
3552                                                 }
3553                                         } else {
3554                                                 validRegDef = reqDef;
3555                                                 break;
3556                                         }
3557                                 }
3558                         }
3559                 }
3560                 if (validRegDef == null) {
3561                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
3562                                         yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3563                         return Either.right(responseFormat);
3564                 }
3565                 return Either.left(validRegDef);
3566         }
3567
3568         private Resource createResourceInstances(String yamlName, Resource resource, Resource oldResource,
3569                                                                                          Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingNodeTypesByResourceNames) {
3570
3571                 Either<Resource, ResponseFormat> eitherResource;
3572                 log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
3573         if (isEmpty(uploadResInstancesMap) && resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
3574             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
3575             throw new ByResponseFormatComponentException(responseFormat);
3576                 }
3577                 if (MapUtils.isNotEmpty(nodeNamespaceMap)) {
3578                         nodeNamespaceMap.forEach((k, v) -> existingNodeTypesByResourceNames.put(v.getToscaResourceName(), v));
3579                 }
3580                 Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
3581                 uploadResInstancesMap.values()
3582                                 .forEach(i -> createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap,
3583                                                 existingNodeTypesByResourceNames, resourcesInstancesMap));
3584                 if (oldResource != null && oldResource.getResourceType() != ResourceTypeEnum.CVFC && oldResource.getComponentInstances() != null) {
3585                         Map<String, Resource> existingNodeTypesByUids = existingNodeTypesByResourceNames.values()
3586                                         .stream()
3587                                         .collect(toMap(Resource::getUniqueId, r -> r));
3588                         oldResource.getComponentInstances()
3589                                         .stream()
3590                                         .filter(i -> !i.isCreatedFromCsar())
3591                                         .forEach(uiInst -> resourcesInstancesMap.put(uiInst,
3592                                                         getOriginResource(existingNodeTypesByUids, uiInst)));
3593                 }
3594
3595                 if (isNotEmpty(resourcesInstancesMap)) {
3596                         try {
3597                                 toscaOperationFacade.associateComponentInstancesToComponent(resource,
3598                                                 resourcesInstancesMap, false, oldResource != null);
3599                         } catch (StorageException exp) {
3600                                 if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) {
3601                                         log.debug("Failed to add component instances to container component {}", resource.getName());
3602                                         ResponseFormat responseFormat = componentsUtils
3603                                                         .getResponseFormat(componentsUtils.convertFromStorageResponse(exp.getStorageOperationStatus()));
3604                                         eitherResource = Either.right(responseFormat);
3605                                         throw new ByResponseFormatComponentException(eitherResource.right().value());
3606                                 }
3607                         }
3608                 }
3609         if (CollectionUtils.isEmpty(resource.getComponentInstances()) &&
3610                 resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
3611                         log.debug("Error when create resource instance from csar. ComponentInstances list empty");
3612                         BeEcompErrorManager.getInstance()
3613                                         .logBeDaoSystemError(
3614                                                         "Error when create resource instance from csar. ComponentInstances list empty");
3615                         throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
3616                 }
3617                 return resource;
3618         }
3619
3620         private void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName,
3621                                                                                           Resource resource, Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingnodeTypeMap,
3622                                                                                           Map<ComponentInstance, Resource> resourcesInstancesMap) {
3623                 Either<Resource, ResponseFormat> eitherResource;
3624                 log.debug("*************Going to create  resource instances {}", yamlName);
3625                 // updating type if the type is node type name - we need to take the
3626                 // updated name
3627                 log.debug("*************Going to create  resource instances {}", uploadComponentInstanceInfo.getName());
3628                 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
3629                         uploadComponentInstanceInfo.setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType())
3630                                         .getToscaResourceName());
3631                 }
3632                 Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo,
3633                                 existingnodeTypeMap);
3634
3635                 ComponentInstance componentInstance = new ComponentInstance();
3636                 componentInstance.setComponentUid(refResource.getUniqueId());
3637         Collection<String> directives = uploadComponentInstanceInfo.getDirectives();
3638         if(directives != null && !directives.isEmpty()) {
3639             componentInstance.setDirectives(new ArrayList<>(directives));
3640         }
3641         UploadNodeFilterInfo uploadNodeFilterInfo = uploadComponentInstanceInfo.getUploadNodeFilterInfo();
3642         if (uploadNodeFilterInfo != null){
3643             componentInstance.setNodeFilter(new CINodeFilterUtils().getNodeFilterDataDefinition(uploadNodeFilterInfo,
3644                     componentInstance.getUniqueId()));
3645         }
3646         ComponentTypeEnum containerComponentType = resource.getComponentType();
3647                 NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
3648                 if (containerNodeType == NodeTypeEnum.Resource && isNotEmpty(uploadComponentInstanceInfo.getCapabilities())
3649                                 && isNotEmpty(refResource.getCapabilities())) {
3650                         setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
3651                         Map<String, List<CapabilityDefinition>> validComponentInstanceCapabilities = getValidComponentInstanceCapabilities(
3652                                         refResource.getUniqueId(), refResource.getCapabilities(),
3653                                         uploadComponentInstanceInfo.getCapabilities());
3654                         componentInstance.setCapabilities(validComponentInstanceCapabilities);
3655                 }
3656
3657         if (isNotEmpty(uploadComponentInstanceInfo.getArtifacts())) {
3658             Map<String, Map<String, UploadArtifactInfo>> artifacts = uploadComponentInstanceInfo.getArtifacts();
3659             Map<String, ToscaArtifactDataDefinition> toscaArtifacts = new HashMap<>();
3660             Map<String, Map<String, UploadArtifactInfo>> arts = artifacts.entrySet().stream()
3661                                         .filter(e -> e.getKey().contains(TypeUtils.ToscaTagNamesEnum.ARTIFACTS.getElementName()))
3662                                         .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
3663             Map<String, UploadArtifactInfo> artifact = arts.get(TypeUtils.ToscaTagNamesEnum.ARTIFACTS.getElementName());
3664             for (Map.Entry<String, UploadArtifactInfo> entry : artifact.entrySet()) {
3665                 ToscaArtifactDataDefinition to = new ToscaArtifactDataDefinition();
3666                 to.setFile(entry.getValue().getFile());
3667                 to.setType(entry.getValue().getType());
3668                 toscaArtifacts.put(entry.getKey(), to);
3669             }
3670             componentInstance.setToscaArtifacts(toscaArtifacts);
3671         }
3672
3673                 if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
3674                         log.debug("createResourceInstances - not found lates version for resource instance with name {} and type ",
3675                                         uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3676                         throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
3677                                         yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3678                 }
3679                 Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
3680                 componentInstance.setName(uploadComponentInstanceInfo.getName());
3681                 componentInstance.setIcon(origResource.getIcon());
3682                 componentInstance.setCreatedFrom(CreatedFrom.CSAR);
3683                 resourcesInstancesMap.put(componentInstance, origResource);
3684         }
3685
3686         private ComponentParametersView getComponentWithInstancesFilter() {
3687                 ComponentParametersView parametersView = new ComponentParametersView();
3688                 parametersView.disableAll();
3689                 parametersView.setIgnoreComponentInstances(false);
3690                 parametersView.setIgnoreInputs(false);
3691                 // inputs are read when creating
3692                 // property values on instances
3693                 parametersView.setIgnoreUsers(false);
3694                 return parametersView;
3695         }
3696
3697         private void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities,
3698                                                                                  Map<String, List<UploadCapInfo>> uploadedCapabilities) {
3699                 for (Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()) {
3700                         if (originCapabilities.containsKey(currEntry.getKey())) {
3701                                 currEntry.getValue()
3702                                                 .stream()
3703                                                 .forEach(cap -> cap.setType(currEntry.getKey()));
3704                         }
3705                 }
3706                 for (Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()) {
3707                         capabilities.getValue()
3708                                         .stream()
3709                                         .forEach(cap -> {
3710                                                 if (uploadedCapabilities.containsKey(cap.getName())) {
3711                                                         uploadedCapabilities.get(cap.getName())
3712                                                                         .stream()
3713                                                                         .forEach(c -> {
3714                                                                                 c.setName(cap.getName());
3715                                                                                 c.setType(cap.getType());
3716                                                                         });
3717                                                 }
3718                                         });
3719                 }
3720         }
3721
3722         private Resource validateResourceInstanceBeforeCreate(String yamlName,
3723                                                                                                                   UploadComponentInstanceInfo uploadComponentInstanceInfo, Map<String, Resource> nodeNamespaceMap) {
3724
3725                 log.debug(
3726                                 "validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type {} before create",
3727                                 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3728                 Resource refResource;
3729                 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
3730                         refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType());
3731                 } else {
3732                         Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade
3733                                         .getLatestCertifiedNodeTypeByToscaResourceName(uploadComponentInstanceInfo.getType());
3734                         if (findResourceEither.isRight()) {
3735                                 log.debug(
3736                                                 "validateResourceInstanceBeforeCreate - not found lates version for resource instance with name {} and type {}",
3737                                                 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3738                                 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
3739                         }
3740                         refResource = findResourceEither.left().value();
3741                         nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
3742                 }
3743                 String componentState = refResource.getComponentMetadataDefinition()
3744                                 .getMetadataDataDefinition()
3745                                 .getState();
3746                 if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
3747                         log.debug(
3748                                         "validateResourceInstanceBeforeCreate - component instance of component {} can not be created because the component is in an illegal state {}.",
3749                                         refResource.getName(), componentState);
3750                         throw new ByActionStatusComponentException(ActionStatus.ILLEGAL_COMPONENT_STATE,
3751                                         refResource.getComponentType().getValue(),refResource.getName(), componentState);
3752                 }
3753
3754                 if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) {
3755                         log.debug("validateResourceInstanceBeforeCreate -  ref resource type is  ", refResource.getResourceType());
3756                         throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
3757                                         yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3758                 }
3759                 return refResource;
3760         }
3761
3762         public Resource propagateStateToCertified(User user, Resource resource,
3763                                                                                           LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock,
3764                                                                                           boolean forceCertificationAllowed) {
3765
3766                 boolean failed = false;
3767                 try {
3768                         if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed
3769                                         && lifecycleBusinessLogic.isFirstCertification(resource.getVersion())) {
3770                                 nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
3771                         }
3772                         if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
3773                                 Either<ArtifactDefinition, Operation> eitherPopulated = populateToscaArtifacts(
3774                                                 resource, user, false, inTransaction, needLock, false);
3775                                 return resource;
3776                         }
3777                         return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
3778                 } catch (ComponentException e) {
3779                         failed = true;
3780                         log.debug("The exception has occurred upon certification of resource {}. ", resource.getName(), e);
3781                         throw e;
3782                 } finally {
3783                         if (failed) {
3784                                 BeEcompErrorManager.getInstance()
3785                                                 .logBeSystemError("Change LifecycleState - Certify");
3786                                 if (!inTransaction) {
3787                     janusGraphDao.rollback();
3788                                 }
3789                         } else if (!inTransaction) {
3790                 janusGraphDao.commit();
3791                         }
3792                 }
3793         }
3794
3795         private Resource nodeFullCertification(String uniqueId, User user,
3796                                                                                    LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
3797                 Either<Resource, ResponseFormat> resourceResponse = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo,
3798                                 inTransaction, needLock);
3799                 if(resourceResponse.isRight()){
3800                         throw new ByResponseFormatComponentException(resourceResponse.right().value());
3801                 }
3802                 return resourceResponse.left().value();
3803         }
3804
3805         private Resource nodeForceCertification(Resource resource, User user,
3806                                                                                         LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
3807                 return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction,
3808                                 needLock);
3809         }
3810
3811         public ImmutablePair<Resource, ActionStatus> createOrUpdateResourceByImport(final Resource resource,
3812                                                                                                                                                                 final User user,
3813                                                                                                                                                                 final boolean isNormative,
3814                                                                                                                                                                 final boolean isInTransaction,
3815                                                                                                                                                                 final boolean needLock,
3816                                                                                                                                                                 final CsarInfo csarInfo,
3817                                                                                                                                                                 final String nodeName,
3818                                                                                                                                                                 final boolean isNested) {
3819
3820                 ImmutablePair<Resource, ActionStatus> result = null;
3821                 // check if resource already exists (search by tosca name = type)
3822                 final boolean isNestedResource = isNestedResourceUpdate(csarInfo, nodeName);
3823                 final Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade
3824                         .getLatestByToscaResourceName(resource.getToscaResourceName());
3825
3826                 if (latestByToscaName.isLeft()) {
3827                         Resource foundResource = latestByToscaName.left().value();
3828                         // we don't allow updating names of top level types
3829                         if (!isNestedResource && !StringUtils.equals(resource.getName(), foundResource.getName())) {
3830                                 BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import",
3831                                         ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
3832                                 log.debug("resource already exist new name={} old name={} same type={}", resource.getName(),
3833                                         foundResource.getName(), resource.getToscaResourceName());
3834                                 final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
3835                                 componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
3836                                 throwComponentException(responseFormat);
3837                         }
3838                         result = updateExistingResourceByImport(resource, foundResource, user, isNormative, needLock, isNested);
3839                 } else if (isNotFound(latestByToscaName)) {
3840                         if (isNestedResource) {
3841                                 result = createOrUpdateNestedResource(resource, user, isNormative, isInTransaction, needLock, csarInfo,
3842                                         isNested, nodeName);
3843                         } else {
3844                                 result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3845                         }
3846                 } else {
3847                         StorageOperationStatus status = latestByToscaName.right().value();
3848                         log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
3849                         ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils
3850                                 .convertFromStorageResponse(latestByToscaName.right().value()), resource);
3851                         componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
3852                         throwComponentException(responseFormat);
3853                 }
3854                 return result;
3855         }
3856
3857         private boolean isNestedResourceUpdate(CsarInfo csarInfo, String nodeName) {
3858                 return csarInfo != null && csarInfo.isUpdate() && nodeName != null;
3859         }
3860
3861         private ImmutablePair<Resource, ActionStatus> createOrUpdateNestedResource(final Resource resource,
3862                                                                                                                                                            final User user,
3863                                                                                                                                                            final boolean isNormative,
3864                                                                                                                                                            final boolean isInTransaction,
3865                                                                                                                                                            final boolean needLock,
3866                                                                                                                                                            final CsarInfo csarInfo,
3867                                                                                                                                                            final boolean isNested,
3868                                                                                                                                                            final String nodeName) {
3869                 final Either<Component, StorageOperationStatus> latestByToscaName = toscaOperationFacade
3870                         .getLatestByToscaResourceName(buildNestedToscaResourceName(resource.getResourceType()
3871                                 .name(), csarInfo.getVfResourceName(), nodeName).getRight());
3872                 if (latestByToscaName.isLeft()) {
3873                         final Resource nestedResource = (Resource) latestByToscaName.left().value();
3874                         log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
3875                         final Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(nestedResource,
3876                                 resource, ValidationUtils.hasBeenCertified(nestedResource.getVersion()));
3877                         if (eitherValidation.isRight()) {
3878                                 return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3879                         }
3880                         return updateExistingResourceByImport(resource, nestedResource, user, isNormative, needLock, isNested);
3881                 } else {
3882                         return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3883                 }
3884         }
3885
3886         private boolean isNotFound(Either<Resource, StorageOperationStatus> getResourceEither) {
3887                 return getResourceEither.isRight() && getResourceEither.right()
3888                                 .value() == StorageOperationStatus.NOT_FOUND;
3889         }
3890
3891         private ImmutablePair<Resource, ActionStatus> createResourceByImport(Resource resource, User user,
3892                                                                                                                                                  boolean isNormative, boolean isInTransaction, CsarInfo csarInfo) {
3893                 log.debug("resource with name {} does not exist. create new resource", resource.getName());
3894                 validateResourceBeforeCreate(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isInTransaction, csarInfo);
3895                 final Resource createResourceByDao = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative,
3896                                 isInTransaction);
3897                 Resource createdResource  = updateCatalog(createResourceByDao, ChangeTypeEnum.LIFECYCLE).left().map(r -> (Resource)r).left().value();
3898                 ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createdResource, ActionStatus.CREATED);
3899                 ASDCKpiApi.countImportResourcesKPI();
3900                 return resourcePair;
3901         }
3902
3903         public boolean isResourceExist(String resourceName) {
3904                 Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resourceName);
3905                 return latestByName.isLeft();
3906         }
3907
3908         private ImmutablePair<Resource, ActionStatus> updateExistingResourceByImport(Resource newResource,
3909                                                                                                                                                                  Resource oldResource, User user, boolean inTransaction, boolean needLock, boolean isNested) {
3910                 String lockedResourceId = oldResource.getUniqueId();
3911                 log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId,
3912                                 oldResource.getVersion(), oldResource.getLifecycleState());
3913                 ImmutablePair<Resource, ActionStatus> resourcePair = null;
3914                 try {
3915                         lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import");
3916                         oldResource = prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false);
3917                         mergeOldResourceMetadataWithNew(oldResource, newResource);
3918
3919                         validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested);
3920                         validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), newResource,
3921                                         AuditingActionEnum.IMPORT_RESOURCE, inTransaction);
3922                         // contact info normalization
3923                         newResource.setContactId(newResource.getContactId()
3924                                         .toLowerCase());
3925                         PropertyConstraintsUtils.validatePropertiesConstraints(newResource, oldResource);
3926                         // non-updatable fields
3927                         newResource.setCreatorUserId(user.getUserId());
3928                         newResource.setCreatorFullName(user.getFullName());
3929                         newResource.setLastUpdaterUserId(user.getUserId());
3930                         newResource.setLastUpdaterFullName(user.getFullName());
3931                         newResource.setUniqueId(oldResource.getUniqueId());
3932                         newResource.setVersion(oldResource.getVersion());
3933                         newResource.setInvariantUUID(oldResource.getInvariantUUID());
3934                         newResource.setLifecycleState(oldResource.getLifecycleState());
3935                         newResource.setUUID(oldResource.getUUID());
3936                         newResource.setNormalizedName(oldResource.getNormalizedName());
3937                         newResource.setSystemName(oldResource.getSystemName());
3938                         if (oldResource.getCsarUUID() != null) {
3939                                 newResource.setCsarUUID(oldResource.getCsarUUID());
3940                         }
3941                         if (oldResource.getImportedToscaChecksum() != null) {
3942                                 newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
3943                         }
3944                         newResource.setAbstract(oldResource.isAbstract());
3945
3946                         if (newResource.getDerivedFrom() == null || newResource.getDerivedFrom()
3947                                         .isEmpty()) {
3948                                 newResource.setDerivedFrom(oldResource.getDerivedFrom());
3949                         }
3950                         if (newResource.getDerivedFromGenericType() == null || newResource.getDerivedFromGenericType()
3951                                         .isEmpty()) {
3952                                 newResource.setDerivedFromGenericType(oldResource.getDerivedFromGenericType());
3953                         }
3954                         if (newResource.getDerivedFromGenericVersion() == null || newResource.getDerivedFromGenericVersion()
3955                                         .isEmpty()) {
3956                                 newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion());
3957                         }
3958                         // add for new)
3959                         // created without tosca artifacts - add the placeholders
3960                         if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts()
3961                                         .isEmpty()) {
3962                                 setToscaArtifactsPlaceHolders(newResource, user);
3963                         }
3964
3965                         if (newResource.getInterfaces() == null || newResource.getInterfaces().isEmpty()) {
3966                                 newResource.setInterfaces(oldResource.getInterfaces());
3967                         }
3968
3969             if (CollectionUtils.isEmpty(newResource.getProperties())) {
3970                 newResource.setProperties(oldResource.getProperties());
3971             }
3972
3973                         Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade
3974                                         .overrideComponent(newResource, oldResource);
3975
3976                         if (overrideResource.isRight()) {
3977                                 ResponseFormat responseFormat = componentsUtils
3978                                                 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(overrideResource.right()
3979                                                                 .value()), newResource);
3980                                 componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE);
3981
3982                                 throwComponentException(responseFormat);
3983                         }
3984                         updateCatalog(overrideResource.left()
3985                                         .value(), ChangeTypeEnum.LIFECYCLE);
3986
3987                         log.debug("Resource updated successfully!!!");
3988                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3989                         componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
3990                                         ResourceVersionInfo.newBuilder()
3991                                                         .state(oldResource.getLifecycleState()
3992                                                                         .name())
3993                                                         .version(oldResource.getVersion())
3994                                                         .build());
3995
3996                         resourcePair = new ImmutablePair<>(overrideResource.left()
3997                                         .value(), ActionStatus.OK);
3998                         return resourcePair;
3999                 } finally {
4000                         if (resourcePair == null) {
4001                                 BeEcompErrorManager.getInstance()
4002                                                 .logBeSystemError("Change LifecycleState - Certify");
4003                                 janusGraphDao.rollback();
4004                         } else if (!inTransaction) {
4005                 janusGraphDao.commit();
4006                         }
4007                         if (needLock) {
4008                                 log.debug("unlock resource {}", lockedResourceId);
4009                                 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
4010                         }
4011                 }
4012
4013         }
4014
4015         /**
4016          * Merge old resource with new. Keep old category and vendor name without
4017          * change
4018          *
4019          * @param oldResource
4020          * @param newResource
4021          */
4022         private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
4023
4024                 // keep old category and vendor name without change
4025                 // merge the rest of the resource metadata
4026                 if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
4027                         newResource.setTags(oldResource.getTags());
4028                 }
4029
4030                 if (newResource.getDescription() == null) {
4031                         newResource.setDescription(oldResource.getDescription());
4032                 }
4033
4034                 if (newResource.getVendorRelease() == null) {
4035                         newResource.setVendorRelease(oldResource.getVendorRelease());
4036                 }
4037
4038                 if (newResource.getResourceVendorModelNumber() == null) {
4039                         newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber());
4040                 }
4041
4042                 if (newResource.getContactId() == null) {
4043                         newResource.setContactId(oldResource.getContactId());
4044                 }
4045
4046                 newResource.setCategories(oldResource.getCategories());
4047                 if (newResource.getVendorName() == null) {
4048                         newResource.setVendorName(oldResource.getVendorName());
4049                 }
4050                 List<GroupDefinition>oldForUpdate = oldResource.getGroups();
4051                 if(CollectionUtils.isNotEmpty(oldForUpdate)){
4052                         List<GroupDefinition>groupForUpdate = oldForUpdate.stream().map(group -> new GroupDefinition(group)).collect(Collectors.toList());
4053
4054                         groupForUpdate.stream().filter(group -> group.isVspOriginated())
4055                                         .forEach(group -> group.setName(group.getInvariantName()));
4056
4057                         newResource.setGroups(groupForUpdate);
4058                 }
4059
4060
4061                 if(newResource.getResourceType().isAtomicType() && !newResource.getName().equals("Root")&& newResource.getResourceType() != ResourceTypeEnum.CVFC) {
4062                         ResourceTypeEnum updatedResourceType = newResource.getResourceType();
4063                         Component derivedFromResource = getParentComponent(newResource);
4064                         if (derivedFromResource.getComponentType() == ComponentTypeEnum.RESOURCE) {
4065                                 Resource parentResource = (Resource) derivedFromResource;
4066                                 if (!(parentResource.isAbstract() && (ResourceTypeEnum.VFC == parentResource.getResourceType() || ResourceTypeEnum.ABSTRACT == parentResource.getResourceType())) &&
4067                                                 parentResource.getResourceType() != updatedResourceType) {
4068                                         BeEcompErrorManager.getInstance()
4069                                                         .logInternalDataError("mergeOldResourceMetadataWithNew", "resource type of the resource does not match to derived from resource type",
4070                                                                         ErrorSeverity.ERROR);
4071                                         log.debug("#mergeOldResourceMetadataWithNew - resource type {} of the resource {} does not match to derived from resource type {}",
4072                                                         newResource.getResourceType(), newResource.getToscaResourceName(), parentResource.getResourceType());
4073                                         throw new ByActionStatusComponentException(ActionStatus.INVALID_RESOURCE_TYPE);
4074                                 }
4075                         }
4076                 }
4077
4078         }
4079
4080         private Component getParentComponent(Resource newResource) {
4081                 String toscaResourceNameDerivedFrom = newResource.getDerivedFrom().get(0);
4082                 Either<Component, StorageOperationStatus> latestByToscaResourceName = toscaOperationFacade.getLatestByToscaResourceName(toscaResourceNameDerivedFrom);
4083                 if(latestByToscaResourceName.isRight()){
4084                         BeEcompErrorManager.getInstance()
4085                                         .logInternalDataError("mergeOldResourceMetadataWithNew", "derived from resource not found", ErrorSeverity.ERROR);
4086                         log.debug("#mergeOldResourceMetadataWithNew - derived from resource {} not found", toscaResourceNameDerivedFrom);
4087                         throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, toscaResourceNameDerivedFrom);
4088                 }
4089                 return latestByToscaResourceName.left().value();
4090         }
4091
4092         private Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user,
4093                                                                                           boolean inTransaction, boolean needLock) {
4094
4095                 if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) {
4096                         // checkout
4097                         return lifecycleBusinessLogic.changeState(oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
4098                                         new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock)
4099                                         .left()
4100                                         .on(response -> failOnChangeState(response, user, oldResource, newResource));
4101                 }
4102                 return oldResource;
4103         }
4104
4105         private Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) {
4106                 log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(), response.getFormattedMessage());
4107                 componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
4108                                 ResourceVersionInfo.newBuilder()
4109                                                 .state(oldResource.getLifecycleState()
4110                                                                 .name())
4111                                                 .version(oldResource.getVersion())
4112                                                 .build());
4113                 throw new ByResponseFormatComponentException(response);
4114         }
4115
4116         public Resource validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum,
4117                                                                                                  boolean inTransaction, CsarInfo csarInfo) {
4118
4119                 validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
4120                 validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
4121                 validateLifecycleTypesCreate(user, resource, actionEnum);
4122                 validateResourceType(user, resource, actionEnum);
4123                 resource.setCreatorUserId(user.getUserId());
4124                 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
4125                 resource.setContactId(resource.getContactId()
4126                                 .toLowerCase());
4127                 if (StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) {
4128                         String resourceSystemName;
4129                         if (csarInfo != null && StringUtils.isNotEmpty(csarInfo.getVfResourceName())) {
4130                                 resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName());
4131                         } else {
4132                                 resourceSystemName = resource.getSystemName();
4133                         }
4134                         resource.setToscaResourceName(CommonBeUtils
4135                                 .generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
4136                 }
4137
4138                 // Generate invariant UUID - must be here and not in operation since it
4139                 // should stay constant during clone
4140                 // TODO
4141                 String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
4142                 resource.setInvariantUUID(invariantUUID);
4143
4144                 return resource;
4145         }
4146
4147         private Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource,
4148                                                                                                                                  AuditingActionEnum actionEnum) {
4149                 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4150                 if (resource.getResourceType() == null) {
4151                         log.debug("Invalid resource type for resource");
4152                         ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
4153                         eitherResult = Either.right(errorResponse);
4154                         componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4155                 }
4156                 return eitherResult;
4157         }
4158
4159         private Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource,
4160                                                                                                                                                  AuditingActionEnum actionEnum) {
4161                 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4162                 if (resource.getInterfaces() != null && resource.getInterfaces()
4163                                 .size() > 0) {
4164                         log.debug("validate interface lifecycle Types Exist");
4165                         Iterator<InterfaceDefinition> intItr = resource.getInterfaces()
4166                                         .values()
4167                                         .iterator();
4168                         while (intItr.hasNext() && eitherResult.isLeft()) {
4169                                 InterfaceDefinition interfaceDefinition = intItr.next();
4170                                 String intType = interfaceDefinition.getUniqueId();
4171                                 Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation
4172                                                 .getInterface(intType);
4173                                 if (eitherCapTypeFound.isRight()) {
4174                                         if (eitherCapTypeFound.right()
4175                                                         .value() == StorageOperationStatus.NOT_FOUND) {
4176                                                 BeEcompErrorManager.getInstance()
4177                                                                 .logBeGraphObjectMissingError("Create Resource - validateLifecycleTypesCreate",
4178                                                                                 "Interface", intType);
4179                                                 log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB",
4180                                                                 intType, resource.getName());
4181                                                 BeEcompErrorManager.getInstance()
4182                                                                 .logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
4183                                                 log.debug("request to data model failed with error: {}", eitherCapTypeFound.right()
4184                                                                 .value()
4185                                                                 .name());
4186                                         }
4187
4188                                         ResponseFormat errorResponse = componentsUtils
4189                                                         .getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
4190                                         eitherResult = Either.right(errorResponse);
4191                                         componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4192                                 }
4193
4194                         }
4195                 }
4196                 return eitherResult;
4197         }
4198
4199         private Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user,
4200                                                                                                                                                   ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
4201                                                                                                                                                   boolean inTransaction) {
4202
4203                 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4204                 if (resource.getCapabilities() != null && resource.getCapabilities()
4205                                 .size() > 0) {
4206                         log.debug("validate capability Types Exist - capabilities section");
4207
4208                         for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities()
4209                                         .entrySet()) {
4210
4211                                 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum,
4212                                                 eitherResult, typeEntry, inTransaction);
4213                                 if (eitherResult.isRight()) {
4214                                         return Either.right(eitherResult.right()
4215                                                         .value());
4216                                 }
4217                         }
4218                 }
4219
4220                 if (resource.getRequirements() != null && resource.getRequirements()
4221                                 .size() > 0) {
4222                         log.debug("validate capability Types Exist - requirements section");
4223                         for (String type : resource.getRequirements()
4224                                         .keySet()) {
4225                                 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource,
4226                                                 resource.getRequirements()
4227                                                                 .get(type),
4228                                                 actionEnum, eitherResult, type, inTransaction);
4229                                 if (eitherResult.isRight()) {
4230                                         return Either.right(eitherResult.right()
4231                                                         .value());
4232                                 }
4233                         }
4234                 }
4235
4236                 return eitherResult;
4237         }
4238
4239         // @param typeObject- the object to which the validation is done
4240         private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
4241                                                                                                                                                  ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List<?> validationObjects,
4242                                                                                                                                                  AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type,
4243                                                                                                                                                  boolean inTransaction) {
4244                 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
4245                                 .getCapabilityType(type, inTransaction);
4246                 if (eitherCapTypeFound.isRight()) {
4247                         if (eitherCapTypeFound.right()
4248                                         .value() == StorageOperationStatus.NOT_FOUND) {
4249                                 BeEcompErrorManager.getInstance()
4250                                                 .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type",
4251                                                                 type);
4252                                 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type,
4253                                                 resource.getName());
4254                                 BeEcompErrorManager.getInstance()
4255                                                 .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
4256                         }
4257                         log.debug("Trying to get capability type {} failed with error: {}", type, eitherCapTypeFound.right()
4258                                         .value()
4259                                         .name());
4260                         ResponseFormat errorResponse = null;
4261                         if (type != null) {
4262                                 errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
4263                         } else {
4264                                 errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE,
4265                                                 validationObjects);
4266                         }
4267                         eitherResult = Either.right(errorResponse);
4268                         componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4269                 }
4270                 return eitherResult;
4271         }
4272
4273         private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
4274                                                                                                                                                  ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
4275                                                                                                                                                  Either<Boolean, ResponseFormat> eitherResult, Entry<String, List<CapabilityDefinition>> typeEntry,
4276                                                                                                                                                  boolean inTransaction) {
4277                 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
4278                                 .getCapabilityType(typeEntry.getKey(), inTransaction);
4279                 if (eitherCapTypeFound.isRight()) {
4280                         if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
4281                                 BeEcompErrorManager.getInstance()
4282                                                 .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type",
4283                                                                 typeEntry.getKey());
4284                                 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB",
4285                                                 typeEntry.getKey(), resource.getName());
4286                                 BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
4287                         }
4288                         log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(),
4289                                         eitherCapTypeFound.right().value().name());
4290                         ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE,
4291                                         typeEntry.getKey());
4292                         componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4293                         return Either.right(errorResponse);
4294                 }
4295                 CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
4296                 if (capabilityTypeDefinition.getProperties() != null) {
4297                         for (CapabilityDefinition capDef : typeEntry.getValue()) {
4298                                 List<ComponentInstanceProperty> properties = capDef.getProperties();
4299                                 List<ComponentInstanceProperty> changedProperties = new ArrayList<>();
4300                                 if (properties == null || properties.isEmpty()) {
4301                                         for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
4302                                                 ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
4303                                                 changedProperties.add(newProp);
4304                                         }
4305                                 } else {
4306                                         List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
4307                                         for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
4308                                                 PropertyDefinition propFromDef = prop.getValue();
4309                                                 boolean propFound = false;
4310                                                 for (ComponentInstanceProperty cip : properties) {
4311                                                         if (propFromDef.getName().equals(cip.getName())) {
4312                                                                 //merge property value and property description only, ignore other fields
4313                                                                 if(cip.getDescription() != null && !cip.getDescription().equals(propFromDef.getDescription())){
4314                                                                         propFromDef.setDescription(cip.getDescription());
4315                                                                 }
4316                                                                 propertyDataValueMergeBusinessLogic.mergePropertyValue(propFromDef, cip, new ArrayList<>());
4317                                                                 if(cip.getValue() != null){
4318                                                                         propFromDef.setValue(cip.getValue());
4319                                                                 }
4320                                                                 propsToAdd.add(new ComponentInstanceProperty(propFromDef));
4321                                                                 propFound = true;
4322                                                                 properties.remove(cip);
4323                                                                 break;
4324                                                         }
4325                                                 }
4326                                                 if(!propFound) {
4327                                                         propsToAdd.add(new ComponentInstanceProperty(propFromDef));
4328                                                 }
4329                                         }
4330                                         if (!propsToAdd.isEmpty()) {
4331                                                 changedProperties.addAll(propsToAdd);
4332                                         }
4333                                 }
4334                                 capDef.setProperties(changedProperties);
4335                         }
4336                 }
4337                 return eitherResult;
4338         }
4339
4340         public Resource createResourceByDao(Resource resource, User user, AuditingActionEnum actionEnum,
4341                                                                                 boolean isNormative, boolean inTransaction) {
4342                 // create resource
4343
4344                 // lock new resource name in order to avoid creation resource with same
4345                 // name
4346                 Resource createdResource = null;
4347                 if (!inTransaction) {
4348                         Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
4349                                         CREATE_RESOURCE);
4350                         if (lockResult.isRight()) {
4351                                 ResponseFormat responseFormat = lockResult.right().value();
4352                                 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4353                                 throw new ByResponseFormatComponentException(responseFormat);
4354                         }
4355
4356                         log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
4357                 }
4358                 try {
4359                         if (resource.deriveFromGeneric()) {
4360                                 handleResourceGenericType(resource);
4361                         }
4362                         createdResource = createResourceTransaction(resource, user, isNormative);
4363                         componentsUtils.auditResource(componentsUtils.getResponseFormat(ActionStatus.CREATED), user,
4364                                         createdResource, actionEnum);
4365                         ASDCKpiApi.countCreatedResourcesKPI();
4366                 } catch (ComponentException e) {
4367                         ResponseFormat responseFormat = e.getResponseFormat() == null
4368                                         ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
4369                         componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4370                         throw e;
4371                 } catch (StorageException e) {
4372                         ResponseFormat responseFormat = componentsUtils
4373                                         .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
4374                         componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4375                         throw e;
4376                 } finally {
4377                         if (!inTransaction) {
4378                                 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
4379                                                 NodeTypeEnum.Resource);
4380                         }
4381                 }
4382                 return createdResource;
4383         }
4384
4385         private Resource createResourceTransaction(Resource resource, User user, boolean isNormative) {
4386                 // validate resource name uniqueness
4387                 log.debug("validate resource name");
4388                 Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(
4389                                 resource.getName(), resource.getResourceType(), resource.getComponentType());
4390                 if (eitherValidation.isRight()) {
4391                         loggerSupportability.log(LoggerSupportabilityActions.VALIDATE_NAME,resource.getComponentMetadataForSupportLog(),
4392                                         StatusCode.ERROR,"ERROR while validate component name {} Status is: {}",resource.getName(),eitherValidation.right().value());
4393                         log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(),
4394                                         eitherValidation.right()
4395                                                         .value());
4396                         throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(eitherValidation.right()
4397                                         .value()));
4398                 }
4399                 if (eitherValidation.left()
4400                                 .value()) {
4401                         log.debug("resource with name: {}, already exists", resource.getName());
4402                         loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(),
4403                                         StatusCode.ERROR,"resource with name: {} already exists",resource.getName());
4404                         throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
4405                                         ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
4406                 }
4407
4408                 log.debug("send resource {} to dao for create", resource.getName());
4409
4410                 createArtifactsPlaceHolderData(resource, user);
4411                 // enrich object
4412                 if (!isNormative) {
4413                         log.debug("enrich resource with creator, version and state");
4414                         resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
4415                         resource.setVersion(INITIAL_VERSION);
4416                         resource.setHighestVersion(true);
4417                         if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC) {
4418                                 resource.setAbstract(false);
4419                         }
4420                 }
4421                 return toscaOperationFacade.createToscaComponent(resource)
4422                                 .left()
4423                                 .on(r -> throwComponentExceptionByResource(r, resource));
4424         }
4425
4426         private Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) {
4427                 ResponseFormat responseFormat = componentsUtils
4428                                 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status), resource);
4429                 throw new ByResponseFormatComponentException(responseFormat);
4430         }
4431
4432         private void createArtifactsPlaceHolderData(Resource resource, User user) {
4433                 // create mandatory artifacts
4434
4435                 // TODO it must be removed after that artifact uniqueId creation will be
4436                 // moved to ArtifactOperation
4437
4438                 setInformationalArtifactsPlaceHolder(resource, user);
4439                 setDeploymentArtifactsPlaceHolder(resource, user);
4440                 setToscaArtifactsPlaceHolders(resource, user);
4441         }
4442
4443         @SuppressWarnings("unchecked")
4444         @Override
4445         public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
4446                 Resource resource = (Resource) component;
4447                 Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
4448                 if (artifactMap == null) {
4449                         artifactMap = new HashMap<>();
4450                 }
4451                 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
4452                                 .getConfiguration()
4453                                 .getDeploymentResourceArtifacts();
4454                 if (deploymentResourceArtifacts != null) {
4455                         Map<String, ArtifactDefinition> finalArtifactMap = artifactMap;
4456                         deploymentResourceArtifacts
4457                                         .forEach((k, v) -> processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k, v));
4458                 }
4459                 resource.setDeploymentArtifacts(artifactMap);
4460         }
4461
4462         private void processDeploymentResourceArtifacts(User user, Resource resource,
4463                                                                                                         Map<String, ArtifactDefinition> artifactMap, String k, Object v) {
4464                 boolean shouldCreateArtifact = true;
4465                 Map<String, Object> artifactDetails = (Map<String, Object>) v;
4466                 Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
4467                 if (object != null) {
4468                         List<String> artifactTypes = (List<String>) object;
4469                         if (!artifactTypes.contains(resource.getResourceType()
4470                                         .name())) {
4471                                 shouldCreateArtifact = false;
4472                                 return;
4473                         }
4474                 } else {
4475                         log.info("resource types for artifact placeholder {} were not defined. default is all resources", k);
4476                 }
4477                 if (shouldCreateArtifact) {
4478                         if (artifactsBusinessLogic != null) {
4479                                 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
4480                                                 resource.getUniqueId(), k, (Map<String, Object>) v, user, ArtifactGroupTypeEnum.DEPLOYMENT);
4481                                 if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
4482                                         artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
4483                                 }
4484                         }
4485                 }
4486         }
4487
4488         @SuppressWarnings("unchecked")
4489         private void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
4490                 Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
4491                 if (artifactMap == null) {
4492                         artifactMap = new HashMap<>();
4493                 }
4494                 String resourceUniqueId = resource.getUniqueId();
4495                 List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager()
4496                                 .getConfiguration()
4497                                 .getExcludeResourceCategory();
4498                 List<String> exludeResourceType = ConfigurationManager.getConfigurationManager()
4499                                 .getConfiguration()
4500                                 .getExcludeResourceType();
4501                 Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager()
4502                                 .getConfiguration()
4503                                 .getInformationalResourceArtifacts();
4504                 List<CategoryDefinition> categories = resource.getCategories();
4505                 boolean isCreateArtifact = true;
4506                 if (exludeResourceCategory != null) {
4507                         String category = categories.get(0)
4508                                         .getName();
4509                         isCreateArtifact = exludeResourceCategory.stream()
4510                                         .noneMatch(e -> e.equalsIgnoreCase(category));
4511                 }
4512                 if (isCreateArtifact && exludeResourceType != null) {
4513                         String resourceType = resource.getResourceType()
4514                                         .name();
4515                         isCreateArtifact = exludeResourceType.stream()
4516                                         .noneMatch(e -> e.equalsIgnoreCase(resourceType));
4517                 }
4518                 if (informationalResourceArtifacts != null && isCreateArtifact) {
4519                         Set<String> keys = informationalResourceArtifacts.keySet();
4520                         for (String informationalResourceArtifactName : keys) {
4521                                 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts
4522                                                 .get(informationalResourceArtifactName);
4523                                 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
4524                                                 resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
4525                                                 ArtifactGroupTypeEnum.INFORMATIONAL);
4526                                 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
4527
4528                         }
4529                 }
4530                 resource.setArtifacts(artifactMap);
4531         }
4532
4533         /**
4534          * deleteResource
4535          *
4536          * @param resourceId
4537          * @param user
4538          * @return
4539          */
4540         public ResponseFormat deleteResource(String resourceId, User user) {
4541                 ResponseFormat responseFormat;
4542                 validateUserExists(user);
4543
4544                 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId);
4545                 if (resourceStatus.isRight()) {
4546                         log.debug("failed to get resource {}", resourceId);
4547                         return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right()
4548                                         .value()), "");
4549                 }
4550
4551                 Resource resource = resourceStatus.left()
4552                                 .value();
4553
4554                 StorageOperationStatus result = StorageOperationStatus.OK;
4555                 lockComponent(resourceId, resource, "Mark resource to delete");
4556                 try {
4557
4558                         result = markComponentToDelete(resource);
4559                         if (result == StorageOperationStatus.OK) {
4560                                 responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
4561                         } else {
4562                                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
4563                                 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
4564                         }
4565                         return responseFormat;
4566
4567                 } finally {
4568                         if (result == null || result != StorageOperationStatus.OK) {
4569                                 janusGraphDao.rollback();
4570                         } else {
4571                 janusGraphDao.commit();
4572                         }
4573                         graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
4574                 }
4575
4576         }
4577
4578         public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) {
4579                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
4580                 validateUserExists(user);
4581                 Resource resource = null;
4582                 StorageOperationStatus result = StorageOperationStatus.OK;
4583                 boolean failed = false;
4584                 try {
4585
4586                         Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade
4587                                         .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version);
4588                         if (resourceStatus.isRight()) {
4589                                 log.debug("failed to get resource {} version {}", resourceName, version);
4590                                 return componentsUtils
4591                                                 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceStatus.right()
4592                                                                 .value()), resourceName);
4593                         }
4594
4595                         resource = resourceStatus.left()
4596                                         .value();
4597
4598                 } finally {
4599                         janusGraphDao.commit();
4600                 }
4601                 if (resource != null) {
4602                         lockComponent(resource.getUniqueId(), resource, DELETE_RESOURCE);
4603                         try {
4604                                 result = markComponentToDelete(resource);
4605                                 if (result != StorageOperationStatus.OK) {
4606                                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
4607                                         responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
4608                                         return responseFormat;
4609                                 }
4610                         }catch (ComponentException e){
4611                                 failed = true;
4612                                 throw e;
4613                         }finally {
4614                                 if (failed || result == null || result != StorageOperationStatus.OK) {
4615                                         janusGraphDao.rollback();
4616                                 } else {
4617                     janusGraphDao.commit();
4618                                 }
4619                                 graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource);
4620                         }
4621                 }
4622                 return responseFormat;
4623         }
4624
4625         public Either<Resource, ResponseFormat> getResource(String resourceId, User user) {
4626
4627                 if (user != null) {
4628                         validateUserExists(user);
4629                 }
4630
4631                 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId);
4632                 if (storageStatus.isRight()) {
4633                         log.debug("failed to get resource by id {}", resourceId);
4634                         return Either.right(componentsUtils
4635                                         .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right()
4636                                                         .value()), resourceId));
4637                 }
4638                 if (!(storageStatus.left()
4639                                 .value() instanceof Resource)) {
4640                         return Either.right(componentsUtils.getResponseFormatByResource(
4641                                         componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId));
4642                 }
4643                 return Either.left(storageStatus.left()
4644                                 .value());
4645
4646         }
4647
4648         public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion,
4649                                                                                                                                                 String userId) {
4650
4651                 validateUserExists(userId);
4652
4653                 Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade
4654                                 .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion);
4655                 if (getResource.isRight()) {
4656                         log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion);
4657                         return Either.right(componentsUtils
4658                                         .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResource.right()
4659                                                         .value()), resourceName));
4660                 }
4661                 return Either.left(getResource.left()
4662                                 .value());
4663         }
4664
4665         /**
4666          * updateResourceMetadata
4667          *
4668          * @param user
4669          *            - modifier data (userId)
4670          * @param inTransaction
4671          *            TODO
4672          * @param resourceIdToUpdate
4673          *            - the resource identifier
4674          * @param newResource
4675          * @return Either<Resource , responseFormat>
4676          */
4677         public Resource updateResourceMetadata(String resourceIdToUpdate, Resource newResource, Resource currentResource,
4678                                                                                    User user, boolean inTransaction) {
4679
4680                 validateUserExists(user.getUserId());
4681
4682                 log.debug("Get resource with id {}", resourceIdToUpdate);
4683                 boolean needToUnlock = false;
4684
4685                 try {
4686                         if (currentResource == null) {
4687                                 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade
4688                                                 .getToscaElement(resourceIdToUpdate);
4689                                 if (storageStatus.isRight()) {
4690                                         throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatByResource(
4691                                                         componentsUtils.convertFromStorageResponse(storageStatus.right()
4692                                                                         .value()),
4693                                                         ""));
4694                                 }
4695
4696                                 currentResource = storageStatus.left()
4697                                                 .value();
4698                         }
4699                         // verify that resource is checked-out and the user is the last
4700                         // updater
4701                         if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) {
4702                                 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
4703                         }
4704
4705                         // lock resource
4706                         StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate,
4707                                         NodeTypeEnum.Resource);
4708                         if (lockResult != StorageOperationStatus.OK) {
4709                                 BeEcompErrorManager.getInstance()
4710                                                 .logBeFailedLockObjectError("Upload Artifact - lock ", NodeTypeEnum.Resource.getName(),
4711                                                                 resourceIdToUpdate);
4712                                 log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult);
4713                                 ResponseFormat responseFormat = componentsUtils
4714                                                 .getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
4715                                 throw new ByResponseFormatComponentException(responseFormat);
4716                         }
4717
4718                         needToUnlock = true;
4719
4720                         // critical section starts here
4721                         // convert json to object
4722
4723                         // Update and updated resource must have a non-empty "derivedFrom"
4724                         // list
4725                         // This code is not called from import resources, because of root
4726                         // VF "derivedFrom" should be null (or ignored)
4727                         if (ModelConverter.isAtomicComponent(currentResource)) {
4728                                 validateDerivedFromNotEmpty(null, newResource, null);
4729                                 validateDerivedFromNotEmpty(null, currentResource, null);
4730                         } else {
4731                                 newResource.setDerivedFrom(null);
4732                         }
4733
4734             Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource,
4735                     user, currentResource, false, true);
4736             if (dataModelResponse.isRight()) {
4737                 log.debug("failed to update resource metadata!!!");
4738                 throw new ByResponseFormatComponentException(dataModelResponse.right().value());
4739             }
4740
4741                         log.debug("Resource metadata updated successfully!!!");
4742                         return dataModelResponse.left()
4743                                         .value();
4744
4745                 } catch (ComponentException | StorageException e) {
4746                         rollback(inTransaction, newResource, null, null);
4747                         throw e;
4748                 } finally {
4749                         if (!inTransaction) {
4750                 janusGraphDao.commit();
4751                         }
4752                         if (needToUnlock) {
4753                                 graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
4754                         }
4755                 }
4756         }
4757
4758         private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource,
4759                                                                                                                                         User user, Resource currentResource, boolean shouldLock, boolean inTransaction) {
4760                 updateVfModuleGroupsNames(currentResource, newResource);
4761                 validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction, false);
4762                 // Setting last updater and uniqueId
4763                 newResource.setContactId(newResource.getContactId()
4764                                 .toLowerCase());
4765                 newResource.setLastUpdaterUserId(user.getUserId());
4766                 newResource.setUniqueId(resourceIdToUpdate);
4767                 // Cannot set highest version through UI
4768                 newResource.setHighestVersion(currentResource.isHighestVersion());
4769                 newResource.setCreationDate(currentResource.getCreationDate());
4770
4771                 Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource,
4772                                 newResource, user.getUserId(), inTransaction);
4773
4774                 if (processUpdateOfDerivedFrom.isRight()) {
4775                         log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate);
4776                         return Either.right(processUpdateOfDerivedFrom.right()
4777                                         .value());
4778                 }
4779
4780                 log.debug("send resource {} to dao for update", newResource.getUniqueId());
4781                 if (isNotEmpty(newResource.getGroups())) {
4782                         for (GroupDefinition group : newResource.getGroups()) {
4783                                 if (DEFAULT_GROUP_VF_MODULE.equals(group.getType())) {
4784                                         groupBusinessLogic.validateAndUpdateGroupMetadata(newResource.getComponentMetadataDefinition()
4785                                                         .getMetadataDataDefinition()
4786                                                         .getUniqueId(), user, newResource.getComponentType(), group, true, false);
4787                                 }
4788                         }
4789                 }
4790                 Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade
4791                                 .updateToscaElement(newResource);
4792
4793                 if (dataModelResponse.isRight()) {
4794                         ResponseFormat responseFormat = componentsUtils
4795                                         .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(dataModelResponse.right()
4796                                                         .value()), newResource);
4797                         return Either.right(responseFormat);
4798                 } else if (dataModelResponse.left()
4799                                 .value() == null) {
4800                         log.debug("No response from updateResource");
4801                         return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4802                 }
4803                 return Either.left(dataModelResponse.left()
4804                                 .value());
4805         }
4806
4807         private void updateVfModuleGroupsNames(Resource currentResource, Resource newResource) {
4808                 if (currentResource.getGroups() != null && !currentResource.getName()
4809                                 .equals(newResource.getName())) {
4810                         List<GroupDefinition> updatedGroups = currentResource.getGroups()
4811                                         .stream()
4812                                         .map(group -> getUpdatedGroup(group, currentResource.getName(), newResource.getName()))
4813                                         .collect(toList());
4814                         newResource.setGroups(updatedGroups);
4815                 }
4816         }
4817
4818         private GroupDefinition getUpdatedGroup(GroupDefinition currGroup, String replacePattern, String with) {
4819                 GroupDefinition updatedGroup = new GroupDefinition(currGroup);
4820                 if (updatedGroup.isSamePrefix(replacePattern) && updatedGroup.getType()
4821                                 .equals(DEFAULT_GROUP_VF_MODULE)) {
4822                         String prefix = updatedGroup.getName()
4823                                         .substring(0, replacePattern.length());
4824                         String newGroupName = updatedGroup.getName()
4825                                         .replaceFirst(prefix, with);
4826                         updatedGroup.setName(newGroupName);
4827                 }
4828                 return updatedGroup;
4829         }
4830
4831         /**
4832          * validateResourceFieldsBeforeCreate
4833          *
4834          * @param user
4835          *            - modifier data (userId)
4836          */
4837         private void validateResourceFieldsBeforeCreate(User user, Resource resource,
4838                                                                                                         AuditingActionEnum actionEnum, boolean inTransaction) {
4839                 componentValidator.validate(user, resource, actionEnum);
4840                 // validate category
4841                 log.debug("validate category");
4842                 validateCategory(user, resource, actionEnum, inTransaction);
4843                 // validate vendor name & release & model number
4844                 log.debug("validate vendor name");
4845                 validateVendorName(user, resource, actionEnum);
4846                 log.debug("validate vendor release");
4847                 validateVendorReleaseName(user, resource, actionEnum);
4848                 log.debug("validate resource vendor model number");
4849                 validateResourceVendorModelNumber(user, resource, actionEnum);
4850                 // validate cost
4851                 log.debug("validate cost");
4852                 validateCost(resource);
4853                 // validate licenseType
4854                 log.debug("validate licenseType");
4855                 validateLicenseType(user, resource, actionEnum);
4856                 // validate template (derived from)
4857                 log.debug("validate derived from");
4858                 if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
4859                         resource.setDerivedFrom(null);
4860                 }
4861                 validateDerivedFromExist(user, resource, actionEnum);
4862                 // warn about non-updatable fields
4863                 checkComponentFieldsForOverrideAttempt(resource);
4864                 String currentCreatorFullName = resource.getCreatorFullName();
4865                 if (currentCreatorFullName != null) {
4866                         log.debug("Resource Creator fullname is automatically set and cannot be updated");
4867                 }
4868
4869                 String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
4870                 if (currentLastUpdaterFullName != null) {
4871                         log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
4872                 }
4873
4874                 Long currentLastUpdateDate = resource.getLastUpdateDate();
4875                 if (currentLastUpdateDate != null) {
4876                         log.debug("Resource last update date is automatically set and cannot be updated");
4877                 }
4878
4879                 Boolean currentAbstract = resource.isAbstract();
4880                 if (currentAbstract != null) {
4881                         log.debug("Resource abstract is automatically set and cannot be updated");
4882                 }
4883         }
4884
4885         /**
4886          * validateResourceFieldsBeforeUpdate
4887          *
4888          * @param currentResource
4889          *            - Resource object to validate
4890          * @param isNested
4891          */
4892         private void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource,
4893                                                                                                         boolean inTransaction, boolean isNested) {
4894                 validateFields(currentResource, updateInfoResource, inTransaction, isNested);
4895                 warnNonEditableFields(currentResource, updateInfoResource);
4896         }
4897
4898         private void warnNonEditableFields(Resource currentResource, Resource updateInfoResource) {
4899                 String currentResourceVersion = currentResource.getVersion();
4900                 String updatedResourceVersion = updateInfoResource.getVersion();
4901
4902                 if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) {
4903                         log.debug("Resource version is automatically set and cannot be updated");
4904                 }
4905
4906                 String currentCreatorUserId = currentResource.getCreatorUserId();
4907                 String updatedCreatorUserId = updateInfoResource.getCreatorUserId();
4908
4909                 if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) {
4910                         log.debug("Resource Creator UserId is automatically set and cannot be updated");
4911                 }
4912
4913                 String currentCreatorFullName = currentResource.getCreatorFullName();
4914                 String updatedCreatorFullName = updateInfoResource.getCreatorFullName();
4915
4916                 if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) {
4917                         log.debug("Resource Creator fullname is automatically set and cannot be updated");
4918                 }
4919
4920                 String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId();
4921                 String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId();
4922
4923                 if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) {
4924                         log.debug("Resource LastUpdater userId is automatically set and cannot be updated");
4925                 }
4926
4927                 String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName();
4928                 String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName();
4929
4930                 if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) {
4931                         log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
4932                 }
4933                 Long currentCreationDate = currentResource.getCreationDate();
4934                 Long updatedCreationDate = updateInfoResource.getCreationDate();
4935
4936                 if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) {
4937                         log.debug("Resource Creation date is automatically set and cannot be updated");
4938                 }
4939
4940                 Long currentLastUpdateDate = currentResource.getLastUpdateDate();
4941                 Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate();
4942
4943                 if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) {
4944                         log.debug("Resource last update date is automatically set and cannot be updated");
4945                 }
4946
4947                 LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState();
4948                 LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState();
4949
4950                 if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) {
4951                         log.debug("Resource lifecycle state date is automatically set and cannot be updated");
4952                 }
4953
4954                 Boolean currentAbstract = currentResource.isAbstract();
4955                 Boolean updatedAbstract = updateInfoResource.isAbstract();
4956
4957                 if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) {
4958                         log.debug("Resource abstract is automatically set and cannot be updated");
4959                 }
4960
4961                 Boolean currentHighestVersion = currentResource.isHighestVersion();
4962                 Boolean updatedHighestVersion = updateInfoResource.isHighestVersion();
4963
4964                 if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) {
4965                         log.debug("Resource highest version is automatically set and cannot be updated");
4966                 }
4967
4968                 String currentUuid = currentResource.getUUID();
4969                 String updatedUuid = updateInfoResource.getUUID();
4970
4971                 if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) {
4972                         log.debug("Resource UUID is automatically set and cannot be updated");
4973                 }
4974
4975                 log.debug("Resource Type  cannot be updated");
4976                 String currentInvariantUuid = currentResource.getInvariantUUID();
4977                 String updatedInvariantUuid = updateInfoResource.getInvariantUUID();
4978
4979                 if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
4980                         log.debug("Resource invariant UUID is automatically set and cannot be updated");
4981                         updateInfoResource.setInvariantUUID(currentInvariantUuid);
4982                 }
4983         }
4984
4985         private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction,
4986                                                                 boolean isNested) {
4987                 boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
4988                 log.debug("validate resource name before update");
4989                 validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested);
4990                 log.debug("validate description before update");
4991                 componentDescriptionValidator.validateAndCorrectField(null, updateInfoResource, null);
4992                 log.debug("validate icon before update");
4993                 validateIcon(currentResource, updateInfoResource, hasBeenCertified);
4994                 log.debug("validate tags before update");
4995                 componentTagsValidator.validateAndCorrectField(null, updateInfoResource, null);
4996                 log.debug("validate vendor name before update");
4997                 validateVendorName(null, updateInfoResource, null);
4998                 log.debug("validate resource vendor model number before update");
4999                 validateResourceVendorModelNumber(currentResource, updateInfoResource);
5000                 log.debug("validate vendor release before update");
5001                 validateVendorReleaseName(null, updateInfoResource, null);
5002                 log.debug("validate contact info before update");
5003                 componentContactIdValidator.validateAndCorrectField(null, updateInfoResource, null);
5004                 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
5005                 validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified);
5006                 log.debug("validate category before update");
5007                 validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction);
5008         }
5009
5010         private boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) {
5011                 String resourceNameUpdated = updateInfoResource.getName();
5012                 String resourceNameCurrent = currentResource.getName();
5013                 if (resourceNameCurrent.equals(resourceNameUpdated)) {
5014                         return true;
5015                 }
5016                 // In case of CVFC type we should support the case of old VF with CVFC
5017                 // instances that were created without the "Cvfc" suffix
5018                 return currentResource.getResourceType() == ResourceTypeEnum.CVFC
5019                                 && resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent));
5020         }
5021
5022         private String addCvfcSuffixToResourceName(String resourceName) {
5023                 return resourceName + "Cvfc";
5024         }
5025
5026         private void validateResourceName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified,
5027                                                                           boolean isNested) {
5028                 String resourceNameUpdated = updateInfoResource.getName();
5029                 if (!isResourceNameEquals(currentResource, updateInfoResource)) {
5030                         if (isNested || !hasBeenCertified) {
5031                                 componentNameValidator.validateAndCorrectField(null, updateInfoResource, null);
5032                                 validateResourceNameUniqueness(updateInfoResource);
5033                                 currentResource.setName(resourceNameUpdated);
5034                                 currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
5035                                 currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
5036
5037                         } else {
5038                                 log.info("Resource name: {}, cannot be updated once the resource has been certified once.",
5039                                                 resourceNameUpdated);
5040                                 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
5041                         }
5042                 }
5043         }
5044
5045         private void validateIcon(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
5046                 String iconUpdated = updateInfoResource.getIcon();
5047                 String iconCurrent = currentResource.getIcon();
5048                 if (!iconCurrent.equals(iconUpdated)) {
5049                         if (!hasBeenCertified) {
5050                                 componentIconValidator.validateAndCorrectField(null, updateInfoResource, null);
5051                         } else {
5052                                 log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated);
5053                                 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
5054                         }
5055                 }
5056         }
5057
5058         private void validateResourceVendorModelNumber(Resource currentResource, Resource updateInfoResource) {
5059                 String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber();
5060                 String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber();
5061                 if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) {
5062                         validateResourceVendorModelNumber(null, updateInfoResource, null);
5063                 }
5064         }
5065
5066         private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource,
5067                                                                                                                          boolean hasBeenCertified, boolean inTransaction) {
5068                 validateCategory(null, updateInfoResource, null, inTransaction);
5069                 if (hasBeenCertified) {
5070                         CategoryDefinition currentCategory = currentResource.getCategories()
5071                                         .get(0);
5072                         SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories()
5073                                         .get(0);
5074                         CategoryDefinition updateCategory = updateInfoResource.getCategories()
5075                                         .get(0);
5076                         SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories()
5077                                         .get(0);
5078                         if (!currentCategory.getName()
5079                                         .equals(updateCategory.getName())
5080                                         || !currentSubCategory.getName()
5081                                         .equals(updtaeSubCategory.getName())) {
5082                                 log.info("Category {} cannot be updated once the resource has been certified once.",
5083                                                 currentResource.getCategories());
5084                                 ResponseFormat errorResponse = componentsUtils
5085                                                 .getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
5086                                 return Either.right(errorResponse);
5087                         }
5088                 }
5089                 return Either.left(true);
5090         }
5091
5092         private Either<Boolean, ResponseFormat> validateDerivedFromDuringUpdate(Resource currentResource,
5093                                                                                                                                                         Resource updateInfoResource, boolean hasBeenCertified) {
5094
5095                 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
5096                 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
5097                 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
5098                                 || updatedDerivedFrom.isEmpty()) {
5099                         log.trace("Update normative types");
5100                         return Either.left(true);
5101                 }
5102
5103                 String derivedFromCurrent = currentDerivedFrom.get(0);
5104                 String derivedFromUpdated = updatedDerivedFrom.get(0);
5105
5106                 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
5107                         if (!hasBeenCertified) {
5108                                 validateDerivedFromExist(null, updateInfoResource, null);
5109                         } else {
5110                                 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
5111                                                 currentResource, updateInfoResource, null);
5112
5113                                 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left()
5114                                                 .value()) {
5115                                         log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
5116                                         return validateDerivedFromExtending;
5117                                 }
5118                         }
5119                 } else {
5120                         // For derived from, we must know whether it was actually changed,
5121                         // otherwise we must do no action.
5122                         // Due to changes it inflicts on data model (remove artifacts,
5123                         // properties...), it's not like a flat field which can be
5124                         // overwritten if not changed.
5125                         // So we must indicate that derived from is not changed
5126                         updateInfoResource.setDerivedFrom(null);
5127                 }
5128                 return Either.left(true);
5129         }
5130
5131         private Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource,
5132                                                                                                                                                                   Resource updateInfoResource, boolean hasBeenCertified) {
5133
5134                 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
5135                 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
5136                 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
5137                                 || updatedDerivedFrom.isEmpty()) {
5138                         log.trace("Update normative types");
5139                         return Either.left(true);
5140                 }
5141
5142                 String derivedFromCurrent = currentDerivedFrom.get(0);
5143                 String derivedFromUpdated = updatedDerivedFrom.get(0);
5144
5145                 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
5146                         if (!hasBeenCertified) {
5147                                 validateDerivedFromExist(null, updateInfoResource, null);
5148                         } else {
5149                                 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
5150                                                 currentResource, updateInfoResource, null);
5151
5152                                 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left()
5153                                                 .value()) {
5154                                         log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
5155                                         return validateDerivedFromExtending;
5156                                 }
5157                         }
5158                 }
5159                 return Either.left(true);
5160         }
5161
5162         private void validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) {
5163                 if (resource.getDerivedFrom() == null || resource.getDerivedFrom()
5164                                 .isEmpty()) {
5165                         return;
5166                 }
5167                 String templateName = resource.getDerivedFrom()
5168                                 .get(0);
5169                 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
5170                                 .validateToscaResourceNameExists(templateName);
5171                 if (dataModelResponse.isRight()) {
5172                         StorageOperationStatus storageStatus = dataModelResponse.right()
5173                                         .value();
5174                         BeEcompErrorManager.getInstance()
5175                                         .logBeDaoSystemError("Create Resource - validateDerivedFromExist");
5176                         log.debug("request to data model failed with error: {}", storageStatus);
5177                         ResponseFormat responseFormat = componentsUtils
5178                                         .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
5179                         log.trace("audit before sending response");
5180                         componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5181                         throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus));
5182                 } else if (!dataModelResponse.left()
5183                                 .value()) {
5184                         log.info("resource template with name: {}, does not exists", templateName);
5185                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
5186                         componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5187                         throw new ByActionStatusComponentException(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
5188                 }
5189         }
5190
5191         // Tal G for extending inheritance US815447
5192         private Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource,
5193                                                                                                                                                  Resource updateInfoResource, AuditingActionEnum actionEnum) {
5194                 String currentTemplateName = currentResource.getDerivedFrom()
5195                                 .get(0);
5196                 String updatedTemplateName = updateInfoResource.getDerivedFrom()
5197                                 .get(0);
5198
5199                 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
5200                                 .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName);
5201                 if (dataModelResponse.isRight()) {
5202                         StorageOperationStatus storageStatus = dataModelResponse.right()
5203                                         .value();
5204                         BeEcompErrorManager.getInstance()
5205                                         .logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
5206                         ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
5207                                         componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
5208                         log.trace("audit before sending response");
5209                         componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
5210                         return Either.right(responseFormat);
5211                 }
5212
5213                 if (!dataModelResponse.left()
5214                                 .value()) {
5215                         log.info("resource template with name {} does not inherit as original {}", updatedTemplateName,
5216                                         currentTemplateName);
5217                         ResponseFormat responseFormat = componentsUtils
5218                                         .getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
5219                         componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
5220
5221                         return Either.right(responseFormat);
5222
5223                 }
5224                 return Either.left(true);
5225         }
5226
5227         public void validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
5228                 log.debug("validate resource derivedFrom field");
5229                 if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom()
5230                                 .isEmpty())
5231                                 || (resource.getDerivedFrom()
5232                                 .get(0)) == null
5233                                 || (resource.getDerivedFrom()
5234                                 .get(0)
5235                                 .trim()
5236                                 .isEmpty())) {
5237                         log.info("derived from (template) field is missing for the resource");
5238                         ResponseFormat responseFormat = componentsUtils
5239                                         .getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
5240                         componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5241
5242                         throw new ByActionStatusComponentException(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
5243                 }
5244         }
5245
5246         private void validateResourceNameUniqueness(Resource resource) {
5247
5248                 Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade
5249                                 .validateComponentNameExists(resource.getName(), resource.getResourceType(),
5250                                                 resource.getComponentType());
5251                 if (resourceOperationResponse.isLeft() && resourceOperationResponse.left()
5252                                 .value()) {
5253                         log.debug("resource with name: {}, already exists", resource.getName());
5254                         throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
5255                                         ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
5256                 } else if (resourceOperationResponse.isRight()) {
5257                         log.debug("error while validateResourceNameExists for resource: {}", resource.getName());
5258                         throw new StorageException(resourceOperationResponse.right()
5259                                         .value());
5260                 }
5261         }
5262
5263         private void validateCategory(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
5264
5265                 List<CategoryDefinition> categories = resource.getCategories();
5266                 if (CollectionUtils.isEmpty(categories)) {
5267                         log.debug(CATEGORY_IS_EMPTY);
5268                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
5269                                         ComponentTypeEnum.RESOURCE.getValue());
5270                         componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5271                         throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
5272                                         ComponentTypeEnum.RESOURCE.getValue());
5273                 }
5274                 if (categories.size() > 1) {
5275                         log.debug("Must be only one category for resource");
5276                         throw new ByActionStatusComponentException(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES,
5277                                         ComponentTypeEnum.RESOURCE.getValue());
5278                 }
5279                 CategoryDefinition category = categories.get(0);
5280                 List<SubCategoryDefinition> subcategories = category.getSubcategories();
5281                 if (CollectionUtils.isEmpty(subcategories)) {
5282                         log.debug("Missinig subcategory for resource");
5283                         throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
5284                 }
5285                 if (subcategories.size() > 1) {
5286                         log.debug("Must be only one sub category for resource");
5287                         throw new ByActionStatusComponentException(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
5288                 }
5289
5290                 SubCategoryDefinition subcategory = subcategories.get(0);
5291
5292                 if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
5293                         log.debug(CATEGORY_IS_EMPTY);
5294                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
5295                                         ComponentTypeEnum.RESOURCE.getValue());
5296                         componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5297                         throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
5298                                         ComponentTypeEnum.RESOURCE.getValue());
5299                 }
5300                 if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
5301                         log.debug(CATEGORY_IS_EMPTY);
5302                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(
5303                                         ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
5304                         componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5305                         throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY,
5306                                         ComponentTypeEnum.RESOURCE.getValue());
5307                 }
5308
5309                 validateCategoryListed(category, subcategory, user, resource, actionEnum, inTransaction);
5310         }
5311
5312         private void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory, User user,
5313                                                                                 Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
5314                 ResponseFormat responseFormat;
5315                 if (category != null && subcategory != null) {
5316                         log.debug("validating resource category {} against valid categories list", category);
5317                         Either<List<CategoryDefinition>, ActionStatus> categories = elementDao
5318                                         .getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
5319                         if (categories.isRight()) {
5320                                 log.debug("failed to retrieve resource categories from JanusGraph");
5321                                 responseFormat = componentsUtils.getResponseFormat(categories.right()
5322                                                 .value());
5323                                 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5324                                 throw new ByActionStatusComponentException(categories.right()
5325                                                 .value());
5326                         }
5327                         List<CategoryDefinition> categoryList = categories.left()
5328                                         .value();
5329                         Optional<CategoryDefinition> foundCategory = categoryList.stream()
5330                                         .filter(cat -> cat.getName()
5331                                                         .equals(category.getName()))
5332                                         .findFirst();
5333                         if (!foundCategory.isPresent()) {
5334                                 log.debug("Category {} is not part of resource category group. Resource category valid values are {}",
5335                                                 category, categoryList);
5336                                 failOnInvalidCategory(user, resource, actionEnum);
5337                         }
5338                         Optional<SubCategoryDefinition> foundSubcategory = foundCategory.get()
5339                                         .getSubcategories()
5340                                         .stream()
5341                                         .filter(subcat -> subcat.getName()
5342                                                         .equals(subcategory.getName()))
5343                                         .findFirst();
5344                         if (!foundSubcategory.isPresent()) {
5345                                 log.debug(
5346                                                 "SubCategory {} is not part of resource category group. Resource subcategory valid values are {}",
5347                                                 subcategory, foundCategory.get()
5348                                                                 .getSubcategories());
5349                                 failOnInvalidCategory(user, resource, actionEnum);
5350                         }
5351                 }
5352         }
5353
5354         private void failOnInvalidCategory(User user, Resource resource, AuditingActionEnum actionEnum) {
5355                 ResponseFormat responseFormat;
5356                 responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY,
5357                                 ComponentTypeEnum.RESOURCE.getValue());
5358                 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5359                 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
5360         }
5361
5362         public void validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) {
5363                 String vendorRelease = resource.getVendorRelease();
5364                 log.debug("validate vendor relese name");
5365                 if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) {
5366                         log.info("vendor relese name is missing.");
5367                         ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
5368                         componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5369                         throw new ByActionStatusComponentException(ActionStatus.MISSING_VENDOR_RELEASE);
5370                 }
5371
5372                 validateVendorReleaseName(vendorRelease, user, resource, actionEnum);
5373         }
5374
5375         public void validateVendorReleaseName(String vendorRelease, User user, Resource resource,
5376                                                                                   AuditingActionEnum actionEnum) {
5377                 if (vendorRelease != null) {
5378                         if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
5379                                 log.info("vendor release exceds limit.");
5380                                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
5381                                                 ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
5382                                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5383                                 throw new ByActionStatusComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT,
5384                                                 "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
5385                         }
5386
5387                         if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
5388                                 log.info("vendor release  is not valid.");
5389                                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
5390                                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5391                 throw new ByActionStatusComponentException(ActionStatus.INVALID_VENDOR_RELEASE, vendorRelease);
5392             }
5393         }
5394     }
5395
5396     private void validateVendorName(User user, Resource resource,
5397                                     AuditingActionEnum actionEnum) {
5398         String vendorName = resource.getVendorName();
5399         if (!ValidationUtils.validateStringNotEmpty(vendorName)) {
5400             log.info("vendor name is missing.");
5401             ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME);
5402             componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5403             throw new ByActionStatusComponentException(ActionStatus.MISSING_VENDOR_NAME);
5404         }
5405         validateVendorName(vendorName, user, resource, actionEnum);
5406     }
5407
5408     private void validateVendorName(String vendorName, User user, Resource resource,
5409                                     AuditingActionEnum actionEnum) {
5410         if (vendorName != null) {
5411             if (!ValidationUtils.validateVendorNameLength(vendorName)) {
5412                 log.info("vendor name exceds limit.");
5413                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
5414                         "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
5415                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5416                 throw new ByActionStatusComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
5417                         "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
5418             }
5419
5420             if (!ValidationUtils.validateVendorName(vendorName)) {
5421                 log.info("vendor name  is not valid.");
5422                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
5423                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5424                 throw new ByActionStatusComponentException(ActionStatus.INVALID_VENDOR_NAME, vendorName);
5425             }
5426         }
5427     }
5428
5429     private void validateResourceVendorModelNumber(User user, Resource resource, AuditingActionEnum actionEnum) {
5430         String resourceVendorModelNumber = resource.getResourceVendorModelNumber();
5431         if (StringUtils.isNotEmpty(resourceVendorModelNumber)) {
5432             if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
5433                 log.info("resource vendor model number exceeds limit.");
5434                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
5435                         ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
5436                         "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
5437                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5438                 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
5439                         "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
5440             }
5441             // resource vendor model number is currently validated as vendor
5442             // name
5443             if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) {
5444                 log.info("resource vendor model number  is not valid.");
5445                 ResponseFormat errorResponse = componentsUtils
5446                         .getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
5447                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5448                 throw new ByActionStatusComponentException(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
5449             }
5450         }
5451     }
5452
5453
5454     private void validateCost(Resource resource) {
5455         String cost = resource.getCost();
5456         if (cost != null) {
5457             if (!ValidationUtils.validateCost(cost)) {
5458                 log.debug("resource cost is invalid.");
5459                 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
5460             }
5461         }
5462     }
5463
5464     private void validateLicenseType(User user, Resource resource,
5465                                      AuditingActionEnum actionEnum) {
5466         log.debug("validate licenseType");
5467         String licenseType = resource.getLicenseType();
5468         if (licenseType != null) {
5469             List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration()
5470                     .getLicenseTypes();
5471             if (!licenseTypes.contains(licenseType)) {
5472                 log.debug("License type {} isn't configured", licenseType);
5473                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
5474                 if (actionEnum != null) {
5475                     // In update case, no audit is required
5476                     componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5477                 }
5478                 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
5479             }
5480         }
5481     }
5482
5483         private Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom(Resource currentResource,
5484                                                                                                                                            Resource updatedResource, String userId, boolean inTransaction) {
5485                 Either<Operation, ResponseFormat> deleteArtifactByInterface;
5486                 if (updatedResource.getDerivedFrom() != null) {
5487                         log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId());
5488                         log.debug("1. Removing interface artifacts from graph");
5489                         // Remove all interface artifacts of resource
5490                         String resourceId = updatedResource.getUniqueId();
5491                         Map<String, InterfaceDefinition> interfaces = currentResource.getInterfaces();
5492
5493                         if (interfaces != null) {
5494                                 Collection<InterfaceDefinition> values = interfaces.values();
5495                                 for (InterfaceDefinition interfaceDefinition : values) {
5496                                         String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition);
5497
5498                                         log.trace("Starting interface artifacts removal for interface type {}", interfaceType);
5499                                         Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
5500                                         if (operations != null) {
5501                                                 for (Entry<String, Operation> operationEntry : operations.entrySet()) {
5502                                                         Operation operation = operationEntry.getValue();
5503                                                         ArtifactDefinition implementation = operation.getImplementationArtifact();
5504                                                         if (implementation != null) {
5505                                                                 String uniqueId = implementation.getUniqueId();
5506                                                                 log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}",
5507                                                                                 uniqueId, operationEntry.getKey(), interfaceType);
5508                                                                 // only thing that transacts and locks here
5509                                                                 deleteArtifactByInterface = artifactsBusinessLogic.deleteArtifactByInterface(resourceId,
5510                                                                                 userId, uniqueId, true);
5511                                                                 if (deleteArtifactByInterface.isRight()) {
5512                                                                         log.debug("Couldn't remove artifact definition with id {}", uniqueId);
5513                                                                         if (!inTransaction) {
5514                                         janusGraphDao.rollback();
5515                                                                         }
5516                                                                         return Either.right(deleteArtifactByInterface.right()
5517                                                                                         .value());
5518                                                                 }
5519                                                         } else {
5520                                                                 log.trace("No implementation found for operation {} - nothing to delete",
5521                                                                                 operationEntry.getKey());
5522                                                         }
5523                                                 }
5524                                         } else {
5525                                                 log.trace("No operations found for interface type {}", interfaceType);
5526                                         }
5527                                 }
5528                         }
5529                         log.debug("2. Removing properties");
5530                         Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = propertyOperation
5531                                         .deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId);
5532
5533                         if (findPropertiesOfNode.isRight() && findPropertiesOfNode.right().value() != StorageOperationStatus.OK) {
5534                                 log.debug("Failed to remove all properties of resource");
5535                                 if (!inTransaction) {
5536                     janusGraphDao.rollback();
5537                                 }
5538                                 return Either.right(componentsUtils
5539                                                 .getResponseFormat(componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right()
5540                                                                 .value())));
5541                         }
5542
5543                 } else {
5544                         log.debug("Derived from wasn't changed during update");
5545                 }
5546
5547                 if (inTransaction) {
5548                         return Either.left(true);
5549                 }
5550         janusGraphDao.commit();
5551                 return Either.left(true);
5552
5553         }
5554
5555         /**** Auditing *******************/
5556
5557         protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) {
5558                 WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
5559                                 .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
5560
5561                 WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
5562
5563                 return webApplicationContext.getBean(class1);
5564         }
5565
5566         public ICapabilityTypeOperation getCapabilityTypeOperation() {
5567                 return capabilityTypeOperation;
5568         }
5569
5570         @Autowired
5571         public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) {
5572                 this.capabilityTypeOperation = capabilityTypeOperation;
5573         }
5574
5575         public Boolean validatePropertiesDefaultValues(Resource resource) {
5576                 log.debug("validate resource properties default values");
5577                 List<PropertyDefinition> properties = resource.getProperties();
5578                 if (properties != null) {
5579                         iterateOverProperties(properties);
5580                 }
5581                 return true;
5582         }
5583
5584         public void iterateOverProperties(List<PropertyDefinition> properties) {
5585                 String type = null;
5586                 String innerType = null;
5587                 for (PropertyDefinition property : properties) {
5588                         if (!propertyOperation.isPropertyTypeValid(property)) {
5589                                 log.info("Invalid type for property {}", property);
5590                                 throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY_TYPE,
5591                                                 property.getType(), property.getName());
5592                         }
5593
5594                         Map<String, DataTypeDefinition> allDataTypes = getAllDataTypes(applicationDataTypeCache);
5595                         type = property.getType();
5596
5597                         if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
5598                                 ResponseFormat responseFormat = validateMapOrListPropertyType(property, innerType, allDataTypes);
5599                                 if (responseFormat != null) {
5600                                         break;
5601                                 }
5602                         }
5603                         validateDefaultPropertyValue(property, allDataTypes, type, innerType);
5604                 }
5605         }
5606
5607         private void validateDefaultPropertyValue(PropertyDefinition property,
5608                                                                                           Map<String, DataTypeDefinition> allDataTypes, String type, String innerType) {
5609                 if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes)) {
5610                         log.info("Invalid default value for property {}", property);
5611                         ResponseFormat responseFormat;
5612                         if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
5613                                 throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE,
5614                                                 property.getName(), type, innerType, property.getDefaultValue());
5615                         }
5616                         throw new ByActionStatusComponentException(ActionStatus.INVALID_DEFAULT_VALUE,
5617                                         property.getName(), type, property.getDefaultValue());
5618                 }
5619         }
5620
5621         private ResponseFormat validateMapOrListPropertyType(PropertyDefinition property, String innerType,
5622                                                                                                                  Map<String, DataTypeDefinition> allDataTypes) {
5623                 ResponseFormat responseFormat = null;
5624                 ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property,
5625                                 allDataTypes);
5626                 innerType = propertyInnerTypeValid.getLeft();
5627                 if (!propertyInnerTypeValid.getRight()
5628                                 .booleanValue()) {
5629                         log.info("Invalid inner type for property {}", property);
5630                         responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType,
5631                                         property.getName());
5632                 }
5633                 return responseFormat;
5634         }
5635
5636         @Override
5637         public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
5638                 return deleteMarkedComponents(ComponentTypeEnum.RESOURCE);
5639         }
5640
5641         @Override
5642         public ComponentInstanceBusinessLogic getComponentInstanceBL() {
5643                 return componentInstanceBusinessLogic;
5644         }
5645
5646         private String getComponentTypeForResponse(Component component) {
5647                 String componentTypeForResponse = "SERVICE";
5648                 if (component instanceof Resource) {
5649                         componentTypeForResponse = ((Resource) component).getResourceType()
5650                                         .name();
5651                 }
5652                 return componentTypeForResponse;
5653         }
5654
5655         public Either<Resource, ResponseFormat> getLatestResourceFromCsarUuid(String csarUuid, User user) {
5656                 // validate user
5657                 if (user != null) {
5658                         validateUserExists(user);
5659                 }
5660                 // get resource from csar uuid
5661                 Either<Resource, StorageOperationStatus> either = toscaOperationFacade
5662                                 .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, "");
5663                 if (either.isRight()) {
5664                         ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND,
5665                                         csarUuid);
5666                         return Either.right(resp);
5667                 }
5668
5669                 return Either.left(either.left()
5670                                 .value());
5671         }
5672
5673         @Override
5674         public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(
5675                         String componentId, String userId) {
5676                 return null;
5677         }
5678
5679         private Map<String, List<CapabilityDefinition>> getValidComponentInstanceCapabilities(String resourceId,
5680                                                                                                                                                                                   Map<String, List<CapabilityDefinition>> defaultCapabilities,
5681                                                                                                                                                                                   Map<String, List<UploadCapInfo>> uploadedCapabilities) {
5682
5683                 Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
5684                 uploadedCapabilities.forEach((k, v) -> addValidComponentInstanceCapabilities(k, v, resourceId,
5685                                 defaultCapabilities, validCapabilitiesMap));
5686                 return validCapabilitiesMap;
5687         }
5688
5689         private void addValidComponentInstanceCapabilities(String key, List<UploadCapInfo> capabilities, String resourceId,
5690                                                                                                            Map<String, List<CapabilityDefinition>> defaultCapabilities,
5691                                                                                                            Map<String, List<CapabilityDefinition>> validCapabilitiesMap) {
5692                 String capabilityType = capabilities.get(0)
5693                                 .getType();
5694                 if (defaultCapabilities.containsKey(capabilityType)) {
5695                         CapabilityDefinition defaultCapability = getCapability(resourceId, defaultCapabilities, capabilityType);
5696                         validateCapabilityProperties(capabilities, resourceId, defaultCapability);
5697                         List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
5698                         validCapabilityList.add(defaultCapability);
5699                         validCapabilitiesMap.put(key, validCapabilityList);
5700                 } else {
5701                         throw new ByActionStatusComponentException(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType);
5702                 }
5703         }
5704
5705         private void validateCapabilityProperties(List<UploadCapInfo> capabilities, String resourceId,
5706                                                                                           CapabilityDefinition defaultCapability) {
5707                 if (CollectionUtils.isEmpty(defaultCapability.getProperties()) && isNotEmpty(capabilities.get(0)
5708                                 .getProperties())) {
5709                         log.debug("Failed to validate capability {} of component {}. Property list is empty. ",
5710                                         defaultCapability.getName(), resourceId);
5711                         log.debug("Failed to update capability property values. Property list of fetched capability {} is empty. ",
5712                                         defaultCapability.getName());
5713                         throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, resourceId);
5714                 } else if (isNotEmpty(capabilities.get(0)
5715                                 .getProperties())) {
5716                         validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, capabilities.get(0));
5717                 }
5718         }
5719
5720         private CapabilityDefinition getCapability(String resourceId,
5721                                                                                            Map<String, List<CapabilityDefinition>> defaultCapabilities, String capabilityType) {
5722                 CapabilityDefinition defaultCapability;
5723                 if (isNotEmpty(defaultCapabilities.get(capabilityType)
5724                                 .get(0)
5725                                 .getProperties())) {
5726                         defaultCapability = defaultCapabilities.get(capabilityType)
5727                                         .get(0);
5728                 } else {
5729                         Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade
5730                                         .getToscaFullElement(resourceId);
5731                         if (getFullComponentRes.isRight()) {
5732                                 log.debug("Failed to get full component {}. Status is {}. ", resourceId, getFullComponentRes.right()
5733                                                 .value());
5734                                 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NOT_FOUND, resourceId);
5735                         }
5736                         defaultCapability = getFullComponentRes.left()
5737                                         .value()
5738                                         .getCapabilities()
5739                                         .get(capabilityType)
5740                                         .get(0);
5741                 }
5742                 return defaultCapability;
5743         }
5744
5745         private void validateUniquenessUpdateUploadedComponentInstanceCapability(CapabilityDefinition defaultCapability,
5746                                                                                                                                                          UploadCapInfo uploadedCapability) {
5747                 List<ComponentInstanceProperty> validProperties = new ArrayList<>();
5748                 Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties()
5749                                 .stream()
5750                                 .collect(toMap(PropertyDefinition::getName, Function.identity()));
5751                 List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
5752                 for (UploadPropInfo property : uploadedProperties) {
5753                         String propertyName = property.getName()
5754                                         .toLowerCase();
5755                         String propertyType = property.getType();
5756                         ComponentInstanceProperty validProperty;
5757                         if (defaultProperties.containsKey(propertyName)
5758                                         && propertTypeEqualsTo(defaultProperties, propertyName, propertyType)) {
5759                                 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, propertyName);
5760                         }
5761                         validProperty = new ComponentInstanceProperty();
5762                         validProperty.setName(propertyName);
5763                         if (property.getValue() != null) {
5764                                 validProperty.setValue(property.getValue()
5765                                                 .toString());
5766                         }
5767                         validProperty.setDescription(property.getDescription());
5768                         validProperty.setPassword(property.isPassword());
5769                         validProperties.add(validProperty);
5770                 }
5771                 defaultCapability.setProperties(validProperties);
5772         }
5773
5774         private boolean propertTypeEqualsTo(Map<String, PropertyDefinition> defaultProperties, String propertyName,
5775                                                                                 String propertyType) {
5776                 return propertyType != null && !defaultProperties.get(propertyName)
5777                                 .getType()
5778                                 .equals(propertyType);
5779         }
5780
5781         private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(
5782                         List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle,
5783                         Resource resource, User user) {
5784
5785                 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(
5786                                 ArtifactOperationEnum.class);
5787                 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
5788                 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either
5789                                 .left(nodeTypeArtifactsToHandle);
5790                 try {
5791                         // add all found Csar artifacts to list to upload
5792                         List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
5793                         List<NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
5794                         List<NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
5795                         for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
5796                                 ArtifactDefinition foundArtifact;
5797
5798                                 if (!existingArtifactsToHandle.isEmpty()) {
5799                                         foundArtifact = existingArtifactsToHandle.stream()
5800                                                         .filter(a -> a.getArtifactName()
5801                                                                         .equals(currNewArtifact.getArtifactName()))
5802                                                         .findFirst()
5803                                                         .orElse(null);
5804                                         if (foundArtifact != null) {
5805                                                 if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()) == currNewArtifact
5806                                                                 .getArtifactType()) {
5807                                                         if (!foundArtifact.getArtifactChecksum()
5808                                                                         .equals(currNewArtifact.getArtifactChecksum())) {
5809                                                                 currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
5810                                                                 // if current artifact already exists, but has
5811                                                                 // different content, add him to the list to
5812                                                                 // update
5813                                                                 artifactsToUpdate.add(currNewArtifact);
5814                                                         }
5815                                                         // remove found artifact from the list of existing
5816                                                         // artifacts to handle, because it was already
5817                                                         // handled
5818                                                         existingArtifactsToHandle.remove(foundArtifact);
5819                                                         // and remove found artifact from the list to
5820                                                         // upload, because it should either be updated or be
5821                                                         // ignored
5822                                                         artifactsToUpload.remove(currNewArtifact);
5823                                                 } else {
5824                                                         log.debug("Can't upload two artifact with the same name {}.",
5825                                                                         currNewArtifact.getArtifactName());
5826                                                         ResponseFormat responseFormat = ResponseFormatManager.getInstance()
5827                                                                         .getResponseFormat(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
5828                                                                                         currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType()
5829                                                                                                         .name(),
5830                                                                                         foundArtifact.getArtifactType());
5831                                                         AuditingActionEnum auditingAction = artifactsBusinessLogic
5832                                                                         .detectAuditingType(artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
5833                                                                                         ArtifactOperationEnum.CREATE), foundArtifact.getArtifactChecksum());
5834                                                         artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(),
5835                                                                         user, null, null, foundArtifact.getUniqueId(), responseFormat,
5836                                                                         resource.getComponentType(), null);
5837                                                         responseWrapper.setInnerElement(responseFormat);
5838                                                         break;
5839                                                 }
5840                                         }
5841                                 }
5842                         }
5843                         if (responseWrapper.isEmpty()) {
5844                                 for (ArtifactDefinition currArtifact : existingArtifactsToHandle) {
5845                                         if (currArtifact.getIsFromCsar()) {
5846                                                 artifactsToDelete.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null,
5847                                                                 ArtifactTypeEnum.findType(currArtifact.getArtifactType()),
5848                                                                 currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(),
5849                                                                 currArtifact.getIsFromCsar()));
5850                                         } else {
5851                                                 artifactsToUpdate.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null,
5852                                                                 ArtifactTypeEnum.findType(currArtifact.getArtifactType()),
5853                                                                 currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(),
5854                                                                 currArtifact.getIsFromCsar()));
5855
5856                                         }
5857                                 }
5858                         }
5859                         if (responseWrapper.isEmpty()) {
5860                                 if (!artifactsToUpload.isEmpty()) {
5861                                         nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
5862                                 }
5863                                 if (!artifactsToUpdate.isEmpty()) {
5864                                         nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
5865                                 }
5866                                 if (!artifactsToDelete.isEmpty()) {
5867                                         nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
5868                                 }
5869                         }
5870                         if (!responseWrapper.isEmpty()) {
5871                                 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
5872                         }
5873                 } catch (Exception e) {
5874                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5875                         responseWrapper.setInnerElement(responseFormat);
5876                         log.debug("Exception occurred when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
5877                 }
5878                 return nodeTypeArtifactsToHandleRes;
5879         }
5880
5881         ImmutablePair<String, String> buildNestedToscaResourceName(final String nodeResourceType,
5882                                                                                                                            final String vfResourceName,
5883                                                                                                                            final String nodeTypeFullName) {
5884                 String actualType;
5885                 String actualVfName;
5886                 if (ResourceTypeEnum.CVFC.name()
5887                         .equals(nodeResourceType)) {
5888                         actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name();
5889                         actualType = ResourceTypeEnum.VFC.name();
5890                 } else {
5891                         actualVfName = vfResourceName;
5892                         actualType = nodeResourceType;
5893                 }
5894                 String nameWithouNamespacePrefix;
5895                 try {
5896                         final String nodeTypeNamePrefix = getNodeTypeNamePrefix(nodeTypeFullName);
5897                         log.debug("####### buildNestedToscaResourceName nodeResourceType {}, vfResourceName {}, "
5898                                         + "nodeTypeFullName {}, actualType {}, vfResourceName {} ",     nodeResourceType, vfResourceName,
5899                                 nodeTypeFullName, actualType, vfResourceName);
5900                         final StringBuilder toscaResourceName = new StringBuilder(nodeTypeNamePrefix);
5901
5902                         if (!nodeTypeFullName.contains(nodeTypeNamePrefix)) {
5903                                 nameWithouNamespacePrefix = nodeTypeFullName;
5904                         } else {
5905                                 nameWithouNamespacePrefix = nodeTypeFullName.substring(nodeTypeNamePrefix.length());
5906                         }
5907                         final String[] findTypes = nameWithouNamespacePrefix.split("\\.");
5908                         String actualName;
5909                         if (nodeResourceType.equalsIgnoreCase(findTypes[0])){
5910                                 actualName = nameWithouNamespacePrefix.substring(nodeResourceType.length());
5911                         } else {
5912                                 actualName = "." + nameWithouNamespacePrefix;
5913                         }
5914
5915                         if (actualName.startsWith(Constants.ABSTRACT)) {
5916                                 toscaResourceName.append(nodeResourceType.toLowerCase()).append('.')
5917                                         .append(ValidationUtils.convertToSystemName(actualVfName));
5918                         } else {
5919                                 toscaResourceName.append(actualType.toLowerCase()).append('.')
5920                                         .append(ValidationUtils.convertToSystemName(actualVfName)).append('.').append(Constants.ABSTRACT);
5921                         }
5922                         final StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName);
5923                         final String[] actualNames = actualName.split("\\.");
5924                         if (actualNames.length < 3) {
5925                                 return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
5926                                         previousToscaResourceName.append(actualName).toString());
5927                         }
5928                         return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
5929                                 previousToscaResourceName.append(actualName.substring(actualNames[1].length() + 1)
5930                                         .toLowerCase()).toString());
5931                 } catch (final Exception e) {
5932                         log.debug("Exception occured when buildNestedToscaResourceName, error is:{}", e.getMessage(), e);
5933                         throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfResourceName);
5934                 }
5935         }
5936
5937         /**
5938          * Extracts a Node Type Name prefix from the given Node Type Name.
5939          *
5940          * @param fullName Node Type Name
5941          * @return Node Type Name Prefix
5942          */
5943         private String getNodeTypeNamePrefix(final String fullName) {
5944                 String tempPrefix = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX;
5945                 final List<String> definedNodeTypeNamespaceList = getDefinedNodeTypeNamespaceList();
5946                 log.debug("************* getPrefiX fullName {} FROM {}", fullName, definedNodeTypeNamespaceList);
5947                 final Optional<String> validNameSpace = validateNodeTypeNamePrefix(fullName, definedNodeTypeNamespaceList);
5948                 if (validNameSpace.isPresent()) {
5949                         tempPrefix = validNameSpace.get();
5950                 }
5951                 log.debug("************* getNodeTypeNamePrefix return fullName {} ", tempPrefix);
5952                 return tempPrefix;
5953         }
5954
5955         @Override
5956         public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId,
5957                                                                                                                                                                                                    List<String> dataParamsToReturn) {
5958
5959                 ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
5960                 Either<Resource, StorageOperationStatus> resourceResultEither =
5961                                 toscaOperationFacade.getToscaElement(resourceId,
5962                                 paramsToRetuen);
5963
5964                 if (resourceResultEither.isRight()) {
5965                         if (resourceResultEither.right().value() == StorageOperationStatus.NOT_FOUND) {
5966                                 log.debug("Failed to found resource with id {} ", resourceId);
5967                                 Either
5968                                                 .right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
5969                         }
5970
5971                         log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn);
5972                         return Either.right(componentsUtils
5973                                         .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceResultEither.right()
5974                                                         .value()), ""));
5975                 }
5976
5977                 Resource resource = resourceResultEither.left().value();
5978                 if (dataParamsToReturn.contains(ComponentFieldsEnum.INPUTS.getValue())) {
5979                         ListUtils.emptyIfNull(resource.getInputs())
5980                                         .forEach(input -> input.setConstraints(setInputConstraint(input)));
5981                 }
5982
5983                 UiComponentDataTransfer dataTransfer = uiComponentDataConverter.getUiDataTransferFromResourceByParams(resource,
5984                                 dataParamsToReturn);
5985                 return Either.left(dataTransfer);
5986         }
5987
5988         @Override
5989         public Either<Component, ActionStatus> shouldUpgradeToLatestDerived(Component clonedComponent) {
5990                 Resource resource = (Resource) clonedComponent;
5991                 if (ModelConverter.isAtomicComponent(resource.getResourceType())) {
5992                         Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived = toscaOperationFacade
5993                                         .shouldUpgradeToLatestDerived(resource);
5994                         if (shouldUpgradeToLatestDerived.isRight()) {
5995                                 return Either.right(componentsUtils.convertFromStorageResponse(shouldUpgradeToLatestDerived.right()
5996                                                 .value()));
5997                         }
5998                         return Either.left(shouldUpgradeToLatestDerived.left()
5999                                         .value());
6000                 } else {
6001                         return super.shouldUpgradeToLatestDerived(clonedComponent);
6002                 }
6003         }
6004 }