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