Refactor ArtifactsBusinessLogic::handleDelete and ArtifactsBusinessLogic::deleteArtif...
[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<ArtifactDefinition, ResponseFormat> handleDelete = artifactsBusinessLogic
2323                                                 .handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(),
2324                                                         resource, shouldLock,
2325                                                                 inTransaction);
2326                                 if (handleDelete.isRight()) {
2327                                         result = Either.right(handleDelete.right()
2328                                                         .value());
2329                                 } else {
2330                                         ArtifactDefinition value = handleDelete.left().value();
2331                                         String updatedArtifactId = value.getUniqueId();
2332                                         if (artifactGroupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
2333                                                 resource.getDeploymentArtifacts().remove(updatedArtifactId);
2334                                         } else {
2335                                                 resource.getArtifacts().remove(updatedArtifactId);
2336                                         }
2337                                 }
2338                                 return result;
2339                         }
2340
2341                         if (StringUtils.isEmpty(artifactId) && artifactFileBytes != null) {
2342                                 operation = new ArtifactOperationInfo(false, false,
2343                                                 ArtifactOperationEnum.CREATE);
2344                         }
2345
2346                 }
2347                 if (artifactFileBytes != null) {
2348                         Map<String, Object> vendorLicenseModelJson = ArtifactUtils.buildJsonForUpdateArtifact(artifactId,
2349                                         artifactFileName, artifactType, artifactGroupType, artifactLabel, artifactDisplayName,
2350                                         artifactDescription, artifactFileBytes, null, isFromCsar);
2351                         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic
2352                                         .createOrUpdateCsarArtifactFromJson(resource, csarInfo.getModifier(), vendorLicenseModelJson,
2353                                                         operation);
2354                         addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
2355                         if (eitherNonMetaArtifacts.isRight()) {
2356                                 BeEcompErrorManager.getInstance()
2357                                                 .logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: "
2358                                                                                 + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(),
2359                                                                 ErrorSeverity.WARNING);
2360                                 return Either.right(eitherNonMetaArtifacts.right()
2361                                                 .value());
2362                         }
2363                         ArtifactDefinition artifactDefinition = eitherNonMetaArtifacts.left().value().left().value();
2364                         createOrUpdateResourceWithUpdatedArtifact(artifactDefinition,resource, artifactGroupType);
2365                 }
2366
2367                 return result;
2368         }
2369
2370         private void createOrUpdateResourceWithUpdatedArtifact(ArtifactDefinition artifact, Resource resource, ArtifactGroupTypeEnum groupTypeEnum) {
2371                 if (groupTypeEnum == ArtifactGroupTypeEnum.DEPLOYMENT) {
2372                         resource.getDeploymentArtifacts().put(artifact.getArtifactLabel(), artifact);
2373                 } else {
2374                         resource.getArtifacts().put(artifact.getArtifactLabel(), artifact);
2375                 }
2376         }
2377
2378         private boolean isArtifactDeletionRequired(String artifactId, byte[] artifactFileBytes, boolean isFromCsar) {
2379                 return !StringUtils.isEmpty(artifactId) && artifactFileBytes == null && isFromCsar;
2380         }
2381
2382         private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation,
2383                                                                                                                          List<ArtifactDefinition> createdArtifacts,
2384                                                                                                                          Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
2385                 if (operation.isCreateOrLink() && createdArtifacts != null
2386                                 && eitherNonMetaArtifacts.isLeft()) {
2387                         Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left()
2388                                         .value();
2389                         if (eitherResult.isLeft()) {
2390                                 createdArtifacts.add(eitherResult.left()
2391                                                 .value());
2392                         }
2393                 }
2394         }
2395
2396         private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource,
2397                                                                                                                                                         List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
2398                                                                                                                                                         ArtifactOperationInfo artifactOperation) {
2399
2400                 Either<Resource, ResponseFormat> resStatus = null;
2401                 Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
2402
2403                 try {
2404                         Either<List<NonMetaArtifactInfo>, String> artifactPathAndNameList = getValidArtifactNames(csarInfo,
2405                                         collectedWarningMessages);
2406                         if (artifactPathAndNameList.isRight()) {
2407                                 return Either.right(getComponentsUtils().getResponseFormatByArtifactId(
2408                                                 ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right()
2409                                                                 .value()));
2410                         }
2411                         EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
2412
2413                         if (artifactOperation.isCreateOrLink()) {
2414                                 vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
2415                                 vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left()
2416                                                 .value());
2417                         } else {
2418                                 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(
2419                                                 resource, artifactPathAndNameList.left()
2420                                                                 .value(),
2421                                                 csarInfo.getModifier());
2422
2423                                 if (findVfCsarArtifactsToHandleRes.isRight()) {
2424                                         resStatus = Either.right(findVfCsarArtifactsToHandleRes.right()
2425                                                         .value());
2426                                 }
2427                                 if (resStatus == null) {
2428                                         vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left()
2429                                                         .value();
2430                                 }
2431                         }
2432                         if (resStatus == null && vfCsarArtifactsToHandle != null) {
2433                                 resStatus = processCsarArtifacts(csarInfo, resource, createdArtifacts, shouldLock, inTransaction,
2434                                                 resStatus, vfCsarArtifactsToHandle);
2435                         }
2436                         if (resStatus == null) {
2437                                 resStatus = Either.left(resource);
2438                         }
2439                 } catch (Exception e) {
2440                         resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2441                         log.debug("Exception occurred in createNonMetaArtifacts, message:{}", e.getMessage(), e);
2442                 } finally {
2443                         CsarUtils.handleWarningMessages(collectedWarningMessages);
2444                 }
2445                 return resStatus;
2446         }
2447
2448         private Either<Resource, ResponseFormat> processCsarArtifacts(CsarInfo csarInfo, Resource resource,
2449                                                                                                                                   List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
2450                                                                                                                                   Either<Resource, ResponseFormat> resStatus,
2451                                                                                                                                   EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle) {
2452                 for (Entry<ArtifactOperationEnum, List<NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle
2453                                 .entrySet()) {
2454
2455                         Optional<ResponseFormat> optionalCreateInDBError =
2456                                         // Stream of artifacts to be created
2457                                         currArtifactOperationPair.getValue()
2458                                                         .stream()
2459                                                         // create each artifact
2460                                                         .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(),
2461                                                                         e.getArtifactName(), e.getArtifactType(),
2462                                                                         e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
2463                                                                         CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(),
2464                                                                         new ArtifactOperationInfo(false, false,
2465                                                                                         currArtifactOperationPair.getKey()),
2466                                                                         createdArtifacts, e.isFromCsar(), shouldLock, inTransaction))
2467                                                         // filter in only error
2468                                                         .filter(Either::isRight)
2469                                                         .
2470                                                         // Convert the error from either to
2471                                                         // ResponseFormat
2472                                                                         map(e -> e.right()
2473                                                                         .value())
2474                                                         .
2475                                                         // Check if an error occurred
2476                                                                         findAny();
2477                         // Error found on artifact Creation
2478                         if (optionalCreateInDBError.isPresent()) {
2479                                 resStatus = Either.right(optionalCreateInDBError.get());
2480                                 break;
2481                         }
2482                 }
2483                 return resStatus;
2484         }
2485
2486         private Either<List<NonMetaArtifactInfo>, String> getValidArtifactNames(CsarInfo csarInfo,
2487                                                                                                                                                         Map<String, Set<List<String>>> collectedWarningMessages) {
2488                 List<NonMetaArtifactInfo> artifactPathAndNameList =
2489                                 // Stream of file paths contained in csar
2490                                 csarInfo.getCsar()
2491                                                 .entrySet()
2492                                                 .stream()
2493                                                 // Filter in only VF artifact path location
2494                                                 .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN)
2495                                                                 .matcher(e.getKey())
2496                                                                 .matches())
2497                                                 // Validate and add warnings
2498                                                 .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), collectedWarningMessages))
2499                                                 // Filter in Non Warnings
2500                                                 .filter(Either::isLeft)
2501                                                 // Convert from Either to NonMetaArtifactInfo
2502                                                 .map(e -> e.left()
2503                                                                 .value())
2504                                                 // collect to List
2505                                                 .collect(toList());
2506                 Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
2507                 for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
2508                         if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName())
2509                                         .matches()) {
2510                                 return Either.right(nonMetaArtifactInfo.getArtifactName());
2511                         }
2512                 }
2513                 return Either.left(artifactPathAndNameList);
2514         }
2515
2516         private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(
2517                         Resource resource, List<NonMetaArtifactInfo> artifactPathAndNameList, User user) {
2518
2519                 List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
2520                 // collect all Deployment and Informational artifacts of VF
2521                 if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts()
2522                                 .isEmpty()) {
2523                         existingArtifacts.addAll(resource.getDeploymentArtifacts()
2524                                         .values());
2525                 }
2526                 if (resource.getArtifacts() != null && !resource.getArtifacts()
2527                                 .isEmpty()) {
2528                         existingArtifacts.addAll(resource.getArtifacts()
2529                                         .values());
2530                 }
2531                 existingArtifacts = existingArtifacts.stream()
2532                                 // filter MANDATORY artifacts, LICENSE artifacts and artifacts
2533                                 // was created from HEAT.meta
2534                                 .filter(this::isNonMetaArtifact)
2535                                 .collect(toList());
2536
2537                 List<String> artifactsToIgnore = new ArrayList<>();
2538                 // collect IDs of Artifacts of VF which belongs to any group
2539                 if (resource.getGroups() != null) {
2540                         resource.getGroups()
2541                                         .stream()
2542                                         .forEach(g -> {
2543                                                 if (g.getArtifacts() != null && !g.getArtifacts()
2544                                                                 .isEmpty()) {
2545                                                         artifactsToIgnore.addAll(g.getArtifacts());
2546                                                 }
2547                                         });
2548                 }
2549                 existingArtifacts = existingArtifacts.stream()
2550                                 // filter artifacts which belongs to any group
2551                                 .filter(a -> !artifactsToIgnore.contains(a.getUniqueId()))
2552                                 .collect(toList());
2553                 return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user);
2554         }
2555
2556         private boolean isNonMetaArtifact(ArtifactDefinition artifact) {
2557                 boolean result = true;
2558                 if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) {
2559                         result = false;
2560                 }
2561                 return result;
2562         }
2563
2564         private boolean isValidArtifactType(ArtifactDefinition artifact) {
2565                 boolean result = true;
2566                 if (artifact.getArtifactType() == null
2567                                 || ArtifactTypeEnum.parse(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE
2568                                 || ArtifactTypeEnum.parse(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) {
2569                         result = false;
2570                 }
2571                 return result;
2572         }
2573
2574         private Resource createResourceInstancesRelations(User user, String yamlName, Resource resource, Resource oldResource,
2575                                                                                                           Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, Map<String, Resource> existingNodeTypesByResourceNames) {
2576                 log.debug("#createResourceInstancesRelations - Going to create relations ");
2577                 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),     StatusCode.STARTED,"Start to create relations");
2578                 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
2579                 if (isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)  &&
2580                 resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances {
2581                         log.debug(
2582                                         "#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ",
2583                                         resource.getUniqueId(), yamlName);
2584                         loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),     StatusCode.ERROR,"No instances found in the resource: {}, is empty, yaml template file name: {}",resource.getName(),yamlName);
2585                         BeEcompErrorManager.getInstance()
2586                                         .logInternalDataError("createResourceInstancesRelations",
2587                                                         "No instances found in a resource or nn yaml template. ", ErrorSeverity.ERROR);
2588                         throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2589                 }
2590                 Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
2591                 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
2592                 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
2593                 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
2594                 Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
2595                 Map<String, List<PropertyDefinition>> instAttributes = new HashMap<>();
2596                 List<RequirementCapabilityRelDef> relations = new ArrayList<>();
2597                 Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
2598
2599                 log.debug("#createResourceInstancesRelations - Before get all datatypes. ");
2600         Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll();
2601                 if (allDataTypes.isRight()) {
2602                         JanusGraphOperationStatus status = allDataTypes.right()
2603                                         .value();
2604                         BeEcompErrorManager.getInstance()
2605                                         .logInternalFlowError("UpdatePropertyValueOnComponentInstance",
2606                                                         "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
2607                         loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),
2608                                         StatusCode.ERROR,"ERROR while update property value on instance. Status is: "+status);
2609                         throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(
2610                                         DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)), yamlName);
2611
2612                 }
2613                 Resource finalResource = resource;
2614                 uploadResInstancesMap.values()
2615                                 .forEach(i -> processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes,
2616                                                 instProperties, instCapabilities, instRequirements, instDeploymentArtifacts, instArtifacts,
2617                                                 instAttributes, existingNodeTypesByResourceNames, instInputs, i));
2618                 resource.getComponentInstances()
2619                                 .stream()
2620                                 .filter(i -> !i.isCreatedFromCsar())
2621                                 .forEach(i->processUiComponentInstance(oldResource, i, instCapabilities, instRequirements, instDeploymentArtifacts, instArtifacts, instProperties, instInputs, instAttributes));
2622
2623                 associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties);
2624                 associateComponentInstanceInputsToComponent(yamlName, resource, instInputs);
2625                 associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts);
2626                 associateArtifactsToInstances(yamlName, resource, instArtifacts);
2627                 associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements);
2628                 associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes);
2629                 addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations);
2630                 associateResourceInstances(yamlName, resource, relations);
2631                 handleSubstitutionMappings(resource, uploadResInstancesMap);
2632                 log.debug("************* in create relations, getResource start");
2633                 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),     StatusCode.COMPLETE,"create relations");
2634                 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
2635                                 .getToscaFullElement(resource.getUniqueId());
2636                 log.debug("************* in create relations, getResource end");
2637                 if (eitherGetResource.isRight()) {
2638                         loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),
2639                                         StatusCode.ERROR,"ERROR while create relations");
2640                         throw new ByResponseFormatComponentException(componentsUtils
2641                                         .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right()
2642                                                         .value()), resource));
2643                 }
2644                 return eitherGetResource.left()
2645                                 .value();
2646         }
2647
2648         private void processUiComponentInstance(Resource oldResource, ComponentInstance instance,
2649                                                                                         Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
2650                                                                                         Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements,
2651                                                                                         Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
2652                                                                                         Map<String, Map<String, ArtifactDefinition>> instArtifacts, Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, List<ComponentInstanceInput>> instInputs, Map<String, List<PropertyDefinition>> instAttributes) {
2653                 Optional<ComponentInstance> foundInstance = findInstance(oldResource, instance);
2654                 if(foundInstance.isPresent()){
2655                         if(MapUtils.isNotEmpty(foundInstance.get().getCapabilities())){
2656                                 instCapabilities.put(instance, foundInstance.get().getCapabilities());
2657                         }
2658                         if(MapUtils.isNotEmpty(foundInstance.get().getRequirements())){
2659                                 instRequirements.put(instance, foundInstance.get().getRequirements());
2660                         }
2661                         if(MapUtils.isNotEmpty(foundInstance.get().getDeploymentArtifacts())){
2662                                 instDeploymentArtifacts.put(instance.getUniqueId(), foundInstance.get().getDeploymentArtifacts());
2663                         }
2664                         if(MapUtils.isNotEmpty(foundInstance.get().getArtifacts())){
2665                                 instArtifacts.put(instance.getUniqueId(), foundInstance.get().getArtifacts());
2666                         }
2667                         if(MapUtils.isNotEmpty(oldResource.getComponentInstancesProperties()) &&
2668                                         CollectionUtils.isNotEmpty(oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId()))){
2669                                 instProperties.put(instance.getUniqueId(), oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId()));
2670                         }
2671                         if(MapUtils.isNotEmpty(oldResource.getComponentInstancesInputs()) &&
2672                                         CollectionUtils.isNotEmpty(oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId()))){
2673                                 instInputs.put(instance.getUniqueId(), oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId()));
2674                         }
2675                         if(MapUtils.isNotEmpty(oldResource.getComponentInstancesAttributes()) &&
2676                                         CollectionUtils.isNotEmpty(oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()))){
2677                                 instAttributes.put(instance.getUniqueId(), oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()).stream().map(PropertyDefinition::new).collect(toList()));
2678                         }
2679                 }
2680         }
2681
2682         private Optional<ComponentInstance> findInstance(Resource oldResource, ComponentInstance instance) {
2683                 if(oldResource != null && CollectionUtils.isNotEmpty(oldResource.getComponentInstances())) {
2684                         return oldResource.getComponentInstances().stream().filter(i -> i.getName().equals(instance.getName())).findFirst();
2685                 }
2686                 return Optional.empty();
2687         }
2688
2689         private void associateResourceInstances(String yamlName, Resource resource,
2690                                                                                         List<RequirementCapabilityRelDef> relations) {
2691                 Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> relationsEither = toscaOperationFacade.associateResourceInstances(resource, resource.getUniqueId(), relations);
2692
2693                 if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) {
2694                         StorageOperationStatus status = relationsEither.right().value();
2695                         log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(),
2696                                         status);
2697                         throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), yamlName);
2698                 } else {
2699                         setResourceInstanceRelationsOnComponent(resource, relationsEither.left().value());
2700                 }
2701         }
2702
2703         private void associateInstAttributeToComponentToInstances(String yamlName, Resource resource,
2704                                                                                                                           Map<String, List<PropertyDefinition>> instAttributes) {
2705                 StorageOperationStatus addArtToInst;
2706                 addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes,
2707                                 resource);
2708                 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2709                         log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
2710                                         addArtToInst);
2711                         throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
2712                 }
2713         }
2714
2715         private void associateOrAddCalculatedCapReq(String yamlName, Resource resource,
2716                                                                                                 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
2717                                                                                                 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
2718                 StorageOperationStatus addArtToInst;
2719                 addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements,
2720                                 resource);
2721                 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2722                         log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(),
2723                                         addArtToInst);
2724                         throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
2725                 }
2726         }
2727
2728         private void associateArtifactsToInstances(String yamlName, Resource resource,
2729                                                                                            Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
2730                 StorageOperationStatus addArtToInst;
2731
2732                 addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource);
2733                 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2734                         log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2735                         throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
2736                 }
2737         }
2738
2739         private void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource,
2740                                                                                                                  Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
2741                 StorageOperationStatus addArtToInst = toscaOperationFacade
2742                                 .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user);
2743                 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2744                         log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2745                         throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
2746                 }
2747         }
2748
2749         private void associateComponentInstanceInputsToComponent(String yamlName, Resource resource,
2750                                                                                                                          Map<String, List<ComponentInstanceInput>> instInputs) {
2751                 if (MapUtils.isNotEmpty(instInputs)) {
2752                         Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
2753                                         .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
2754                         if (addInputToInst.isRight()) {
2755
2756                                 StorageOperationStatus addInputToInstError = addInputToInst.right().value();
2757                                 log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(),
2758                                                 addInputToInstError);
2759                                 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addInputToInstError), yamlName);
2760                         }
2761                         setComponentInstanceInputsOnComponent(resource, instInputs);
2762                 }
2763         }
2764
2765         private void setComponentInstanceInputsOnComponent(Resource resource, Map<String, List<ComponentInstanceInput>> instInputs) {
2766                 Map<String, List<ComponentInstanceInput>> componentInstancesInputs = resource.getComponentInstancesInputs();
2767                 if (componentInstancesInputs == null)
2768                         componentInstancesInputs = new HashMap<>();
2769                 componentInstancesInputs.putAll(instInputs);
2770                 resource.setComponentInstancesInputs(componentInstancesInputs);
2771         }
2772
2773         private void associateComponentInstancePropertiesToComponent(String yamlName, Resource resource,
2774                                                                                                                                  Map<String, List<ComponentInstanceProperty>> instProperties) {
2775                 Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
2776                                 .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
2777                 if (addPropToInst.isRight()) {
2778                         loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),
2779                                         StatusCode.ERROR,"ERROR while  associate compnent insatnce properties of resource: {} status is: {}",resource.getName(),addPropToInst.right().value());
2780                         StorageOperationStatus storageOperationStatus = addPropToInst.right().value();
2781                         log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(),
2782                                         storageOperationStatus);
2783                         throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageOperationStatus), yamlName);
2784                 }
2785                 setComponentInstancePropertiesOnComponent(resource, instProperties);
2786         }
2787
2788         private void setComponentInstancePropertiesOnComponent(Resource resource, Map<String, List<ComponentInstanceProperty>> instProperties) {
2789                 Map<String, List<ComponentInstanceProperty>> componentInstanceProps = resource.getComponentInstancesProperties();
2790                 if (componentInstanceProps == null )
2791                         componentInstanceProps = new HashMap<>();
2792                 componentInstanceProps.putAll(instProperties);
2793                 resource.setComponentInstancesProperties(componentInstanceProps);
2794         }
2795
2796         private void handleSubstitutionMappings(Resource resource,
2797                                                                                         Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2798                 if (resource.getResourceType() == ResourceTypeEnum.CVFC) {
2799                         Either<Resource, StorageOperationStatus> getResourceRes =
2800                                         updateCalculatedCapReqWithSubstitutionMappings(resource, uploadResInstancesMap);
2801                         if (getResourceRes.isRight()) {
2802                                 ResponseFormat responseFormat = componentsUtils
2803                                                 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResourceRes.right()
2804                                                                 .value()), resource);
2805                                 throw new ByResponseFormatComponentException(responseFormat);
2806                         }
2807                 }
2808         }
2809
2810         private void addRelationsToRI(String yamlName, Resource resource,
2811                                                                   Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2812                                                                   List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) {
2813                 for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
2814                         UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
2815                         ComponentInstance currentCompInstance = null;
2816                         for (ComponentInstance compInstance : componentInstancesList) {
2817
2818                                 if (compInstance.getName()
2819                                                 .equals(uploadComponentInstanceInfo.getName())) {
2820                                         currentCompInstance = compInstance;
2821                                         break;
2822                                 }
2823
2824                         }
2825                         if (currentCompInstance == null) {
2826                                 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
2827                                                 resource.getUniqueId());
2828                                 BeEcompErrorManager.getInstance()
2829                                                 .logInternalDataError(
2830                                                                 COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
2831                                                                 resource.getUniqueId(), ErrorSeverity.ERROR);
2832                                 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2833                         }
2834
2835                         ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
2836                         if (addRelationToRiRes.getStatus() != 200) {
2837                                 throw new ByResponseFormatComponentException(addRelationToRiRes);
2838                         }
2839                 }
2840
2841         }
2842
2843         private void setResourceInstanceRelationsOnComponent(Resource resource, List<RequirementCapabilityRelDef> relations) {
2844                 if (resource.getComponentInstancesRelations() != null) {
2845                         resource.getComponentInstancesRelations().addAll(relations);
2846                 } else {
2847                         resource.setComponentInstancesRelations(relations);
2848                 }
2849         }
2850
2851         private void processComponentInstance(String yamlName, Resource resource,
2852                                                                                   List<ComponentInstance> componentInstancesList,
2853                                                                                   Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
2854                                                                                   Map<String, List<ComponentInstanceProperty>> instProperties,
2855                                                                                   Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
2856                                                                                   Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements,
2857                                                                                   Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
2858                                                                                   Map<String, Map<String, ArtifactDefinition>> instArtifacts,
2859                                                                                   Map<String, List<PropertyDefinition>> instAttributes, Map<String, Resource> originCompMap,
2860                                                                                   Map<String, List<ComponentInstanceInput>> instInputs,
2861                                                                                   UploadComponentInstanceInfo uploadComponentInstanceInfo) {
2862                 Optional<ComponentInstance> currentCompInstanceOpt = componentInstancesList.stream()
2863                                 .filter(i -> i.getName()
2864                                                 .equals(uploadComponentInstanceInfo.getName()))
2865                                 .findFirst();
2866                 if (!currentCompInstanceOpt.isPresent()) {
2867                         log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
2868                                         resource.getUniqueId());
2869                         BeEcompErrorManager.getInstance()
2870                                         .logInternalDataError(
2871                                                         COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
2872                                                         resource.getUniqueId(), ErrorSeverity.ERROR);
2873                         throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2874                 }
2875                 ComponentInstance currentCompInstance = currentCompInstanceOpt.get();
2876                 String resourceInstanceId = currentCompInstance.getUniqueId();
2877                 Resource originResource = getOriginResource(originCompMap, currentCompInstance);
2878                 if (isNotEmpty(originResource.getRequirements())) {
2879                         instRequirements.put(currentCompInstance, originResource.getRequirements());
2880                 }
2881                 if (isNotEmpty(originResource.getCapabilities())) {
2882                         processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo,
2883                                         currentCompInstance, originResource);
2884                 }
2885                 if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts()
2886                                 .isEmpty()) {
2887                         instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
2888                 }
2889                 if (originResource.getArtifacts() != null && !originResource.getArtifacts()
2890                                 .isEmpty()) {
2891                         instArtifacts.put(resourceInstanceId, originResource.getArtifacts());
2892                 }
2893                 if (originResource.getAttributes() != null && !originResource.getAttributes()
2894                                 .isEmpty()) {
2895                         instAttributes.put(resourceInstanceId, originResource.getAttributes());
2896                 }
2897                 if (originResource.getResourceType() != ResourceTypeEnum.CVFC) {
2898                         ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource,
2899                                         originResource, currentCompInstance, instProperties, allDataTypes.left()
2900                                                         .value());
2901                         if (addPropertiesValueToRiRes.getStatus() != 200) {
2902                                 throw new ByResponseFormatComponentException(addPropertiesValueToRiRes);
2903                         }
2904                 } else {
2905                         addInputsValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, instInputs,
2906                                         allDataTypes.left()
2907                                                         .value());
2908                 }
2909         }
2910
2911         private Resource getOriginResource(Map<String, Resource> originCompMap, ComponentInstance currentCompInstance) {
2912                 Resource originResource;
2913                 if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
2914                         Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade
2915                                         .getToscaFullElement(currentCompInstance.getComponentUid());
2916                         if (getOriginResourceRes.isRight()) {
2917                                 log.debug("failed to fetch resource with uniqueId {} and tosca component name {} status is {}",
2918                                                 currentCompInstance.getComponentUid(), currentCompInstance.getToscaComponentName(),
2919                                                 getOriginResourceRes);
2920                                 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getOriginResourceRes.right()
2921                                                 .value()), currentCompInstance.getComponentUid());
2922                         }
2923                         originResource = getOriginResourceRes.left()
2924                                         .value();
2925                         originCompMap.put(originResource.getUniqueId(), originResource);
2926                 } else {
2927                         originResource = originCompMap.get(currentCompInstance.getComponentUid());
2928                 }
2929                 return originResource;
2930         }
2931
2932         private void processComponentInstanceCapabilities(
2933                         Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
2934                         Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
2935                         UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance,
2936                         Resource originResource) {
2937                 Map<String, List<CapabilityDefinition>> originCapabilities;
2938                 if (isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) {
2939                         originCapabilities = new HashMap<>();
2940                         Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>();
2941                         originResource.getCapabilities()
2942                                         .forEach((k, v) -> addCapabilities(originCapabilities, k, v));
2943                         uploadComponentInstanceInfo.getCapabilities()
2944                                         .values()
2945                                         .forEach(l -> addCapabilitiesProperties(newPropertiesMap, l));
2946                         updateCapabilityPropertiesValues(allDataTypes, originCapabilities, newPropertiesMap);
2947                 } else {
2948                         originCapabilities = originResource.getCapabilities();
2949                 }
2950                 instCapabilties.put(currentCompInstance, originCapabilities);
2951         }
2952
2953         private void updateCapabilityPropertiesValues(
2954                         Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
2955                         Map<String, List<CapabilityDefinition>> originCapabilities,
2956                         Map<String, Map<String, UploadPropInfo>> newPropertiesMap) {
2957                 originCapabilities.values()
2958                                 .stream()
2959                                 .flatMap(Collection::stream)
2960                                 .filter(c -> newPropertiesMap.containsKey(c.getName()))
2961                                 .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()),
2962                                                 allDataTypes.left()
2963                                                                 .value()));
2964         }
2965
2966         private void addCapabilitiesProperties(Map<String, Map<String, UploadPropInfo>> newPropertiesMap,
2967                                                                                    List<UploadCapInfo> capabilities) {
2968                 for (UploadCapInfo capability : capabilities) {
2969                         if (isNotEmpty(capability.getProperties())) {
2970                                 newPropertiesMap.put(capability.getName(), capability.getProperties()
2971                                                 .stream()
2972                                                 .collect(toMap(UploadInfo::getName, p -> p)));
2973                         }
2974                 }
2975         }
2976
2977         private void addCapabilities(Map<String, List<CapabilityDefinition>> originCapabilities, String type,
2978                                                                  List<CapabilityDefinition> capabilities) {
2979                 List<CapabilityDefinition> list = capabilities.stream()
2980                                 .map(CapabilityDefinition::new)
2981                                 .collect(toList());
2982                 originCapabilities.put(type, list);
2983         }
2984
2985         private void updatePropertyValues(List<ComponentInstanceProperty> properties,
2986                                                                           Map<String, UploadPropInfo> newProperties, Map<String, DataTypeDefinition> allDataTypes) {
2987                 properties.forEach(p -> updatePropertyValue(p, newProperties.get(p.getName()), allDataTypes));
2988         }
2989
2990         private String updatePropertyValue(ComponentInstanceProperty property, UploadPropInfo propertyInfo,
2991                                                                            Map<String, DataTypeDefinition> allDataTypes) {
2992                 String value = null;
2993                 List<GetInputValueDataDefinition> getInputs = null;
2994                 boolean isValidate = true;
2995                 if (null != propertyInfo && propertyInfo.getValue() != null) {
2996                         getInputs = propertyInfo.getGet_input();
2997                         isValidate = getInputs == null || getInputs.isEmpty();
2998                         if (isValidate) {
2999                                 value = getPropertyJsonStringValue(propertyInfo.getValue(), property.getType());
3000                         } else {
3001                                 value = getPropertyJsonStringValue(propertyInfo.getValue(),
3002                                                 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
3003                         }
3004                 }
3005                 property.setValue(value);
3006         return validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
3007         }
3008
3009         private Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource,
3010                                                                                                                                                                                                         Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
3011                 Either<Resource, StorageOperationStatus> updateRes = null;
3012                 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>();
3013                 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>();
3014                 StorageOperationStatus status = toscaOperationFacade
3015                                 .deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId());
3016                 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
3017                         log.debug(
3018                                         "Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}",
3019                                         resource.getUniqueId(), status);
3020                         updateRes = Either.right(status);
3021                 }
3022                 if (updateRes == null) {
3023                         fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap,
3024                                         updatedInstCapabilities, updatedInstRequirements);
3025                         status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities,
3026                                         updatedInstRequirements, resource);
3027                         if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
3028                                 log.debug(
3029                                                 "Failed to associate capabilities and requirementss of resource {}, updated according to a substitution mapping. Status is {}",
3030                                                 resource.getUniqueId(), status);
3031                                 updateRes = Either.right(status);
3032                         }
3033                 }
3034                 if (updateRes == null) {
3035                         updateRes = Either.left(resource);
3036                 }
3037                 return updateRes;
3038         }
3039
3040         private void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances,
3041                                                                                                                  Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
3042                                                                                                                  Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities,
3043                                                                                                                  Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) {
3044
3045                 componentInstances.stream()
3046                                 .forEach(i -> {
3047                                         fillUpdatedInstCapabilities(updatedInstCapabilities, i, uploadResInstancesMap.get(i.getName())
3048                                                         .getCapabilitiesNamesToUpdate());
3049                                         fillUpdatedInstRequirements(updatedInstRequirements, i, uploadResInstancesMap.get(i.getName())
3050                                                         .getRequirementsNamesToUpdate());
3051                                 });
3052         }
3053
3054         private void fillUpdatedInstRequirements(
3055                         Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements,
3056                         ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
3057                 Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
3058                 Set<String> updatedReqNames = new HashSet<>();
3059                 if (isNotEmpty(requirementsNamesToUpdate)) {
3060                         for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements()
3061                                         .entrySet()) {
3062                                 updatedRequirements.put(requirements.getKey(), requirements.getValue()
3063                                                 .stream()
3064                                                 .filter(r -> requirementsNamesToUpdate.containsKey(r.getName())
3065                                                                 && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
3066                                                 .map(r -> {
3067                                                         r.setParentName(r.getName());
3068                                                         r.setName(requirementsNamesToUpdate.get(r.getName()));
3069                                                         updatedReqNames.add(r.getName());
3070                                                         return r;
3071                                                 })
3072                                                 .collect(toList()));
3073                         }
3074                 }
3075                 if (isNotEmpty(updatedRequirements)) {
3076                         updatedInstRequirements.put(instance, updatedRequirements);
3077                 }
3078         }
3079
3080         private void fillUpdatedInstCapabilities(
3081                         Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties,
3082                         ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
3083                 Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
3084                 Set<String> updatedCapNames = new HashSet<>();
3085                 if (isNotEmpty(capabilitiesNamesToUpdate)) {
3086                         for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities()
3087                                         .entrySet()) {
3088                                 updatedCapabilities.put(requirements.getKey(), requirements.getValue()
3089                                                 .stream()
3090                                                 .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName())
3091                                                                 && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
3092                                                 .map(c -> {
3093                                                         c.setParentName(c.getName());
3094                                                         c.setName(capabilitiesNamesToUpdate.get(c.getName()));
3095                                                         updatedCapNames.add(c.getName());
3096                                                         return c;
3097                                                 })
3098                                                 .collect(toList()));
3099                         }
3100                 }
3101                 if (isNotEmpty(updatedCapabilities)) {
3102                         updatedInstCapabilties.put(instance, updatedCapabilities);
3103                 }
3104         }
3105
3106         private ResponseFormat addRelationToRI(String yamlName, Resource resource,
3107                                                                                    UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
3108                 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
3109
3110                 ComponentInstance currentCompInstance = null;
3111
3112                 for (ComponentInstance compInstance : componentInstancesList) {
3113
3114                         if (compInstance.getName()
3115                                         .equals(nodesInfoValue.getName())) {
3116                                 currentCompInstance = compInstance;
3117                                 break;
3118                         }
3119
3120                 }
3121
3122                 if (currentCompInstance == null) {
3123                         log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), resource.getUniqueId());
3124                         BeEcompErrorManager.getInstance()
3125                                         .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE,
3126                                                         resource.getUniqueId(), ErrorSeverity.ERROR);
3127                         return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3128                 }
3129                 String resourceInstanceId = currentCompInstance.getUniqueId();
3130
3131                 Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
3132
3133                 if (regMap != null) {
3134                         Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet()
3135                                         .iterator();
3136
3137                         while (nodesRegValue.hasNext()) {
3138                                 Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
3139
3140                                 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
3141                                 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
3142                                         log.debug("Going to create  relation {}", uploadRegInfo.getName());
3143                                         loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),     StatusCode.STARTED,"Started to create relations on instance: {}",uploadRegInfo.getName());
3144                                         String regName = uploadRegInfo.getName();
3145                                         RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
3146                                         regCapRelDef.setFromNode(resourceInstanceId);
3147                                         log.debug("try to find available requirement {} ", regName);
3148                                         Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName,
3149                                                         yamlName, nodesInfoValue, currentCompInstance, uploadRegInfo.getCapabilityName());
3150                                         if (eitherReqStatus.isRight()) {
3151                                                 log.debug("failed to find available requirement {} status is {}", regName,
3152                                                                 eitherReqStatus.right()
3153                                                                                 .value());
3154                                                 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),     StatusCode.ERROR,"ERROR while search available requirement {} status is: {}",regName,eitherReqStatus.right().value());
3155                                                 return eitherReqStatus.right()
3156                                                                 .value();
3157                                         }
3158
3159                                         RequirementDefinition validReq = eitherReqStatus.left()
3160                                                         .value();
3161                                         List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef
3162                                                         .getRelationships();
3163                                         if (reqAndRelationshipPairList == null) {
3164                                                 reqAndRelationshipPairList = new ArrayList<>();
3165                                         }
3166                                         RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
3167                                         reqAndRelationshipPair.setRequirement(regName);
3168                                         reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
3169                                         reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
3170                                         RelationshipImpl relationship = new RelationshipImpl();
3171                                         relationship.setType(validReq.getCapability());
3172                                         reqAndRelationshipPair.setRelationships(relationship);
3173
3174                                         ComponentInstance currentCapCompInstance = null;
3175                                         for (ComponentInstance compInstance : componentInstancesList) {
3176                                                 if (compInstance.getName()
3177                                                                 .equals(uploadRegInfo.getNode())) {
3178                                                         currentCapCompInstance = compInstance;
3179                                                         break;
3180                                                 }
3181                                         }
3182
3183                                         if (currentCapCompInstance == null) {
3184                                                 log.debug("The component instance  with name {} not found on resource {} ",
3185                                                                 uploadRegInfo.getNode(), resource.getUniqueId());
3186                                                 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR component instance  with name: {} not found on resource: {}",uploadRegInfo.getNode(),resource.getUniqueId());
3187                                                 BeEcompErrorManager.getInstance()
3188                                                                 .logInternalDataError(
3189                                                                                 COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE,
3190                                                                                 resource.getUniqueId(), ErrorSeverity.ERROR);
3191                                                 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3192                                         }
3193                                         regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
3194                                         log.debug("try to find aviable Capability  req name is {} ", validReq.getName());
3195                                         CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq,
3196                                                         currentCapCompInstance, uploadRegInfo);
3197
3198                                         if (aviableCapForRel == null) {
3199                                                 log.debug("aviable capability was not found. req name is {} component instance is {}",
3200                                                                 validReq.getName(), currentCapCompInstance.getUniqueId());
3201                                                 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());
3202                                                 BeEcompErrorManager.getInstance()
3203                                                                 .logInternalDataError(
3204                                                                                 "aviable capability was not found. req name is " + validReq.getName()
3205                                                                                                 + " component instance is " + currentCapCompInstance.getUniqueId(),
3206                                                                                 resource.getUniqueId(), ErrorSeverity.ERROR);
3207                                                 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3208                                         }
3209                                         reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
3210                                         reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
3211                                         reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
3212
3213                                         CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
3214                                         capReqRel.setRelation(reqAndRelationshipPair);
3215                                         reqAndRelationshipPairList.add(capReqRel);
3216                                         regCapRelDef.setRelationships(reqAndRelationshipPairList);
3217                                         relations.add(regCapRelDef);
3218                                 }
3219                         }
3220                 } else if (resource.getResourceType() != ResourceTypeEnum.CVFC) {
3221                         return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
3222                 }
3223                 return componentsUtils.getResponseFormat(ActionStatus.OK);
3224         }
3225
3226         private void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource,
3227                                                                          Resource originResource, ComponentInstance currentCompInstance,
3228                                                                          Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) {
3229                 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
3230                 if (MapUtils.isNotEmpty(propMap)) {
3231                         Map<String, InputDefinition> currPropertiesMap = new HashMap<>();
3232                         List<ComponentInstanceInput> instPropList = new ArrayList<>();
3233
3234                         if (CollectionUtils.isEmpty(originResource.getInputs())) {
3235                                 log.debug("failed to find properties ");
3236                                 loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,resource.getComponentMetadataForSupportLog(),StatusCode.ERROR,"ERROR while try to find properties");
3237                                 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND);
3238                         }
3239                         originResource.getInputs()
3240                                         .forEach(p -> addInput(currPropertiesMap, p));
3241                         for (List<UploadPropInfo> propertyList : propMap.values()) {
3242                                 processProperty(resource, currentCompInstance, allDataTypes, currPropertiesMap, instPropList,
3243                                                 propertyList);
3244                         }
3245                         currPropertiesMap.values()
3246                                         .forEach(p -> instPropList.add(new ComponentInstanceInput(p)));
3247                         instInputs.put(currentCompInstance.getUniqueId(), instPropList);
3248                 }
3249         }
3250
3251         private void processProperty(Resource resource, ComponentInstance currentCompInstance,
3252                                                                  Map<String, DataTypeDefinition> allDataTypes, Map<String, InputDefinition> currPropertiesMap,
3253                                                                  List<ComponentInstanceInput> instPropList, List<UploadPropInfo> propertyList) {
3254                 UploadPropInfo propertyInfo = propertyList.get(0);
3255                 String propName = propertyInfo.getName();
3256                 if (!currPropertiesMap.containsKey(propName)) {
3257                         loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
3258                                         StatusCode.ERROR,"ERROR failed to find property: {}",propName);
3259                         log.debug("failed to find property {} ", propName);
3260                         throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, propName);
3261                 }
3262                 InputDefinition curPropertyDef = currPropertiesMap.get(propName);
3263                 ComponentInstanceInput property = null;
3264
3265                 String value = null;
3266                 List<GetInputValueDataDefinition> getInputs = null;
3267                 boolean isValidate = true;
3268                 if (propertyInfo.getValue() != null) {
3269                         getInputs = propertyInfo.getGet_input();
3270                         isValidate = getInputs == null || getInputs.isEmpty();
3271                         if (isValidate) {
3272                                 value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
3273                         } else {
3274                                 value = getPropertyJsonStringValue(propertyInfo.getValue(),
3275                                                 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
3276                         }
3277                 }
3278                 String innerType = null;
3279                 property = new ComponentInstanceInput(curPropertyDef, value, null);
3280
3281         String validPropertyVAlue = validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
3282
3283                 property.setValue(validPropertyVAlue);
3284
3285                 if (isNotEmpty(getInputs)) {
3286                         List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
3287                         for (GetInputValueDataDefinition getInput : getInputs) {
3288                                 List<InputDefinition> inputs = resource.getInputs();
3289                                 if (CollectionUtils.isEmpty(inputs)) {
3290                                         loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
3291                                                         StatusCode.ERROR,"ERROR Failed to add property: "+propName+" to resource instance: {}. Inputs list is empty ",currentCompInstance.getUniqueId());
3292                                         log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property,
3293                                                         currentCompInstance.getUniqueId());
3294                                         throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
3295                                 }
3296
3297                                 Optional<InputDefinition> optional = inputs.stream()
3298                                                 .filter(p -> p.getName()
3299                                                                 .equals(getInput.getInputName()))
3300                                                 .findAny();
3301                                 if (!optional.isPresent()) {
3302                                         loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
3303                                                         StatusCode.ERROR,"ERROR Failed to find input: "+getInput.getInputName());
3304                                         log.debug("Failed to find input {} ", getInput.getInputName());
3305                                         // @@TODO error message
3306                                         throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
3307                                 }
3308                                 InputDefinition input = optional.get();
3309                                 getInput.setInputId(input.getUniqueId());
3310                                 getInputValues.add(getInput);
3311
3312                                 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
3313                                 processGetInput(getInputValues, inputs, getInputIndex);
3314                         }
3315                         property.setGetInputValues(getInputValues);
3316                 }
3317                 instPropList.add(property);
3318                 // delete overriden property
3319                 currPropertiesMap.remove(property.getName());
3320         }
3321
3322         private void processGetInput(List<GetInputValueDataDefinition> getInputValues, List<InputDefinition> inputs,
3323                                                                  GetInputValueDataDefinition getInputIndex) {
3324                 Optional<InputDefinition> optional;
3325                 if (getInputIndex != null) {
3326                         optional = inputs.stream()
3327                                         .filter(p -> p.getName()
3328                                                         .equals(getInputIndex.getInputName()))
3329                                         .findAny();
3330                         if (!optional.isPresent()) {
3331                                 log.debug("Failed to find input {} ", getInputIndex.getInputName());
3332                                 // @@TODO error message
3333                                 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
3334                         }
3335                         InputDefinition inputIndex = optional.get();
3336                         getInputIndex.setInputId(inputIndex.getUniqueId());
3337                         getInputValues.add(getInputIndex);
3338                 }
3339         }
3340
3341         private void addInput(Map<String, InputDefinition> currPropertiesMap, InputDefinition prop) {
3342                 String propName = prop.getName();
3343                 if (!currPropertiesMap.containsKey(propName)) {
3344                         currPropertiesMap.put(propName, prop);
3345                 }
3346         }
3347
3348         private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
3349                                                                                                  Resource resource, Resource originResource, ComponentInstance currentCompInstance,
3350                                                                                                  Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) {
3351
3352                 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
3353                 Map<String, PropertyDefinition> currPropertiesMap = new HashMap<>();
3354
3355                 List<PropertyDefinition> listFromMap = originResource.getProperties();
3356                 if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) {
3357                         loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
3358                                         StatusCode.ERROR,"ERROR Failed to find properties");
3359                         log.debug("failed to find properties");
3360                         return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
3361                 }
3362                 if (listFromMap == null || listFromMap.isEmpty()) {
3363                         return componentsUtils.getResponseFormat(ActionStatus.OK);
3364                 }
3365                 for (PropertyDefinition prop : listFromMap) {
3366                         String propName = prop.getName();
3367                         if (!currPropertiesMap.containsKey(propName)) {
3368                                 currPropertiesMap.put(propName, prop);
3369                         }
3370                 }
3371                 List<ComponentInstanceProperty> instPropList = new ArrayList<>();
3372                 if (propMap != null && propMap.size() > 0) {
3373                         for (List<UploadPropInfo> propertyList : propMap.values()) {
3374
3375                                 UploadPropInfo propertyInfo = propertyList.get(0);
3376                                 String propName = propertyInfo.getName();
3377                                 if (!currPropertiesMap.containsKey(propName)) {
3378                                         log.debug("failed to find property {} ", propName);
3379                                         loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR Failed to find property: {}",propName);
3380                                         return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
3381                                 }
3382                                 PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
3383                                 ComponentInstanceProperty property = null;
3384
3385                                 String value = null;
3386                                 List<GetInputValueDataDefinition> getInputs = null;
3387                                 boolean isValidate = true;
3388                                 if (propertyInfo.getValue() != null) {
3389                                         getInputs = propertyInfo.getGet_input();
3390                                         isValidate = getInputs == null || getInputs.isEmpty();
3391                                         if (isValidate) {
3392                                                 value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
3393                                         } else {
3394                                                 value = getPropertyJsonStringValue(propertyInfo.getValue(),
3395                                                                 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
3396                                         }
3397                                 }
3398                                 String innerType = null;
3399                                 property = new ComponentInstanceProperty(curPropertyDef, value, null);
3400
3401                 String validatePropValue = validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
3402                                 property.setValue(validatePropValue);
3403
3404                                 if (getInputs != null && !getInputs.isEmpty()) {
3405                                         List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
3406                                         for (GetInputValueDataDefinition getInput : getInputs) {
3407                                                 List<InputDefinition> inputs = resource.getInputs();
3408                                                 if (inputs == null || inputs.isEmpty()) {
3409                                                         log.debug("Failed to add property {} to instance. Inputs list is empty ", property);
3410                                                         loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"Failed to add property: {} to instance. Inputs list is empty",propName);
3411                                                         rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
3412                                                                         .stream()
3413                                                                         .map(GetInputValueDataDefinition::getInputName)
3414                                                                         .collect(toList())
3415                                                                         .toString());
3416                                                 }
3417                                                 InputDefinition input = findInputByName(inputs, getInput);
3418                                                 getInput.setInputId(input.getUniqueId());
3419                                                 getInputValues.add(getInput);
3420
3421                                                 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
3422                                                 if (getInputIndex != null) {
3423                                                         input = findInputByName(inputs, getInputIndex);
3424                                                         getInputIndex.setInputId(input.getUniqueId());
3425                                                         getInputValues.add(getInputIndex);
3426
3427                                                 }
3428
3429                                         }
3430                                         property.setGetInputValues(getInputValues);
3431                                 }
3432                                 instPropList.add(property);
3433                                 // delete overriden property
3434                                 currPropertiesMap.remove(property.getName());
3435                         }
3436                 }
3437                 // add rest of properties
3438                 if (!currPropertiesMap.isEmpty()) {
3439                         for (PropertyDefinition value : currPropertiesMap.values()) {
3440                                 instPropList.add(new ComponentInstanceProperty(value));
3441                         }
3442                 }
3443                 instProperties.put(currentCompInstance.getUniqueId(), instPropList);
3444                 return componentsUtils.getResponseFormat(ActionStatus.OK);
3445         }
3446
3447         // US740820 Relate RIs according to capability name
3448         private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq,
3449                                                                                                                                          ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
3450                 if (null == uploadReqInfo.getCapabilityName() || validReq.getCapability()
3451                                 .equals(uploadReqInfo.getCapabilityName())) {// get
3452                         // by
3453                         // capability
3454                         // type
3455                         return findAvailableCapability(validReq, currentCapCompInstance);
3456                 }
3457                 return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo);
3458         }
3459
3460         private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq,
3461                                                                                                                  ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
3462                 CapabilityDefinition cap = null;
3463                 Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
3464                 if (!capMap.containsKey(validReq.getCapability())) {
3465                         return null;
3466                 }
3467                 Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability())
3468                                 .stream()
3469                                 .filter(p -> p.getName()
3470                                                 .equals(uploadReqInfo.getCapabilityName()))
3471                                 .findAny();
3472                 if (!capByName.isPresent()) {
3473                         return null;
3474                 }
3475                 cap = capByName.get();
3476
3477                 if (isBoundedByOccurrences(cap)) {
3478                         String leftOccurrences = cap.getLeftOccurrences();
3479                         int left = Integer.parseInt(leftOccurrences);
3480                         if (left > 0) {
3481                                 --left;
3482                                 cap.setLeftOccurrences(String.valueOf(left));
3483
3484                         }
3485
3486                 }
3487                 return cap;
3488         }
3489
3490         private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance instance) {
3491                 Map<String, List<CapabilityDefinition>> capMap = instance.getCapabilities();
3492                 if (capMap.containsKey(validReq.getCapability())) {
3493                         List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
3494
3495                         for (CapabilityDefinition cap : capList) {
3496                                 if (isBoundedByOccurrences(cap)) {
3497                                         String leftOccurrences = cap.getLeftOccurrences() != null ? cap.getLeftOccurrences()
3498                                                         : cap.getMaxOccurrences();
3499                                         int left = Integer.parseInt(leftOccurrences);
3500                                         if (left > 0) {
3501                                                 --left;
3502                                                 cap.setLeftOccurrences(String.valueOf(left));
3503                                                 return cap;
3504                                         }
3505                                 } else {
3506                                         return cap;
3507                                 }
3508                         }
3509                 }
3510                 return null;
3511         }
3512
3513         private boolean isBoundedByOccurrences(CapabilityDefinition cap) {
3514                 return cap.getMaxOccurrences() != null && !cap.getMaxOccurrences()
3515                                 .equals(CapabilityDataDefinition.MAX_OCCURRENCES);
3516         }
3517
3518         private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName,
3519                                                                                                                                                                 UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance,
3520                                                                                                                                                                 String capName) {
3521                 Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
3522                 List<RequirementDefinition> list = comInstRegDefMap.get(capName);
3523                 RequirementDefinition validRegDef = null;
3524                 if (list == null) {
3525                         for (Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
3526                                 for (RequirementDefinition reqDef : entry.getValue()) {
3527                                         if (reqDef.getName()
3528                                                         .equals(regName)) {
3529                                                 if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences()
3530                                                                 .equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
3531                                                         String leftOccurrences = reqDef.getLeftOccurrences();
3532                                                         if (leftOccurrences == null) {
3533                                                                 leftOccurrences = reqDef.getMaxOccurrences();
3534                                                         }
3535                                                         int left = Integer.parseInt(leftOccurrences);
3536                                                         if (left > 0) {
3537                                                                 --left;
3538                                                                 reqDef.setLeftOccurrences(String.valueOf(left));
3539                                                                 validRegDef = reqDef;
3540                                                                 break;
3541                                                         } else {
3542                                                                 continue;
3543                                                         }
3544                                                 } else {
3545                                                         validRegDef = reqDef;
3546                                                         break;
3547                                                 }
3548
3549                                         }
3550                                 }
3551                                 if (validRegDef != null) {
3552                                         break;
3553                                 }
3554                         }
3555                 } else {
3556                         for (RequirementDefinition reqDef : list) {
3557                                 if (reqDef.getName()
3558                                                 .equals(regName)) {
3559                                         if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences()
3560                                                         .equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
3561                                                 String leftOccurrences = reqDef.getLeftOccurrences();
3562                                                 if (leftOccurrences == null) {
3563                                                         leftOccurrences = reqDef.getMaxOccurrences();
3564                                                 }
3565                                                 int left = Integer.parseInt(leftOccurrences);
3566                                                 if (left > 0) {
3567                                                         --left;
3568                                                         reqDef.setLeftOccurrences(String.valueOf(left));
3569                                                         validRegDef = reqDef;
3570                                                         break;
3571                                                 } else {
3572                                                         continue;
3573                                                 }
3574                                         } else {
3575                                                 validRegDef = reqDef;
3576                                                 break;
3577                                         }
3578                                 }
3579                         }
3580                 }
3581                 if (validRegDef == null) {
3582                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
3583                                         yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3584                         return Either.right(responseFormat);
3585                 }
3586                 return Either.left(validRegDef);
3587         }
3588
3589         private Resource createResourceInstances(String yamlName, Resource resource, Resource oldResource,
3590                                                                                          Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingNodeTypesByResourceNames) {
3591
3592                 Either<Resource, ResponseFormat> eitherResource;
3593                 log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
3594         if (isEmpty(uploadResInstancesMap) && resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
3595             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
3596             throw new ByResponseFormatComponentException(responseFormat);
3597                 }
3598                 if (MapUtils.isNotEmpty(nodeNamespaceMap)) {
3599                         nodeNamespaceMap.forEach((k, v) -> existingNodeTypesByResourceNames.put(v.getToscaResourceName(), v));
3600                 }
3601                 Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
3602                 uploadResInstancesMap.values()
3603                                 .forEach(i -> createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap,
3604                                                 existingNodeTypesByResourceNames, resourcesInstancesMap));
3605                 if (oldResource != null && oldResource.getResourceType() != ResourceTypeEnum.CVFC && oldResource.getComponentInstances() != null) {
3606                         Map<String, Resource> existingNodeTypesByUids = existingNodeTypesByResourceNames.values()
3607                                         .stream()
3608                                         .collect(toMap(Resource::getUniqueId, r -> r));
3609                         oldResource.getComponentInstances()
3610                                         .stream()
3611                                         .filter(i -> !i.isCreatedFromCsar())
3612                                         .forEach(uiInst -> resourcesInstancesMap.put(uiInst,
3613                                                         getOriginResource(existingNodeTypesByUids, uiInst)));
3614                 }
3615
3616                 if (isNotEmpty(resourcesInstancesMap)) {
3617                         try {
3618                                 toscaOperationFacade.associateComponentInstancesToComponent(resource,
3619                                                 resourcesInstancesMap, false, oldResource != null);
3620                         } catch (StorageException exp) {
3621                                 if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) {
3622                                         log.debug("Failed to add component instances to container component {}", resource.getName());
3623                                         ResponseFormat responseFormat = componentsUtils
3624                                                         .getResponseFormat(componentsUtils.convertFromStorageResponse(exp.getStorageOperationStatus()));
3625                                         eitherResource = Either.right(responseFormat);
3626                                         throw new ByResponseFormatComponentException(eitherResource.right().value());
3627                                 }
3628                         }
3629                 }
3630         if (CollectionUtils.isEmpty(resource.getComponentInstances()) &&
3631                 resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
3632                         log.debug("Error when create resource instance from csar. ComponentInstances list empty");
3633                         BeEcompErrorManager.getInstance()
3634                                         .logBeDaoSystemError(
3635                                                         "Error when create resource instance from csar. ComponentInstances list empty");
3636                         throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
3637                 }
3638                 return resource;
3639         }
3640
3641         private void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName,
3642                                                                                           Resource resource, Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingnodeTypeMap,
3643                                                                                           Map<ComponentInstance, Resource> resourcesInstancesMap) {
3644                 Either<Resource, ResponseFormat> eitherResource;
3645                 log.debug("*************Going to create  resource instances {}", yamlName);
3646                 // updating type if the type is node type name - we need to take the
3647                 // updated name
3648                 log.debug("*************Going to create  resource instances {}", uploadComponentInstanceInfo.getName());
3649                 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
3650                         uploadComponentInstanceInfo.setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType())
3651                                         .getToscaResourceName());
3652                 }
3653                 Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo,
3654                                 existingnodeTypeMap);
3655
3656                 ComponentInstance componentInstance = new ComponentInstance();
3657                 componentInstance.setComponentUid(refResource.getUniqueId());
3658         Collection<String> directives = uploadComponentInstanceInfo.getDirectives();
3659         if(directives != null && !directives.isEmpty()) {
3660             componentInstance.setDirectives(new ArrayList<>(directives));
3661         }
3662         UploadNodeFilterInfo uploadNodeFilterInfo = uploadComponentInstanceInfo.getUploadNodeFilterInfo();
3663         if (uploadNodeFilterInfo != null){
3664             componentInstance.setNodeFilter(new CINodeFilterUtils().getNodeFilterDataDefinition(uploadNodeFilterInfo,
3665                     componentInstance.getUniqueId()));
3666         }
3667         ComponentTypeEnum containerComponentType = resource.getComponentType();
3668                 NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
3669                 if (containerNodeType == NodeTypeEnum.Resource && isNotEmpty(uploadComponentInstanceInfo.getCapabilities())
3670                                 && isNotEmpty(refResource.getCapabilities())) {
3671                         setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
3672                         Map<String, List<CapabilityDefinition>> validComponentInstanceCapabilities = getValidComponentInstanceCapabilities(
3673                                         refResource.getUniqueId(), refResource.getCapabilities(),
3674                                         uploadComponentInstanceInfo.getCapabilities());
3675                         componentInstance.setCapabilities(validComponentInstanceCapabilities);
3676                 }
3677
3678         if (isNotEmpty(uploadComponentInstanceInfo.getArtifacts())) {
3679             Map<String, Map<String, UploadArtifactInfo>> artifacts = uploadComponentInstanceInfo.getArtifacts();
3680             Map<String, ToscaArtifactDataDefinition> toscaArtifacts = new HashMap<>();
3681             Map<String, Map<String, UploadArtifactInfo>> arts = artifacts.entrySet().stream()
3682                                         .filter(e -> e.getKey().contains(TypeUtils.ToscaTagNamesEnum.ARTIFACTS.getElementName()))
3683                                         .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
3684             Map<String, UploadArtifactInfo> artifact = arts.get(TypeUtils.ToscaTagNamesEnum.ARTIFACTS.getElementName());
3685             for (Map.Entry<String, UploadArtifactInfo> entry : artifact.entrySet()) {
3686                 ToscaArtifactDataDefinition to = new ToscaArtifactDataDefinition();
3687                 to.setFile(entry.getValue().getFile());
3688                 to.setType(entry.getValue().getType());
3689                 toscaArtifacts.put(entry.getKey(), to);
3690             }
3691             componentInstance.setToscaArtifacts(toscaArtifacts);
3692         }
3693
3694                 if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
3695                         log.debug("createResourceInstances - not found lates version for resource instance with name {} and type ",
3696                                         uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3697                         throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
3698                                         yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3699                 }
3700                 Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
3701                 componentInstance.setName(uploadComponentInstanceInfo.getName());
3702                 componentInstance.setIcon(origResource.getIcon());
3703                 componentInstance.setCreatedFrom(CreatedFrom.CSAR);
3704                 resourcesInstancesMap.put(componentInstance, origResource);
3705         }
3706
3707         private ComponentParametersView getComponentWithInstancesFilter() {
3708                 ComponentParametersView parametersView = new ComponentParametersView();
3709                 parametersView.disableAll();
3710                 parametersView.setIgnoreComponentInstances(false);
3711                 parametersView.setIgnoreInputs(false);
3712                 // inputs are read when creating
3713                 // property values on instances
3714                 parametersView.setIgnoreUsers(false);
3715                 return parametersView;
3716         }
3717
3718         private void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities,
3719                                                                                  Map<String, List<UploadCapInfo>> uploadedCapabilities) {
3720                 for (Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()) {
3721                         if (originCapabilities.containsKey(currEntry.getKey())) {
3722                                 currEntry.getValue()
3723                                                 .stream()
3724                                                 .forEach(cap -> cap.setType(currEntry.getKey()));
3725                         }
3726                 }
3727                 for (Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()) {
3728                         capabilities.getValue()
3729                                         .stream()
3730                                         .forEach(cap -> {
3731                                                 if (uploadedCapabilities.containsKey(cap.getName())) {
3732                                                         uploadedCapabilities.get(cap.getName())
3733                                                                         .stream()
3734                                                                         .forEach(c -> {
3735                                                                                 c.setName(cap.getName());
3736                                                                                 c.setType(cap.getType());
3737                                                                         });
3738                                                 }
3739                                         });
3740                 }
3741         }
3742
3743         private Resource validateResourceInstanceBeforeCreate(String yamlName,
3744                                                                                                                   UploadComponentInstanceInfo uploadComponentInstanceInfo, Map<String, Resource> nodeNamespaceMap) {
3745
3746                 log.debug(
3747                                 "validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type {} before create",
3748                                 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3749                 Resource refResource;
3750                 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
3751                         refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType());
3752                 } else {
3753                         Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade
3754                                         .getLatestCertifiedNodeTypeByToscaResourceName(uploadComponentInstanceInfo.getType());
3755                         if (findResourceEither.isRight()) {
3756                                 log.debug(
3757                                                 "validateResourceInstanceBeforeCreate - not found lates version for resource instance with name {} and type {}",
3758                                                 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3759                                 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
3760                         }
3761                         refResource = findResourceEither.left().value();
3762                         nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
3763                 }
3764                 String componentState = refResource.getComponentMetadataDefinition()
3765                                 .getMetadataDataDefinition()
3766                                 .getState();
3767                 if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
3768                         log.debug(
3769                                         "validateResourceInstanceBeforeCreate - component instance of component {} can not be created because the component is in an illegal state {}.",
3770                                         refResource.getName(), componentState);
3771                         throw new ByActionStatusComponentException(ActionStatus.ILLEGAL_COMPONENT_STATE,
3772                                         refResource.getComponentType().getValue(),refResource.getName(), componentState);
3773                 }
3774
3775                 if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) {
3776                         log.debug("validateResourceInstanceBeforeCreate -  ref resource type is  ", refResource.getResourceType());
3777                         throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
3778                                         yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3779                 }
3780                 return refResource;
3781         }
3782
3783         public Resource propagateStateToCertified(User user, Resource resource,
3784                                                                                           LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock,
3785                                                                                           boolean forceCertificationAllowed) {
3786
3787                 boolean failed = false;
3788                 try {
3789                         if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed
3790                                         && lifecycleBusinessLogic.isFirstCertification(resource.getVersion())) {
3791                                 nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
3792                         }
3793                         if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
3794                                 Either<ArtifactDefinition, Operation> eitherPopulated = populateToscaArtifacts(
3795                                                 resource, user, false, inTransaction, needLock, false);
3796                                 return resource;
3797                         }
3798                         return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
3799                 } catch (ComponentException e) {
3800                         failed = true;
3801                         log.debug("The exception has occurred upon certification of resource {}. ", resource.getName(), e);
3802                         throw e;
3803                 } finally {
3804                         if (failed) {
3805                                 BeEcompErrorManager.getInstance()
3806                                                 .logBeSystemError("Change LifecycleState - Certify");
3807                                 if (!inTransaction) {
3808                     janusGraphDao.rollback();
3809                                 }
3810                         } else if (!inTransaction) {
3811                 janusGraphDao.commit();
3812                         }
3813                 }
3814         }
3815
3816         private Resource nodeFullCertification(String uniqueId, User user,
3817                                                                                    LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
3818                 Either<Resource, ResponseFormat> resourceResponse = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo,
3819                                 inTransaction, needLock);
3820                 if(resourceResponse.isRight()){
3821                         throw new ByResponseFormatComponentException(resourceResponse.right().value());
3822                 }
3823                 return resourceResponse.left().value();
3824         }
3825
3826         private Resource nodeForceCertification(Resource resource, User user,
3827                                                                                         LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
3828                 return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction,
3829                                 needLock);
3830         }
3831
3832         public ImmutablePair<Resource, ActionStatus> createOrUpdateResourceByImport(final Resource resource,
3833                                                                                                                                                                 final User user,
3834                                                                                                                                                                 final boolean isNormative,
3835                                                                                                                                                                 final boolean isInTransaction,
3836                                                                                                                                                                 final boolean needLock,
3837                                                                                                                                                                 final CsarInfo csarInfo,
3838                                                                                                                                                                 final String nodeName,
3839                                                                                                                                                                 final boolean isNested) {
3840
3841                 ImmutablePair<Resource, ActionStatus> result = null;
3842                 // check if resource already exists (search by tosca name = type)
3843                 final boolean isNestedResource = isNestedResourceUpdate(csarInfo, nodeName);
3844                 final Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade
3845                         .getLatestByToscaResourceName(resource.getToscaResourceName());
3846
3847                 if (latestByToscaName.isLeft()) {
3848                         Resource foundResource = latestByToscaName.left().value();
3849                         // we don't allow updating names of top level types
3850                         if (!isNestedResource && !StringUtils.equals(resource.getName(), foundResource.getName())) {
3851                                 BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import",
3852                                         ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
3853                                 log.debug("resource already exist new name={} old name={} same type={}", resource.getName(),
3854                                         foundResource.getName(), resource.getToscaResourceName());
3855                                 final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
3856                                 componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
3857                                 throwComponentException(responseFormat);
3858                         }
3859                         result = updateExistingResourceByImport(resource, foundResource, user, isNormative, needLock, isNested);
3860                 } else if (isNotFound(latestByToscaName)) {
3861                         if (isNestedResource) {
3862                                 result = createOrUpdateNestedResource(resource, user, isNormative, isInTransaction, needLock, csarInfo,
3863                                         isNested, nodeName);
3864                         } else {
3865                                 result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3866                         }
3867                 } else {
3868                         StorageOperationStatus status = latestByToscaName.right().value();
3869                         log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
3870                         ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils
3871                                 .convertFromStorageResponse(latestByToscaName.right().value()), resource);
3872                         componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
3873                         throwComponentException(responseFormat);
3874                 }
3875                 return result;
3876         }
3877
3878         private boolean isNestedResourceUpdate(CsarInfo csarInfo, String nodeName) {
3879                 return csarInfo != null && csarInfo.isUpdate() && nodeName != null;
3880         }
3881
3882         private ImmutablePair<Resource, ActionStatus> createOrUpdateNestedResource(final Resource resource,
3883                                                                                                                                                            final User user,
3884                                                                                                                                                            final boolean isNormative,
3885                                                                                                                                                            final boolean isInTransaction,
3886                                                                                                                                                            final boolean needLock,
3887                                                                                                                                                            final CsarInfo csarInfo,
3888                                                                                                                                                            final boolean isNested,
3889                                                                                                                                                            final String nodeName) {
3890                 final Either<Component, StorageOperationStatus> latestByToscaName = toscaOperationFacade
3891                         .getLatestByToscaResourceName(buildNestedToscaResourceName(resource.getResourceType()
3892                                 .name(), csarInfo.getVfResourceName(), nodeName).getRight());
3893                 if (latestByToscaName.isLeft()) {
3894                         final Resource nestedResource = (Resource) latestByToscaName.left().value();
3895                         log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
3896                         final Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(nestedResource,
3897                                 resource, ValidationUtils.hasBeenCertified(nestedResource.getVersion()));
3898                         if (eitherValidation.isRight()) {
3899                                 return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3900                         }
3901                         return updateExistingResourceByImport(resource, nestedResource, user, isNormative, needLock, isNested);
3902                 } else {
3903                         return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3904                 }
3905         }
3906
3907         private boolean isNotFound(Either<Resource, StorageOperationStatus> getResourceEither) {
3908                 return getResourceEither.isRight() && getResourceEither.right()
3909                                 .value() == StorageOperationStatus.NOT_FOUND;
3910         }
3911
3912         private ImmutablePair<Resource, ActionStatus> createResourceByImport(Resource resource, User user,
3913                                                                                                                                                  boolean isNormative, boolean isInTransaction, CsarInfo csarInfo) {
3914                 log.debug("resource with name {} does not exist. create new resource", resource.getName());
3915                 validateResourceBeforeCreate(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isInTransaction, csarInfo);
3916                 final Resource createResourceByDao = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative,
3917                                 isInTransaction);
3918                 Resource createdResource  = updateCatalog(createResourceByDao, ChangeTypeEnum.LIFECYCLE).left().map(r -> (Resource)r).left().value();
3919                 ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createdResource, ActionStatus.CREATED);
3920                 ASDCKpiApi.countImportResourcesKPI();
3921                 return resourcePair;
3922         }
3923
3924         public boolean isResourceExist(String resourceName) {
3925                 Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resourceName);
3926                 return latestByName.isLeft();
3927         }
3928
3929         private ImmutablePair<Resource, ActionStatus> updateExistingResourceByImport(Resource newResource,
3930                                                                                                                                                                  Resource oldResource, User user, boolean inTransaction, boolean needLock, boolean isNested) {
3931                 String lockedResourceId = oldResource.getUniqueId();
3932                 log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId,
3933                                 oldResource.getVersion(), oldResource.getLifecycleState());
3934                 ImmutablePair<Resource, ActionStatus> resourcePair = null;
3935                 try {
3936                         lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import");
3937                         oldResource = prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false);
3938                         mergeOldResourceMetadataWithNew(oldResource, newResource);
3939
3940                         validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested);
3941                         validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), newResource,
3942                                         AuditingActionEnum.IMPORT_RESOURCE, inTransaction);
3943                         // contact info normalization
3944                         newResource.setContactId(newResource.getContactId()
3945                                         .toLowerCase());
3946                         PropertyConstraintsUtils.validatePropertiesConstraints(newResource, oldResource);
3947                         // non-updatable fields
3948                         newResource.setCreatorUserId(user.getUserId());
3949                         newResource.setCreatorFullName(user.getFullName());
3950                         newResource.setLastUpdaterUserId(user.getUserId());
3951                         newResource.setLastUpdaterFullName(user.getFullName());
3952                         newResource.setUniqueId(oldResource.getUniqueId());
3953                         newResource.setVersion(oldResource.getVersion());
3954                         newResource.setInvariantUUID(oldResource.getInvariantUUID());
3955                         newResource.setLifecycleState(oldResource.getLifecycleState());
3956                         newResource.setUUID(oldResource.getUUID());
3957                         newResource.setNormalizedName(oldResource.getNormalizedName());
3958                         newResource.setSystemName(oldResource.getSystemName());
3959                         if (oldResource.getCsarUUID() != null) {
3960                                 newResource.setCsarUUID(oldResource.getCsarUUID());
3961                         }
3962                         if (oldResource.getImportedToscaChecksum() != null) {
3963                                 newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
3964                         }
3965                         newResource.setAbstract(oldResource.isAbstract());
3966
3967                         if (newResource.getDerivedFrom() == null || newResource.getDerivedFrom()
3968                                         .isEmpty()) {
3969                                 newResource.setDerivedFrom(oldResource.getDerivedFrom());
3970                         }
3971                         if (newResource.getDerivedFromGenericType() == null || newResource.getDerivedFromGenericType()
3972                                         .isEmpty()) {
3973                                 newResource.setDerivedFromGenericType(oldResource.getDerivedFromGenericType());
3974                         }
3975                         if (newResource.getDerivedFromGenericVersion() == null || newResource.getDerivedFromGenericVersion()
3976                                         .isEmpty()) {
3977                                 newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion());
3978                         }
3979                         // add for new)
3980                         // created without tosca artifacts - add the placeholders
3981                         if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts()
3982                                         .isEmpty()) {
3983                                 setToscaArtifactsPlaceHolders(newResource, user);
3984                         }
3985
3986                         if (newResource.getInterfaces() == null || newResource.getInterfaces().isEmpty()) {
3987                                 newResource.setInterfaces(oldResource.getInterfaces());
3988                         }
3989
3990             if (CollectionUtils.isEmpty(newResource.getProperties())) {
3991                 newResource.setProperties(oldResource.getProperties());
3992             }
3993
3994                         Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade
3995                                         .overrideComponent(newResource, oldResource);
3996
3997                         if (overrideResource.isRight()) {
3998                                 ResponseFormat responseFormat = componentsUtils
3999                                                 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(overrideResource.right()
4000                                                                 .value()), newResource);
4001                                 componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE);
4002
4003                                 throwComponentException(responseFormat);
4004                         }
4005                         updateCatalog(overrideResource.left()
4006                                         .value(), ChangeTypeEnum.LIFECYCLE);
4007
4008                         log.debug("Resource updated successfully!!!");
4009                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4010                         componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
4011                                         ResourceVersionInfo.newBuilder()
4012                                                         .state(oldResource.getLifecycleState()
4013                                                                         .name())
4014                                                         .version(oldResource.getVersion())
4015                                                         .build());
4016
4017                         resourcePair = new ImmutablePair<>(overrideResource.left()
4018                                         .value(), ActionStatus.OK);
4019                         return resourcePair;
4020                 } finally {
4021                         if (resourcePair == null) {
4022                                 BeEcompErrorManager.getInstance()
4023                                                 .logBeSystemError("Change LifecycleState - Certify");
4024                                 janusGraphDao.rollback();
4025                         } else if (!inTransaction) {
4026                 janusGraphDao.commit();
4027                         }
4028                         if (needLock) {
4029                                 log.debug("unlock resource {}", lockedResourceId);
4030                                 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
4031                         }
4032                 }
4033
4034         }
4035
4036         /**
4037          * Merge old resource with new. Keep old category and vendor name without
4038          * change
4039          *
4040          * @param oldResource
4041          * @param newResource
4042          */
4043         private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
4044
4045                 // keep old category and vendor name without change
4046                 // merge the rest of the resource metadata
4047                 if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
4048                         newResource.setTags(oldResource.getTags());
4049                 }
4050
4051                 if (newResource.getDescription() == null) {
4052                         newResource.setDescription(oldResource.getDescription());
4053                 }
4054
4055                 if (newResource.getVendorRelease() == null) {
4056                         newResource.setVendorRelease(oldResource.getVendorRelease());
4057                 }
4058
4059                 if (newResource.getResourceVendorModelNumber() == null) {
4060                         newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber());
4061                 }
4062
4063                 if (newResource.getContactId() == null) {
4064                         newResource.setContactId(oldResource.getContactId());
4065                 }
4066
4067                 newResource.setCategories(oldResource.getCategories());
4068                 if (newResource.getVendorName() == null) {
4069                         newResource.setVendorName(oldResource.getVendorName());
4070                 }
4071                 List<GroupDefinition>oldForUpdate = oldResource.getGroups();
4072                 if(CollectionUtils.isNotEmpty(oldForUpdate)){
4073                         List<GroupDefinition>groupForUpdate = oldForUpdate.stream().map(group -> new GroupDefinition(group)).collect(Collectors.toList());
4074
4075                         groupForUpdate.stream().filter(group -> group.isVspOriginated())
4076                                         .forEach(group -> group.setName(group.getInvariantName()));
4077
4078                         newResource.setGroups(groupForUpdate);
4079                 }
4080
4081
4082                 if(newResource.getResourceType().isAtomicType() && !newResource.getName().equals("Root")&& newResource.getResourceType() != ResourceTypeEnum.CVFC) {
4083                         ResourceTypeEnum updatedResourceType = newResource.getResourceType();
4084                         Component derivedFromResource = getParentComponent(newResource);
4085                         if (derivedFromResource.getComponentType() == ComponentTypeEnum.RESOURCE) {
4086                                 Resource parentResource = (Resource) derivedFromResource;
4087                                 if (!(parentResource.isAbstract() && (ResourceTypeEnum.VFC == parentResource.getResourceType() || ResourceTypeEnum.ABSTRACT == parentResource.getResourceType())) &&
4088                                                 parentResource.getResourceType() != updatedResourceType) {
4089                                         BeEcompErrorManager.getInstance()
4090                                                         .logInternalDataError("mergeOldResourceMetadataWithNew", "resource type of the resource does not match to derived from resource type",
4091                                                                         ErrorSeverity.ERROR);
4092                                         log.debug("#mergeOldResourceMetadataWithNew - resource type {} of the resource {} does not match to derived from resource type {}",
4093                                                         newResource.getResourceType(), newResource.getToscaResourceName(), parentResource.getResourceType());
4094                                         throw new ByActionStatusComponentException(ActionStatus.INVALID_RESOURCE_TYPE);
4095                                 }
4096                         }
4097                 }
4098
4099         }
4100
4101         private Component getParentComponent(Resource newResource) {
4102                 String toscaResourceNameDerivedFrom = newResource.getDerivedFrom().get(0);
4103                 Either<Component, StorageOperationStatus> latestByToscaResourceName = toscaOperationFacade.getLatestByToscaResourceName(toscaResourceNameDerivedFrom);
4104                 if(latestByToscaResourceName.isRight()){
4105                         BeEcompErrorManager.getInstance()
4106                                         .logInternalDataError("mergeOldResourceMetadataWithNew", "derived from resource not found", ErrorSeverity.ERROR);
4107                         log.debug("#mergeOldResourceMetadataWithNew - derived from resource {} not found", toscaResourceNameDerivedFrom);
4108                         throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, toscaResourceNameDerivedFrom);
4109                 }
4110                 return latestByToscaResourceName.left().value();
4111         }
4112
4113         private Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user,
4114                                                                                           boolean inTransaction, boolean needLock) {
4115
4116                 if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) {
4117                         // checkout
4118                         return lifecycleBusinessLogic.changeState(oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
4119                                         new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock)
4120                                         .left()
4121                                         .on(response -> failOnChangeState(response, user, oldResource, newResource));
4122                 }
4123                 return oldResource;
4124         }
4125
4126         private Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) {
4127                 log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(), response.getFormattedMessage());
4128                 componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
4129                                 ResourceVersionInfo.newBuilder()
4130                                                 .state(oldResource.getLifecycleState()
4131                                                                 .name())
4132                                                 .version(oldResource.getVersion())
4133                                                 .build());
4134                 throw new ByResponseFormatComponentException(response);
4135         }
4136
4137         public Resource validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum,
4138                                                                                                  boolean inTransaction, CsarInfo csarInfo) {
4139
4140                 validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
4141                 validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
4142                 validateLifecycleTypesCreate(user, resource, actionEnum);
4143                 validateResourceType(user, resource, actionEnum);
4144                 resource.setCreatorUserId(user.getUserId());
4145                 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
4146                 resource.setContactId(resource.getContactId()
4147                                 .toLowerCase());
4148                 if (StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) {
4149                         String resourceSystemName;
4150                         if (csarInfo != null && StringUtils.isNotEmpty(csarInfo.getVfResourceName())) {
4151                                 resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName());
4152                         } else {
4153                                 resourceSystemName = resource.getSystemName();
4154                         }
4155                         resource.setToscaResourceName(CommonBeUtils
4156                                 .generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
4157                 }
4158
4159                 // Generate invariant UUID - must be here and not in operation since it
4160                 // should stay constant during clone
4161                 // TODO
4162                 String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
4163                 resource.setInvariantUUID(invariantUUID);
4164
4165                 return resource;
4166         }
4167
4168         private Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource,
4169                                                                                                                                  AuditingActionEnum actionEnum) {
4170                 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4171                 if (resource.getResourceType() == null) {
4172                         log.debug("Invalid resource type for resource");
4173                         ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
4174                         eitherResult = Either.right(errorResponse);
4175                         componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4176                 }
4177                 return eitherResult;
4178         }
4179
4180         private Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource,
4181                                                                                                                                                  AuditingActionEnum actionEnum) {
4182                 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4183                 if (resource.getInterfaces() != null && resource.getInterfaces()
4184                                 .size() > 0) {
4185                         log.debug("validate interface lifecycle Types Exist");
4186                         Iterator<InterfaceDefinition> intItr = resource.getInterfaces()
4187                                         .values()
4188                                         .iterator();
4189                         while (intItr.hasNext() && eitherResult.isLeft()) {
4190                                 InterfaceDefinition interfaceDefinition = intItr.next();
4191                                 String intType = interfaceDefinition.getUniqueId();
4192                                 Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation
4193                                                 .getInterface(intType);
4194                                 if (eitherCapTypeFound.isRight()) {
4195                                         if (eitherCapTypeFound.right()
4196                                                         .value() == StorageOperationStatus.NOT_FOUND) {
4197                                                 BeEcompErrorManager.getInstance()
4198                                                                 .logBeGraphObjectMissingError("Create Resource - validateLifecycleTypesCreate",
4199                                                                                 "Interface", intType);
4200                                                 log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB",
4201                                                                 intType, resource.getName());
4202                                                 BeEcompErrorManager.getInstance()
4203                                                                 .logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
4204                                                 log.debug("request to data model failed with error: {}", eitherCapTypeFound.right()
4205                                                                 .value()
4206                                                                 .name());
4207                                         }
4208
4209                                         ResponseFormat errorResponse = componentsUtils
4210                                                         .getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
4211                                         eitherResult = Either.right(errorResponse);
4212                                         componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4213                                 }
4214
4215                         }
4216                 }
4217                 return eitherResult;
4218         }
4219
4220         private Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user,
4221                                                                                                                                                   ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
4222                                                                                                                                                   boolean inTransaction) {
4223
4224                 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4225                 if (resource.getCapabilities() != null && resource.getCapabilities()
4226                                 .size() > 0) {
4227                         log.debug("validate capability Types Exist - capabilities section");
4228
4229                         for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities()
4230                                         .entrySet()) {
4231
4232                                 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum,
4233                                                 eitherResult, typeEntry, inTransaction);
4234                                 if (eitherResult.isRight()) {
4235                                         return Either.right(eitherResult.right()
4236                                                         .value());
4237                                 }
4238                         }
4239                 }
4240
4241                 if (resource.getRequirements() != null && resource.getRequirements()
4242                                 .size() > 0) {
4243                         log.debug("validate capability Types Exist - requirements section");
4244                         for (String type : resource.getRequirements()
4245                                         .keySet()) {
4246                                 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource,
4247                                                 resource.getRequirements()
4248                                                                 .get(type),
4249                                                 actionEnum, eitherResult, type, inTransaction);
4250                                 if (eitherResult.isRight()) {
4251                                         return Either.right(eitherResult.right()
4252                                                         .value());
4253                                 }
4254                         }
4255                 }
4256
4257                 return eitherResult;
4258         }
4259
4260         // @param typeObject- the object to which the validation is done
4261         private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
4262                                                                                                                                                  ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List<?> validationObjects,
4263                                                                                                                                                  AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type,
4264                                                                                                                                                  boolean inTransaction) {
4265                 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
4266                                 .getCapabilityType(type, inTransaction);
4267                 if (eitherCapTypeFound.isRight()) {
4268                         if (eitherCapTypeFound.right()
4269                                         .value() == StorageOperationStatus.NOT_FOUND) {
4270                                 BeEcompErrorManager.getInstance()
4271                                                 .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type",
4272                                                                 type);
4273                                 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type,
4274                                                 resource.getName());
4275                                 BeEcompErrorManager.getInstance()
4276                                                 .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
4277                         }
4278                         log.debug("Trying to get capability type {} failed with error: {}", type, eitherCapTypeFound.right()
4279                                         .value()
4280                                         .name());
4281                         ResponseFormat errorResponse = null;
4282                         if (type != null) {
4283                                 errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
4284                         } else {
4285                                 errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE,
4286                                                 validationObjects);
4287                         }
4288                         eitherResult = Either.right(errorResponse);
4289                         componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4290                 }
4291                 return eitherResult;
4292         }
4293
4294         private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
4295                                                                                                                                                  ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
4296                                                                                                                                                  Either<Boolean, ResponseFormat> eitherResult, Entry<String, List<CapabilityDefinition>> typeEntry,
4297                                                                                                                                                  boolean inTransaction) {
4298                 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
4299                                 .getCapabilityType(typeEntry.getKey(), inTransaction);
4300                 if (eitherCapTypeFound.isRight()) {
4301                         if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
4302                                 BeEcompErrorManager.getInstance()
4303                                                 .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type",
4304                                                                 typeEntry.getKey());
4305                                 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB",
4306                                                 typeEntry.getKey(), resource.getName());
4307                                 BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
4308                         }
4309                         log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(),
4310                                         eitherCapTypeFound.right().value().name());
4311                         ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE,
4312                                         typeEntry.getKey());
4313                         componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4314                         return Either.right(errorResponse);
4315                 }
4316                 CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
4317                 if (capabilityTypeDefinition.getProperties() != null) {
4318                         for (CapabilityDefinition capDef : typeEntry.getValue()) {
4319                                 List<ComponentInstanceProperty> properties = capDef.getProperties();
4320                                 List<ComponentInstanceProperty> changedProperties = new ArrayList<>();
4321                                 if (properties == null || properties.isEmpty()) {
4322                                         for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
4323                                                 ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
4324                                                 changedProperties.add(newProp);
4325                                         }
4326                                 } else {
4327                                         List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
4328                                         for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
4329                                                 PropertyDefinition propFromDef = prop.getValue();
4330                                                 boolean propFound = false;
4331                                                 for (ComponentInstanceProperty cip : properties) {
4332                                                         if (propFromDef.getName().equals(cip.getName())) {
4333                                                                 //merge property value and property description only, ignore other fields
4334                                                                 if(cip.getDescription() != null && !cip.getDescription().equals(propFromDef.getDescription())){
4335                                                                         propFromDef.setDescription(cip.getDescription());
4336                                                                 }
4337                                                                 propertyDataValueMergeBusinessLogic.mergePropertyValue(propFromDef, cip, new ArrayList<>());
4338                                                                 if(cip.getValue() != null){
4339                                                                         propFromDef.setValue(cip.getValue());
4340                                                                 }
4341                                                                 propsToAdd.add(new ComponentInstanceProperty(propFromDef));
4342                                                                 propFound = true;
4343                                                                 properties.remove(cip);
4344                                                                 break;
4345                                                         }
4346                                                 }
4347                                                 if(!propFound) {
4348                                                         propsToAdd.add(new ComponentInstanceProperty(propFromDef));
4349                                                 }
4350                                         }
4351                                         if (!propsToAdd.isEmpty()) {
4352                                                 changedProperties.addAll(propsToAdd);
4353                                         }
4354                                 }
4355                                 capDef.setProperties(changedProperties);
4356                         }
4357                 }
4358                 return eitherResult;
4359         }
4360
4361         public Resource createResourceByDao(Resource resource, User user, AuditingActionEnum actionEnum,
4362                                                                                 boolean isNormative, boolean inTransaction) {
4363                 // create resource
4364
4365                 // lock new resource name in order to avoid creation resource with same
4366                 // name
4367                 Resource createdResource = null;
4368                 if (!inTransaction) {
4369                         Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
4370                                         CREATE_RESOURCE);
4371                         if (lockResult.isRight()) {
4372                                 ResponseFormat responseFormat = lockResult.right().value();
4373                                 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4374                                 throw new ByResponseFormatComponentException(responseFormat);
4375                         }
4376
4377                         log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
4378                 }
4379                 try {
4380                         if (resource.deriveFromGeneric()) {
4381                                 handleResourceGenericType(resource);
4382                         }
4383                         createdResource = createResourceTransaction(resource, user, isNormative);
4384                         componentsUtils.auditResource(componentsUtils.getResponseFormat(ActionStatus.CREATED), user,
4385                                         createdResource, actionEnum);
4386                         ASDCKpiApi.countCreatedResourcesKPI();
4387                 } catch (ComponentException e) {
4388                         ResponseFormat responseFormat = e.getResponseFormat() == null
4389                                         ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
4390                         componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4391                         throw e;
4392                 } catch (StorageException e) {
4393                         ResponseFormat responseFormat = componentsUtils
4394                                         .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
4395                         componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4396                         throw e;
4397                 } finally {
4398                         if (!inTransaction) {
4399                                 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
4400                                                 NodeTypeEnum.Resource);
4401                         }
4402                 }
4403                 return createdResource;
4404         }
4405
4406         private Resource createResourceTransaction(Resource resource, User user, boolean isNormative) {
4407                 // validate resource name uniqueness
4408                 log.debug("validate resource name");
4409                 Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(
4410                                 resource.getName(), resource.getResourceType(), resource.getComponentType());
4411                 if (eitherValidation.isRight()) {
4412                         loggerSupportability.log(LoggerSupportabilityActions.VALIDATE_NAME,resource.getComponentMetadataForSupportLog(),
4413                                         StatusCode.ERROR,"ERROR while validate component name {} Status is: {}",resource.getName(),eitherValidation.right().value());
4414                         log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(),
4415                                         eitherValidation.right()
4416                                                         .value());
4417                         throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(eitherValidation.right()
4418                                         .value()));
4419                 }
4420                 if (eitherValidation.left()
4421                                 .value()) {
4422                         log.debug("resource with name: {}, already exists", resource.getName());
4423                         loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(),
4424                                         StatusCode.ERROR,"resource with name: {} already exists",resource.getName());
4425                         throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
4426                                         ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
4427                 }
4428
4429                 log.debug("send resource {} to dao for create", resource.getName());
4430
4431                 createArtifactsPlaceHolderData(resource, user);
4432                 // enrich object
4433                 if (!isNormative) {
4434                         log.debug("enrich resource with creator, version and state");
4435                         resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
4436                         resource.setVersion(INITIAL_VERSION);
4437                         resource.setHighestVersion(true);
4438                         if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC) {
4439                                 resource.setAbstract(false);
4440                         }
4441                 }
4442                 return toscaOperationFacade.createToscaComponent(resource)
4443                                 .left()
4444                                 .on(r -> throwComponentExceptionByResource(r, resource));
4445         }
4446
4447         private Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) {
4448                 ResponseFormat responseFormat = componentsUtils
4449                                 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status), resource);
4450                 throw new ByResponseFormatComponentException(responseFormat);
4451         }
4452
4453         private void createArtifactsPlaceHolderData(Resource resource, User user) {
4454                 // create mandatory artifacts
4455
4456                 // TODO it must be removed after that artifact uniqueId creation will be
4457                 // moved to ArtifactOperation
4458
4459                 setInformationalArtifactsPlaceHolder(resource, user);
4460                 setDeploymentArtifactsPlaceHolder(resource, user);
4461                 setToscaArtifactsPlaceHolders(resource, user);
4462         }
4463
4464         @SuppressWarnings("unchecked")
4465         @Override
4466         public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
4467                 Resource resource = (Resource) component;
4468                 Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
4469                 if (artifactMap == null) {
4470                         artifactMap = new HashMap<>();
4471                 }
4472                 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
4473                                 .getConfiguration()
4474                                 .getDeploymentResourceArtifacts();
4475                 if (deploymentResourceArtifacts != null) {
4476                         Map<String, ArtifactDefinition> finalArtifactMap = artifactMap;
4477                         deploymentResourceArtifacts
4478                                         .forEach((k, v) -> processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k, v));
4479                 }
4480                 resource.setDeploymentArtifacts(artifactMap);
4481         }
4482
4483         private void processDeploymentResourceArtifacts(User user, Resource resource,
4484                                                                                                         Map<String, ArtifactDefinition> artifactMap, String k, Object v) {
4485                 boolean shouldCreateArtifact = true;
4486                 Map<String, Object> artifactDetails = (Map<String, Object>) v;
4487                 Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
4488                 if (object != null) {
4489                         List<String> artifactTypes = (List<String>) object;
4490                         if (!artifactTypes.contains(resource.getResourceType()
4491                                         .name())) {
4492                                 shouldCreateArtifact = false;
4493                                 return;
4494                         }
4495                 } else {
4496                         log.info("resource types for artifact placeholder {} were not defined. default is all resources", k);
4497                 }
4498                 if (shouldCreateArtifact) {
4499                         if (artifactsBusinessLogic != null) {
4500                                 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
4501                                                 resource.getUniqueId(), k, (Map<String, Object>) v, user, ArtifactGroupTypeEnum.DEPLOYMENT);
4502                                 if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
4503                                         artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
4504                                 }
4505                         }
4506                 }
4507         }
4508
4509         @SuppressWarnings("unchecked")
4510         private void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
4511                 Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
4512                 if (artifactMap == null) {
4513                         artifactMap = new HashMap<>();
4514                 }
4515                 String resourceUniqueId = resource.getUniqueId();
4516                 List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager()
4517                                 .getConfiguration()
4518                                 .getExcludeResourceCategory();
4519                 List<String> exludeResourceType = ConfigurationManager.getConfigurationManager()
4520                                 .getConfiguration()
4521                                 .getExcludeResourceType();
4522                 Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager()
4523                                 .getConfiguration()
4524                                 .getInformationalResourceArtifacts();
4525                 List<CategoryDefinition> categories = resource.getCategories();
4526                 boolean isCreateArtifact = true;
4527                 if (exludeResourceCategory != null) {
4528                         String category = categories.get(0)
4529                                         .getName();
4530                         isCreateArtifact = exludeResourceCategory.stream()
4531                                         .noneMatch(e -> e.equalsIgnoreCase(category));
4532                 }
4533                 if (isCreateArtifact && exludeResourceType != null) {
4534                         String resourceType = resource.getResourceType()
4535                                         .name();
4536                         isCreateArtifact = exludeResourceType.stream()
4537                                         .noneMatch(e -> e.equalsIgnoreCase(resourceType));
4538                 }
4539                 if (informationalResourceArtifacts != null && isCreateArtifact) {
4540                         Set<String> keys = informationalResourceArtifacts.keySet();
4541                         for (String informationalResourceArtifactName : keys) {
4542                                 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts
4543                                                 .get(informationalResourceArtifactName);
4544                                 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
4545                                                 resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
4546                                                 ArtifactGroupTypeEnum.INFORMATIONAL);
4547                                 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
4548
4549                         }
4550                 }
4551                 resource.setArtifacts(artifactMap);
4552         }
4553
4554         /**
4555          * deleteResource
4556          *
4557          * @param resourceId
4558          * @param user
4559          * @return
4560          */
4561         public ResponseFormat deleteResource(String resourceId, User user) {
4562                 ResponseFormat responseFormat;
4563                 validateUserExists(user);
4564
4565                 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId);
4566                 if (resourceStatus.isRight()) {
4567                         log.debug("failed to get resource {}", resourceId);
4568                         return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right()
4569                                         .value()), "");
4570                 }
4571
4572                 Resource resource = resourceStatus.left()
4573                                 .value();
4574
4575                 StorageOperationStatus result = StorageOperationStatus.OK;
4576                 lockComponent(resourceId, resource, "Mark resource to delete");
4577                 try {
4578
4579                         result = markComponentToDelete(resource);
4580                         if (result == StorageOperationStatus.OK) {
4581                                 responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
4582                         } else {
4583                                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
4584                                 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
4585                         }
4586                         return responseFormat;
4587
4588                 } finally {
4589                         if (result == null || result != StorageOperationStatus.OK) {
4590                                 janusGraphDao.rollback();
4591                         } else {
4592                 janusGraphDao.commit();
4593                         }
4594                         graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
4595                 }
4596
4597         }
4598
4599         public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) {
4600                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
4601                 validateUserExists(user);
4602                 Resource resource = null;
4603                 StorageOperationStatus result = StorageOperationStatus.OK;
4604                 boolean failed = false;
4605                 try {
4606
4607                         Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade
4608                                         .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version);
4609                         if (resourceStatus.isRight()) {
4610                                 log.debug("failed to get resource {} version {}", resourceName, version);
4611                                 return componentsUtils
4612                                                 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceStatus.right()
4613                                                                 .value()), resourceName);
4614                         }
4615
4616                         resource = resourceStatus.left()
4617                                         .value();
4618
4619                 } finally {
4620                         janusGraphDao.commit();
4621                 }
4622                 if (resource != null) {
4623                         lockComponent(resource.getUniqueId(), resource, DELETE_RESOURCE);
4624                         try {
4625                                 result = markComponentToDelete(resource);
4626                                 if (result != StorageOperationStatus.OK) {
4627                                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
4628                                         responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
4629                                         return responseFormat;
4630                                 }
4631                         }catch (ComponentException e){
4632                                 failed = true;
4633                                 throw e;
4634                         }finally {
4635                                 if (failed || result == null || result != StorageOperationStatus.OK) {
4636                                         janusGraphDao.rollback();
4637                                 } else {
4638                     janusGraphDao.commit();
4639                                 }
4640                                 graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource);
4641                         }
4642                 }
4643                 return responseFormat;
4644         }
4645
4646         public Either<Resource, ResponseFormat> getResource(String resourceId, User user) {
4647
4648                 if (user != null) {
4649                         validateUserExists(user);
4650                 }
4651
4652                 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId);
4653                 if (storageStatus.isRight()) {
4654                         log.debug("failed to get resource by id {}", resourceId);
4655                         return Either.right(componentsUtils
4656                                         .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right()
4657                                                         .value()), resourceId));
4658                 }
4659                 if (!(storageStatus.left()
4660                                 .value() instanceof Resource)) {
4661                         return Either.right(componentsUtils.getResponseFormatByResource(
4662                                         componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId));
4663                 }
4664                 return Either.left(storageStatus.left()
4665                                 .value());
4666
4667         }
4668
4669         public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion,
4670                                                                                                                                                 String userId) {
4671
4672                 validateUserExists(userId);
4673
4674                 Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade
4675                                 .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion);
4676                 if (getResource.isRight()) {
4677                         log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion);
4678                         return Either.right(componentsUtils
4679                                         .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResource.right()
4680                                                         .value()), resourceName));
4681                 }
4682                 return Either.left(getResource.left()
4683                                 .value());
4684         }
4685
4686         /**
4687          * updateResourceMetadata
4688          *
4689          * @param user
4690          *            - modifier data (userId)
4691          * @param inTransaction
4692          *            TODO
4693          * @param resourceIdToUpdate
4694          *            - the resource identifier
4695          * @param newResource
4696          * @return Either<Resource , responseFormat>
4697          */
4698         public Resource updateResourceMetadata(String resourceIdToUpdate, Resource newResource, Resource currentResource,
4699                                                                                    User user, boolean inTransaction) {
4700
4701                 validateUserExists(user.getUserId());
4702
4703                 log.debug("Get resource with id {}", resourceIdToUpdate);
4704                 boolean needToUnlock = false;
4705
4706                 try {
4707                         if (currentResource == null) {
4708                                 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade
4709                                                 .getToscaElement(resourceIdToUpdate);
4710                                 if (storageStatus.isRight()) {
4711                                         throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatByResource(
4712                                                         componentsUtils.convertFromStorageResponse(storageStatus.right()
4713                                                                         .value()),
4714                                                         ""));
4715                                 }
4716
4717                                 currentResource = storageStatus.left()
4718                                                 .value();
4719                         }
4720                         // verify that resource is checked-out and the user is the last
4721                         // updater
4722                         if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) {
4723                                 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
4724                         }
4725
4726                         // lock resource
4727                         StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate,
4728                                         NodeTypeEnum.Resource);
4729                         if (lockResult != StorageOperationStatus.OK) {
4730                                 BeEcompErrorManager.getInstance()
4731                                                 .logBeFailedLockObjectError("Upload Artifact - lock ", NodeTypeEnum.Resource.getName(),
4732                                                                 resourceIdToUpdate);
4733                                 log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult);
4734                                 ResponseFormat responseFormat = componentsUtils
4735                                                 .getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
4736                                 throw new ByResponseFormatComponentException(responseFormat);
4737                         }
4738
4739                         needToUnlock = true;
4740
4741                         // critical section starts here
4742                         // convert json to object
4743
4744                         // Update and updated resource must have a non-empty "derivedFrom"
4745                         // list
4746                         // This code is not called from import resources, because of root
4747                         // VF "derivedFrom" should be null (or ignored)
4748                         if (ModelConverter.isAtomicComponent(currentResource)) {
4749                                 validateDerivedFromNotEmpty(null, newResource, null);
4750                                 validateDerivedFromNotEmpty(null, currentResource, null);
4751                         } else {
4752                                 newResource.setDerivedFrom(null);
4753                         }
4754
4755             Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource,
4756                     user, currentResource, false, true);
4757             if (dataModelResponse.isRight()) {
4758                 log.debug("failed to update resource metadata!!!");
4759                 throw new ByResponseFormatComponentException(dataModelResponse.right().value());
4760             }
4761
4762                         log.debug("Resource metadata updated successfully!!!");
4763                         return dataModelResponse.left()
4764                                         .value();
4765
4766                 } catch (ComponentException | StorageException e) {
4767                         rollback(inTransaction, newResource, null, null);
4768                         throw e;
4769                 } finally {
4770                         if (!inTransaction) {
4771                 janusGraphDao.commit();
4772                         }
4773                         if (needToUnlock) {
4774                                 graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
4775                         }
4776                 }
4777         }
4778
4779         private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource,
4780                                                                                                                                         User user, Resource currentResource, boolean shouldLock, boolean inTransaction) {
4781                 updateVfModuleGroupsNames(currentResource, newResource);
4782                 validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction, false);
4783                 // Setting last updater and uniqueId
4784                 newResource.setContactId(newResource.getContactId()
4785                                 .toLowerCase());
4786                 newResource.setLastUpdaterUserId(user.getUserId());
4787                 newResource.setUniqueId(resourceIdToUpdate);
4788                 // Cannot set highest version through UI
4789                 newResource.setHighestVersion(currentResource.isHighestVersion());
4790                 newResource.setCreationDate(currentResource.getCreationDate());
4791
4792                 Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource,
4793                                 newResource, user.getUserId(), inTransaction);
4794
4795                 if (processUpdateOfDerivedFrom.isRight()) {
4796                         log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate);
4797                         return Either.right(processUpdateOfDerivedFrom.right()
4798                                         .value());
4799                 }
4800
4801                 log.debug("send resource {} to dao for update", newResource.getUniqueId());
4802                 if (isNotEmpty(newResource.getGroups())) {
4803                         for (GroupDefinition group : newResource.getGroups()) {
4804                                 if (DEFAULT_GROUP_VF_MODULE.equals(group.getType())) {
4805                                         groupBusinessLogic.validateAndUpdateGroupMetadata(newResource.getComponentMetadataDefinition()
4806                                                         .getMetadataDataDefinition()
4807                                                         .getUniqueId(), user, newResource.getComponentType(), group, true, false);
4808                                 }
4809                         }
4810                 }
4811                 Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade
4812                                 .updateToscaElement(newResource);
4813
4814                 if (dataModelResponse.isRight()) {
4815                         ResponseFormat responseFormat = componentsUtils
4816                                         .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(dataModelResponse.right()
4817                                                         .value()), newResource);
4818                         return Either.right(responseFormat);
4819                 } else if (dataModelResponse.left()
4820                                 .value() == null) {
4821                         log.debug("No response from updateResource");
4822                         return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4823                 }
4824                 return Either.left(dataModelResponse.left()
4825                                 .value());
4826         }
4827
4828         private void updateVfModuleGroupsNames(Resource currentResource, Resource newResource) {
4829                 if (currentResource.getGroups() != null && !currentResource.getName()
4830                                 .equals(newResource.getName())) {
4831                         List<GroupDefinition> updatedGroups = currentResource.getGroups()
4832                                         .stream()
4833                                         .map(group -> getUpdatedGroup(group, currentResource.getName(), newResource.getName()))
4834                                         .collect(toList());
4835                         newResource.setGroups(updatedGroups);
4836                 }
4837         }
4838
4839         private GroupDefinition getUpdatedGroup(GroupDefinition currGroup, String replacePattern, String with) {
4840                 GroupDefinition updatedGroup = new GroupDefinition(currGroup);
4841                 if (updatedGroup.isSamePrefix(replacePattern) && updatedGroup.getType()
4842                                 .equals(DEFAULT_GROUP_VF_MODULE)) {
4843                         String prefix = updatedGroup.getName()
4844                                         .substring(0, replacePattern.length());
4845                         String newGroupName = updatedGroup.getName()
4846                                         .replaceFirst(prefix, with);
4847                         updatedGroup.setName(newGroupName);
4848                 }
4849                 return updatedGroup;
4850         }
4851
4852         /**
4853          * validateResourceFieldsBeforeCreate
4854          *
4855          * @param user
4856          *            - modifier data (userId)
4857          */
4858         private void validateResourceFieldsBeforeCreate(User user, Resource resource,
4859                                                                                                         AuditingActionEnum actionEnum, boolean inTransaction) {
4860                 componentValidator.validate(user, resource, actionEnum);
4861                 // validate category
4862                 log.debug("validate category");
4863                 validateCategory(user, resource, actionEnum, inTransaction);
4864                 // validate vendor name & release & model number
4865                 log.debug("validate vendor name");
4866                 validateVendorName(user, resource, actionEnum);
4867                 log.debug("validate vendor release");
4868                 validateVendorReleaseName(user, resource, actionEnum);
4869                 log.debug("validate resource vendor model number");
4870                 validateResourceVendorModelNumber(user, resource, actionEnum);
4871                 // validate cost
4872                 log.debug("validate cost");
4873                 validateCost(resource);
4874                 // validate licenseType
4875                 log.debug("validate licenseType");
4876                 validateLicenseType(user, resource, actionEnum);
4877                 // validate template (derived from)
4878                 log.debug("validate derived from");
4879                 if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
4880                         resource.setDerivedFrom(null);
4881                 }
4882                 validateDerivedFromExist(user, resource, actionEnum);
4883                 // warn about non-updatable fields
4884                 checkComponentFieldsForOverrideAttempt(resource);
4885                 String currentCreatorFullName = resource.getCreatorFullName();
4886                 if (currentCreatorFullName != null) {
4887                         log.debug("Resource Creator fullname is automatically set and cannot be updated");
4888                 }
4889
4890                 String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
4891                 if (currentLastUpdaterFullName != null) {
4892                         log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
4893                 }
4894
4895                 Long currentLastUpdateDate = resource.getLastUpdateDate();
4896                 if (currentLastUpdateDate != null) {
4897                         log.debug("Resource last update date is automatically set and cannot be updated");
4898                 }
4899
4900                 Boolean currentAbstract = resource.isAbstract();
4901                 if (currentAbstract != null) {
4902                         log.debug("Resource abstract is automatically set and cannot be updated");
4903                 }
4904         }
4905
4906         /**
4907          * validateResourceFieldsBeforeUpdate
4908          *
4909          * @param currentResource
4910          *            - Resource object to validate
4911          * @param isNested
4912          */
4913         private void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource,
4914                                                                                                         boolean inTransaction, boolean isNested) {
4915                 validateFields(currentResource, updateInfoResource, inTransaction, isNested);
4916                 warnNonEditableFields(currentResource, updateInfoResource);
4917         }
4918
4919         private void warnNonEditableFields(Resource currentResource, Resource updateInfoResource) {
4920                 String currentResourceVersion = currentResource.getVersion();
4921                 String updatedResourceVersion = updateInfoResource.getVersion();
4922
4923                 if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) {
4924                         log.debug("Resource version is automatically set and cannot be updated");
4925                 }
4926
4927                 String currentCreatorUserId = currentResource.getCreatorUserId();
4928                 String updatedCreatorUserId = updateInfoResource.getCreatorUserId();
4929
4930                 if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) {
4931                         log.debug("Resource Creator UserId is automatically set and cannot be updated");
4932                 }
4933
4934                 String currentCreatorFullName = currentResource.getCreatorFullName();
4935                 String updatedCreatorFullName = updateInfoResource.getCreatorFullName();
4936
4937                 if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) {
4938                         log.debug("Resource Creator fullname is automatically set and cannot be updated");
4939                 }
4940
4941                 String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId();
4942                 String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId();
4943
4944                 if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) {
4945                         log.debug("Resource LastUpdater userId is automatically set and cannot be updated");
4946                 }
4947
4948                 String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName();
4949                 String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName();
4950
4951                 if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) {
4952                         log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
4953                 }
4954                 Long currentCreationDate = currentResource.getCreationDate();
4955                 Long updatedCreationDate = updateInfoResource.getCreationDate();
4956
4957                 if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) {
4958                         log.debug("Resource Creation date is automatically set and cannot be updated");
4959                 }
4960
4961                 Long currentLastUpdateDate = currentResource.getLastUpdateDate();
4962                 Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate();
4963
4964                 if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) {
4965                         log.debug("Resource last update date is automatically set and cannot be updated");
4966                 }
4967
4968                 LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState();
4969                 LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState();
4970
4971                 if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) {
4972                         log.debug("Resource lifecycle state date is automatically set and cannot be updated");
4973                 }
4974
4975                 Boolean currentAbstract = currentResource.isAbstract();
4976                 Boolean updatedAbstract = updateInfoResource.isAbstract();
4977
4978                 if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) {
4979                         log.debug("Resource abstract is automatically set and cannot be updated");
4980                 }
4981
4982                 Boolean currentHighestVersion = currentResource.isHighestVersion();
4983                 Boolean updatedHighestVersion = updateInfoResource.isHighestVersion();
4984
4985                 if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) {
4986                         log.debug("Resource highest version is automatically set and cannot be updated");
4987                 }
4988
4989                 String currentUuid = currentResource.getUUID();
4990                 String updatedUuid = updateInfoResource.getUUID();
4991
4992                 if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) {
4993                         log.debug("Resource UUID is automatically set and cannot be updated");
4994                 }
4995
4996                 log.debug("Resource Type  cannot be updated");
4997                 String currentInvariantUuid = currentResource.getInvariantUUID();
4998                 String updatedInvariantUuid = updateInfoResource.getInvariantUUID();
4999
5000                 if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
5001                         log.debug("Resource invariant UUID is automatically set and cannot be updated");
5002                         updateInfoResource.setInvariantUUID(currentInvariantUuid);
5003                 }
5004         }
5005
5006         private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction,
5007                                                                 boolean isNested) {
5008                 boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
5009                 log.debug("validate resource name before update");
5010                 validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested);
5011                 log.debug("validate description before update");
5012                 componentDescriptionValidator.validateAndCorrectField(null, updateInfoResource, null);
5013                 log.debug("validate icon before update");
5014                 validateIcon(currentResource, updateInfoResource, hasBeenCertified);
5015                 log.debug("validate tags before update");
5016                 componentTagsValidator.validateAndCorrectField(null, updateInfoResource, null);
5017                 log.debug("validate vendor name before update");
5018                 validateVendorName(null, updateInfoResource, null);
5019                 log.debug("validate resource vendor model number before update");
5020                 validateResourceVendorModelNumber(currentResource, updateInfoResource);
5021                 log.debug("validate vendor release before update");
5022                 validateVendorReleaseName(null, updateInfoResource, null);
5023                 log.debug("validate contact info before update");
5024                 componentContactIdValidator.validateAndCorrectField(null, updateInfoResource, null);
5025                 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
5026                 validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified);
5027                 log.debug("validate category before update");
5028                 validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction);
5029         }
5030
5031         private boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) {
5032                 String resourceNameUpdated = updateInfoResource.getName();
5033                 String resourceNameCurrent = currentResource.getName();
5034                 if (resourceNameCurrent.equals(resourceNameUpdated)) {
5035                         return true;
5036                 }
5037                 // In case of CVFC type we should support the case of old VF with CVFC
5038                 // instances that were created without the "Cvfc" suffix
5039                 return currentResource.getResourceType() == ResourceTypeEnum.CVFC
5040                                 && resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent));
5041         }
5042
5043         private String addCvfcSuffixToResourceName(String resourceName) {
5044                 return resourceName + "Cvfc";
5045         }
5046
5047         private void validateResourceName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified,
5048                                                                           boolean isNested) {
5049                 String resourceNameUpdated = updateInfoResource.getName();
5050                 if (!isResourceNameEquals(currentResource, updateInfoResource)) {
5051                         if (isNested || !hasBeenCertified) {
5052                                 componentNameValidator.validateAndCorrectField(null, updateInfoResource, null);
5053                                 validateResourceNameUniqueness(updateInfoResource);
5054                                 currentResource.setName(resourceNameUpdated);
5055                                 currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
5056                                 currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
5057
5058                         } else {
5059                                 log.info("Resource name: {}, cannot be updated once the resource has been certified once.",
5060                                                 resourceNameUpdated);
5061                                 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
5062                         }
5063                 }
5064         }
5065
5066         private void validateIcon(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
5067                 String iconUpdated = updateInfoResource.getIcon();
5068                 String iconCurrent = currentResource.getIcon();
5069                 if (!iconCurrent.equals(iconUpdated)) {
5070                         if (!hasBeenCertified) {
5071                                 componentIconValidator.validateAndCorrectField(null, updateInfoResource, null);
5072                         } else {
5073                                 log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated);
5074                                 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
5075                         }
5076                 }
5077         }
5078
5079         private void validateResourceVendorModelNumber(Resource currentResource, Resource updateInfoResource) {
5080                 String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber();
5081                 String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber();
5082                 if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) {
5083                         validateResourceVendorModelNumber(null, updateInfoResource, null);
5084                 }
5085         }
5086
5087         private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource,
5088                                                                                                                          boolean hasBeenCertified, boolean inTransaction) {
5089                 validateCategory(null, updateInfoResource, null, inTransaction);
5090                 if (hasBeenCertified) {
5091                         CategoryDefinition currentCategory = currentResource.getCategories()
5092                                         .get(0);
5093                         SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories()
5094                                         .get(0);
5095                         CategoryDefinition updateCategory = updateInfoResource.getCategories()
5096                                         .get(0);
5097                         SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories()
5098                                         .get(0);
5099                         if (!currentCategory.getName()
5100                                         .equals(updateCategory.getName())
5101                                         || !currentSubCategory.getName()
5102                                         .equals(updtaeSubCategory.getName())) {
5103                                 log.info("Category {} cannot be updated once the resource has been certified once.",
5104                                                 currentResource.getCategories());
5105                                 ResponseFormat errorResponse = componentsUtils
5106                                                 .getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
5107                                 return Either.right(errorResponse);
5108                         }
5109                 }
5110                 return Either.left(true);
5111         }
5112
5113         private Either<Boolean, ResponseFormat> validateDerivedFromDuringUpdate(Resource currentResource,
5114                                                                                                                                                         Resource updateInfoResource, boolean hasBeenCertified) {
5115
5116                 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
5117                 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
5118                 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
5119                                 || updatedDerivedFrom.isEmpty()) {
5120                         log.trace("Update normative types");
5121                         return Either.left(true);
5122                 }
5123
5124                 String derivedFromCurrent = currentDerivedFrom.get(0);
5125                 String derivedFromUpdated = updatedDerivedFrom.get(0);
5126
5127                 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
5128                         if (!hasBeenCertified) {
5129                                 validateDerivedFromExist(null, updateInfoResource, null);
5130                         } else {
5131                                 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
5132                                                 currentResource, updateInfoResource, null);
5133
5134                                 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left()
5135                                                 .value()) {
5136                                         log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
5137                                         return validateDerivedFromExtending;
5138                                 }
5139                         }
5140                 } else {
5141                         // For derived from, we must know whether it was actually changed,
5142                         // otherwise we must do no action.
5143                         // Due to changes it inflicts on data model (remove artifacts,
5144                         // properties...), it's not like a flat field which can be
5145                         // overwritten if not changed.
5146                         // So we must indicate that derived from is not changed
5147                         updateInfoResource.setDerivedFrom(null);
5148                 }
5149                 return Either.left(true);
5150         }
5151
5152         private Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource,
5153                                                                                                                                                                   Resource updateInfoResource, boolean hasBeenCertified) {
5154
5155                 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
5156                 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
5157                 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
5158                                 || updatedDerivedFrom.isEmpty()) {
5159                         log.trace("Update normative types");
5160                         return Either.left(true);
5161                 }
5162
5163                 String derivedFromCurrent = currentDerivedFrom.get(0);
5164                 String derivedFromUpdated = updatedDerivedFrom.get(0);
5165
5166                 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
5167                         if (!hasBeenCertified) {
5168                                 validateDerivedFromExist(null, updateInfoResource, null);
5169                         } else {
5170                                 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
5171                                                 currentResource, updateInfoResource, null);
5172
5173                                 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left()
5174                                                 .value()) {
5175                                         log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
5176                                         return validateDerivedFromExtending;
5177                                 }
5178                         }
5179                 }
5180                 return Either.left(true);
5181         }
5182
5183         private void validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) {
5184                 if (resource.getDerivedFrom() == null || resource.getDerivedFrom()
5185                                 .isEmpty()) {
5186                         return;
5187                 }
5188                 String templateName = resource.getDerivedFrom()
5189                                 .get(0);
5190                 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
5191                                 .validateToscaResourceNameExists(templateName);
5192                 if (dataModelResponse.isRight()) {
5193                         StorageOperationStatus storageStatus = dataModelResponse.right()
5194                                         .value();
5195                         BeEcompErrorManager.getInstance()
5196                                         .logBeDaoSystemError("Create Resource - validateDerivedFromExist");
5197                         log.debug("request to data model failed with error: {}", storageStatus);
5198                         ResponseFormat responseFormat = componentsUtils
5199                                         .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
5200                         log.trace("audit before sending response");
5201                         componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5202                         throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus));
5203                 } else if (!dataModelResponse.left()
5204                                 .value()) {
5205                         log.info("resource template with name: {}, does not exists", templateName);
5206                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
5207                         componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5208                         throw new ByActionStatusComponentException(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
5209                 }
5210         }
5211
5212         // Tal G for extending inheritance US815447
5213         private Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource,
5214                                                                                                                                                  Resource updateInfoResource, AuditingActionEnum actionEnum) {
5215                 String currentTemplateName = currentResource.getDerivedFrom()
5216                                 .get(0);
5217                 String updatedTemplateName = updateInfoResource.getDerivedFrom()
5218                                 .get(0);
5219
5220                 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
5221                                 .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName);
5222                 if (dataModelResponse.isRight()) {
5223                         StorageOperationStatus storageStatus = dataModelResponse.right()
5224                                         .value();
5225                         BeEcompErrorManager.getInstance()
5226                                         .logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
5227                         ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
5228                                         componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
5229                         log.trace("audit before sending response");
5230                         componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
5231                         return Either.right(responseFormat);
5232                 }
5233
5234                 if (!dataModelResponse.left()
5235                                 .value()) {
5236                         log.info("resource template with name {} does not inherit as original {}", updatedTemplateName,
5237                                         currentTemplateName);
5238                         ResponseFormat responseFormat = componentsUtils
5239                                         .getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
5240                         componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
5241
5242                         return Either.right(responseFormat);
5243
5244                 }
5245                 return Either.left(true);
5246         }
5247
5248         public void validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
5249                 log.debug("validate resource derivedFrom field");
5250                 if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom()
5251                                 .isEmpty())
5252                                 || (resource.getDerivedFrom()
5253                                 .get(0)) == null
5254                                 || (resource.getDerivedFrom()
5255                                 .get(0)
5256                                 .trim()
5257                                 .isEmpty())) {
5258                         log.info("derived from (template) field is missing for the resource");
5259                         ResponseFormat responseFormat = componentsUtils
5260                                         .getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
5261                         componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5262
5263                         throw new ByActionStatusComponentException(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
5264                 }
5265         }
5266
5267         private void validateResourceNameUniqueness(Resource resource) {
5268
5269                 Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade
5270                                 .validateComponentNameExists(resource.getName(), resource.getResourceType(),
5271                                                 resource.getComponentType());
5272                 if (resourceOperationResponse.isLeft() && resourceOperationResponse.left()
5273                                 .value()) {
5274                         log.debug("resource with name: {}, already exists", resource.getName());
5275                         throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
5276                                         ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
5277                 } else if (resourceOperationResponse.isRight()) {
5278                         log.debug("error while validateResourceNameExists for resource: {}", resource.getName());
5279                         throw new StorageException(resourceOperationResponse.right()
5280                                         .value());
5281                 }
5282         }
5283
5284         private void validateCategory(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
5285
5286                 List<CategoryDefinition> categories = resource.getCategories();
5287                 if (CollectionUtils.isEmpty(categories)) {
5288                         log.debug(CATEGORY_IS_EMPTY);
5289                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
5290                                         ComponentTypeEnum.RESOURCE.getValue());
5291                         componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5292                         throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
5293                                         ComponentTypeEnum.RESOURCE.getValue());
5294                 }
5295                 if (categories.size() > 1) {
5296                         log.debug("Must be only one category for resource");
5297                         throw new ByActionStatusComponentException(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES,
5298                                         ComponentTypeEnum.RESOURCE.getValue());
5299                 }
5300                 CategoryDefinition category = categories.get(0);
5301                 List<SubCategoryDefinition> subcategories = category.getSubcategories();
5302                 if (CollectionUtils.isEmpty(subcategories)) {
5303                         log.debug("Missinig subcategory for resource");
5304                         throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
5305                 }
5306                 if (subcategories.size() > 1) {
5307                         log.debug("Must be only one sub category for resource");
5308                         throw new ByActionStatusComponentException(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
5309                 }
5310
5311                 SubCategoryDefinition subcategory = subcategories.get(0);
5312
5313                 if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
5314                         log.debug(CATEGORY_IS_EMPTY);
5315                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
5316                                         ComponentTypeEnum.RESOURCE.getValue());
5317                         componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5318                         throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
5319                                         ComponentTypeEnum.RESOURCE.getValue());
5320                 }
5321                 if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
5322                         log.debug(CATEGORY_IS_EMPTY);
5323                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(
5324                                         ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
5325                         componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5326                         throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY,
5327                                         ComponentTypeEnum.RESOURCE.getValue());
5328                 }
5329
5330                 validateCategoryListed(category, subcategory, user, resource, actionEnum, inTransaction);
5331         }
5332
5333         private void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory, User user,
5334                                                                                 Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
5335                 ResponseFormat responseFormat;
5336                 if (category != null && subcategory != null) {
5337                         log.debug("validating resource category {} against valid categories list", category);
5338                         Either<List<CategoryDefinition>, ActionStatus> categories = elementDao
5339                                         .getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
5340                         if (categories.isRight()) {
5341                                 log.debug("failed to retrieve resource categories from JanusGraph");
5342                                 responseFormat = componentsUtils.getResponseFormat(categories.right()
5343                                                 .value());
5344                                 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5345                                 throw new ByActionStatusComponentException(categories.right()
5346                                                 .value());
5347                         }
5348                         List<CategoryDefinition> categoryList = categories.left()
5349                                         .value();
5350                         Optional<CategoryDefinition> foundCategory = categoryList.stream()
5351                                         .filter(cat -> cat.getName()
5352                                                         .equals(category.getName()))
5353                                         .findFirst();
5354                         if (!foundCategory.isPresent()) {
5355                                 log.debug("Category {} is not part of resource category group. Resource category valid values are {}",
5356                                                 category, categoryList);
5357                                 failOnInvalidCategory(user, resource, actionEnum);
5358                         }
5359                         Optional<SubCategoryDefinition> foundSubcategory = foundCategory.get()
5360                                         .getSubcategories()
5361                                         .stream()
5362                                         .filter(subcat -> subcat.getName()
5363                                                         .equals(subcategory.getName()))
5364                                         .findFirst();
5365                         if (!foundSubcategory.isPresent()) {
5366                                 log.debug(
5367                                                 "SubCategory {} is not part of resource category group. Resource subcategory valid values are {}",
5368                                                 subcategory, foundCategory.get()
5369                                                                 .getSubcategories());
5370                                 failOnInvalidCategory(user, resource, actionEnum);
5371                         }
5372                 }
5373         }
5374
5375         private void failOnInvalidCategory(User user, Resource resource, AuditingActionEnum actionEnum) {
5376                 ResponseFormat responseFormat;
5377                 responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY,
5378                                 ComponentTypeEnum.RESOURCE.getValue());
5379                 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5380                 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
5381         }
5382
5383         public void validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) {
5384                 String vendorRelease = resource.getVendorRelease();
5385                 log.debug("validate vendor relese name");
5386                 if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) {
5387                         log.info("vendor relese name is missing.");
5388                         ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
5389                         componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5390                         throw new ByActionStatusComponentException(ActionStatus.MISSING_VENDOR_RELEASE);
5391                 }
5392
5393                 validateVendorReleaseName(vendorRelease, user, resource, actionEnum);
5394         }
5395
5396         public void validateVendorReleaseName(String vendorRelease, User user, Resource resource,
5397                                                                                   AuditingActionEnum actionEnum) {
5398                 if (vendorRelease != null) {
5399                         if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
5400                                 log.info("vendor release exceds limit.");
5401                                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
5402                                                 ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
5403                                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5404                                 throw new ByActionStatusComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT,
5405                                                 "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
5406                         }
5407
5408                         if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
5409                                 log.info("vendor release  is not valid.");
5410                                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
5411                                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5412                 throw new ByActionStatusComponentException(ActionStatus.INVALID_VENDOR_RELEASE, vendorRelease);
5413             }
5414         }
5415     }
5416
5417     private void validateVendorName(User user, Resource resource,
5418                                     AuditingActionEnum actionEnum) {
5419         String vendorName = resource.getVendorName();
5420         if (!ValidationUtils.validateStringNotEmpty(vendorName)) {
5421             log.info("vendor name is missing.");
5422             ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME);
5423             componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5424             throw new ByActionStatusComponentException(ActionStatus.MISSING_VENDOR_NAME);
5425         }
5426         validateVendorName(vendorName, user, resource, actionEnum);
5427     }
5428
5429     private void validateVendorName(String vendorName, User user, Resource resource,
5430                                     AuditingActionEnum actionEnum) {
5431         if (vendorName != null) {
5432             if (!ValidationUtils.validateVendorNameLength(vendorName)) {
5433                 log.info("vendor name exceds limit.");
5434                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
5435                         "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
5436                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5437                 throw new ByActionStatusComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
5438                         "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
5439             }
5440
5441             if (!ValidationUtils.validateVendorName(vendorName)) {
5442                 log.info("vendor name  is not valid.");
5443                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
5444                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5445                 throw new ByActionStatusComponentException(ActionStatus.INVALID_VENDOR_NAME, vendorName);
5446             }
5447         }
5448     }
5449
5450     private void validateResourceVendorModelNumber(User user, Resource resource, AuditingActionEnum actionEnum) {
5451         String resourceVendorModelNumber = resource.getResourceVendorModelNumber();
5452         if (StringUtils.isNotEmpty(resourceVendorModelNumber)) {
5453             if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
5454                 log.info("resource vendor model number exceeds limit.");
5455                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
5456                         ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
5457                         "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
5458                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5459                 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
5460                         "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
5461             }
5462             // resource vendor model number is currently validated as vendor
5463             // name
5464             if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) {
5465                 log.info("resource vendor model number  is not valid.");
5466                 ResponseFormat errorResponse = componentsUtils
5467                         .getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
5468                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5469                 throw new ByActionStatusComponentException(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
5470             }
5471         }
5472     }
5473
5474
5475     private void validateCost(Resource resource) {
5476         String cost = resource.getCost();
5477         if (cost != null) {
5478             if (!ValidationUtils.validateCost(cost)) {
5479                 log.debug("resource cost is invalid.");
5480                 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
5481             }
5482         }
5483     }
5484
5485     private void validateLicenseType(User user, Resource resource,
5486                                      AuditingActionEnum actionEnum) {
5487         log.debug("validate licenseType");
5488         String licenseType = resource.getLicenseType();
5489         if (licenseType != null) {
5490             List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration()
5491                     .getLicenseTypes();
5492             if (!licenseTypes.contains(licenseType)) {
5493                 log.debug("License type {} isn't configured", licenseType);
5494                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
5495                 if (actionEnum != null) {
5496                     // In update case, no audit is required
5497                     componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5498                 }
5499                 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
5500             }
5501         }
5502     }
5503
5504         private Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom(Resource currentResource,
5505                                                                                                                                            Resource updatedResource, String userId, boolean inTransaction) {
5506                 if (updatedResource.getDerivedFrom() != null) {
5507                         log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId());
5508                         log.debug("1. Removing interface artifacts from graph");
5509                         // Remove all interface artifacts of resource
5510                         String resourceId = updatedResource.getUniqueId();
5511                         Map<String, InterfaceDefinition> interfaces = currentResource.getInterfaces();
5512
5513                         if (interfaces != null) {
5514                                 Collection<InterfaceDefinition> values = interfaces.values();
5515                                 for (InterfaceDefinition interfaceDefinition : values) {
5516                                         String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition);
5517
5518                                         log.trace("Starting interface artifacts removal for interface type {}", interfaceType);
5519                                         Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
5520                                         if (operations != null) {
5521                                                 for (Entry<String, Operation> operationEntry : operations.entrySet()) {
5522                                                         Operation operation = operationEntry.getValue();
5523                                                         ArtifactDefinition implementation = operation.getImplementationArtifact();
5524                                                         if (implementation != null) {
5525                                                                 String uniqueId = implementation.getUniqueId();
5526                                                                 log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}",
5527                                                                                 uniqueId, operationEntry.getKey(), interfaceType);
5528                                                                 // only thing that transacts and locks here
5529                                                                 Either<ArtifactDefinition, ResponseFormat> deleteArtifactByInterface =
5530                                                                         artifactsBusinessLogic.deleteArtifactByInterface(resourceId, userId, uniqueId, true);
5531                                                                 if (deleteArtifactByInterface.isRight()) {
5532                                                                         log.debug("Couldn't remove artifact definition with id {}", uniqueId);
5533                                                                         if (!inTransaction) {
5534                                                                                 janusGraphDao.rollback();
5535                                                                         }
5536                                                                         return Either.right(deleteArtifactByInterface.right()
5537                                                                                         .value());
5538                                                                 }
5539                                                         } else {
5540                                                                 log.trace("No implementation found for operation {} - nothing to delete",
5541                                                                                 operationEntry.getKey());
5542                                                         }
5543                                                 }
5544                                         } else {
5545                                                 log.trace("No operations found for interface type {}", interfaceType);
5546                                         }
5547                                 }
5548                         }
5549                         log.debug("2. Removing properties");
5550                         Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = propertyOperation
5551                                         .deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId);
5552
5553                         if (findPropertiesOfNode.isRight() && findPropertiesOfNode.right().value() != StorageOperationStatus.OK) {
5554                                 log.debug("Failed to remove all properties of resource");
5555                                 if (!inTransaction) {
5556                     janusGraphDao.rollback();
5557                                 }
5558                                 return Either.right(componentsUtils
5559                                                 .getResponseFormat(componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right()
5560                                                                 .value())));
5561                         }
5562
5563                 } else {
5564                         log.debug("Derived from wasn't changed during update");
5565                 }
5566
5567                 if (inTransaction) {
5568                         return Either.left(true);
5569                 }
5570         janusGraphDao.commit();
5571                 return Either.left(true);
5572
5573         }
5574
5575         /**** Auditing *******************/
5576
5577         protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) {
5578                 WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
5579                                 .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
5580
5581                 WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
5582
5583                 return webApplicationContext.getBean(class1);
5584         }
5585
5586         public ICapabilityTypeOperation getCapabilityTypeOperation() {
5587                 return capabilityTypeOperation;
5588         }
5589
5590         @Autowired
5591         public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) {
5592                 this.capabilityTypeOperation = capabilityTypeOperation;
5593         }
5594
5595         public Boolean validatePropertiesDefaultValues(Resource resource) {
5596                 log.debug("validate resource properties default values");
5597                 List<PropertyDefinition> properties = resource.getProperties();
5598                 if (properties != null) {
5599                         iterateOverProperties(properties);
5600                 }
5601                 return true;
5602         }
5603
5604         public void iterateOverProperties(List<PropertyDefinition> properties) {
5605                 String type = null;
5606                 String innerType = null;
5607                 for (PropertyDefinition property : properties) {
5608                         if (!propertyOperation.isPropertyTypeValid(property)) {
5609                                 log.info("Invalid type for property {}", property);
5610                                 throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY_TYPE,
5611                                                 property.getType(), property.getName());
5612                         }
5613
5614                         Map<String, DataTypeDefinition> allDataTypes = getAllDataTypes(applicationDataTypeCache);
5615                         type = property.getType();
5616
5617                         if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
5618                                 ResponseFormat responseFormat = validateMapOrListPropertyType(property, innerType, allDataTypes);
5619                                 if (responseFormat != null) {
5620                                         break;
5621                                 }
5622                         }
5623                         validateDefaultPropertyValue(property, allDataTypes, type, innerType);
5624                 }
5625         }
5626
5627         private void validateDefaultPropertyValue(PropertyDefinition property,
5628                                                                                           Map<String, DataTypeDefinition> allDataTypes, String type, String innerType) {
5629                 if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes)) {
5630                         log.info("Invalid default value for property {}", property);
5631                         ResponseFormat responseFormat;
5632                         if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
5633                                 throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE,
5634                                                 property.getName(), type, innerType, property.getDefaultValue());
5635                         }
5636                         throw new ByActionStatusComponentException(ActionStatus.INVALID_DEFAULT_VALUE,
5637                                         property.getName(), type, property.getDefaultValue());
5638                 }
5639         }
5640
5641         private ResponseFormat validateMapOrListPropertyType(PropertyDefinition property, String innerType,
5642                                                                                                                  Map<String, DataTypeDefinition> allDataTypes) {
5643                 ResponseFormat responseFormat = null;
5644                 ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property,
5645                                 allDataTypes);
5646                 innerType = propertyInnerTypeValid.getLeft();
5647                 if (!propertyInnerTypeValid.getRight()
5648                                 .booleanValue()) {
5649                         log.info("Invalid inner type for property {}", property);
5650                         responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType,
5651                                         property.getName());
5652                 }
5653                 return responseFormat;
5654         }
5655
5656         @Override
5657         public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
5658                 return deleteMarkedComponents(ComponentTypeEnum.RESOURCE);
5659         }
5660
5661         @Override
5662         public ComponentInstanceBusinessLogic getComponentInstanceBL() {
5663                 return componentInstanceBusinessLogic;
5664         }
5665
5666         private String getComponentTypeForResponse(Component component) {
5667                 String componentTypeForResponse = "SERVICE";
5668                 if (component instanceof Resource) {
5669                         componentTypeForResponse = ((Resource) component).getResourceType()
5670                                         .name();
5671                 }
5672                 return componentTypeForResponse;
5673         }
5674
5675         public Either<Resource, ResponseFormat> getLatestResourceFromCsarUuid(String csarUuid, User user) {
5676                 // validate user
5677                 if (user != null) {
5678                         validateUserExists(user);
5679                 }
5680                 // get resource from csar uuid
5681                 Either<Resource, StorageOperationStatus> either = toscaOperationFacade
5682                                 .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, "");
5683                 if (either.isRight()) {
5684                         ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND,
5685                                         csarUuid);
5686                         return Either.right(resp);
5687                 }
5688
5689                 return Either.left(either.left()
5690                                 .value());
5691         }
5692
5693         @Override
5694         public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(
5695                         String componentId, String userId) {
5696                 return null;
5697         }
5698
5699         private Map<String, List<CapabilityDefinition>> getValidComponentInstanceCapabilities(String resourceId,
5700                                                                                                                                                                                   Map<String, List<CapabilityDefinition>> defaultCapabilities,
5701                                                                                                                                                                                   Map<String, List<UploadCapInfo>> uploadedCapabilities) {
5702
5703                 Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
5704                 uploadedCapabilities.forEach((k, v) -> addValidComponentInstanceCapabilities(k, v, resourceId,
5705                                 defaultCapabilities, validCapabilitiesMap));
5706                 return validCapabilitiesMap;
5707         }
5708
5709         private void addValidComponentInstanceCapabilities(String key, List<UploadCapInfo> capabilities, String resourceId,
5710                                                                                                            Map<String, List<CapabilityDefinition>> defaultCapabilities,
5711                                                                                                            Map<String, List<CapabilityDefinition>> validCapabilitiesMap) {
5712                 String capabilityType = capabilities.get(0)
5713                                 .getType();
5714                 if (defaultCapabilities.containsKey(capabilityType)) {
5715                         CapabilityDefinition defaultCapability = getCapability(resourceId, defaultCapabilities, capabilityType);
5716                         validateCapabilityProperties(capabilities, resourceId, defaultCapability);
5717                         List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
5718                         validCapabilityList.add(defaultCapability);
5719                         validCapabilitiesMap.put(key, validCapabilityList);
5720                 } else {
5721                         throw new ByActionStatusComponentException(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType);
5722                 }
5723         }
5724
5725         private void validateCapabilityProperties(List<UploadCapInfo> capabilities, String resourceId,
5726                                                                                           CapabilityDefinition defaultCapability) {
5727                 if (CollectionUtils.isEmpty(defaultCapability.getProperties()) && isNotEmpty(capabilities.get(0)
5728                                 .getProperties())) {
5729                         log.debug("Failed to validate capability {} of component {}. Property list is empty. ",
5730                                         defaultCapability.getName(), resourceId);
5731                         log.debug("Failed to update capability property values. Property list of fetched capability {} is empty. ",
5732                                         defaultCapability.getName());
5733                         throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, resourceId);
5734                 } else if (isNotEmpty(capabilities.get(0)
5735                                 .getProperties())) {
5736                         validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, capabilities.get(0));
5737                 }
5738         }
5739
5740         private CapabilityDefinition getCapability(String resourceId,
5741                                                                                            Map<String, List<CapabilityDefinition>> defaultCapabilities, String capabilityType) {
5742                 CapabilityDefinition defaultCapability;
5743                 if (isNotEmpty(defaultCapabilities.get(capabilityType)
5744                                 .get(0)
5745                                 .getProperties())) {
5746                         defaultCapability = defaultCapabilities.get(capabilityType)
5747                                         .get(0);
5748                 } else {
5749                         Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade
5750                                         .getToscaFullElement(resourceId);
5751                         if (getFullComponentRes.isRight()) {
5752                                 log.debug("Failed to get full component {}. Status is {}. ", resourceId, getFullComponentRes.right()
5753                                                 .value());
5754                                 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NOT_FOUND, resourceId);
5755                         }
5756                         defaultCapability = getFullComponentRes.left()
5757                                         .value()
5758                                         .getCapabilities()
5759                                         .get(capabilityType)
5760                                         .get(0);
5761                 }
5762                 return defaultCapability;
5763         }
5764
5765         private void validateUniquenessUpdateUploadedComponentInstanceCapability(CapabilityDefinition defaultCapability,
5766                                                                                                                                                          UploadCapInfo uploadedCapability) {
5767                 List<ComponentInstanceProperty> validProperties = new ArrayList<>();
5768                 Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties()
5769                                 .stream()
5770                                 .collect(toMap(PropertyDefinition::getName, Function.identity()));
5771                 List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
5772                 for (UploadPropInfo property : uploadedProperties) {
5773                         String propertyName = property.getName()
5774                                         .toLowerCase();
5775                         String propertyType = property.getType();
5776                         ComponentInstanceProperty validProperty;
5777                         if (defaultProperties.containsKey(propertyName)
5778                                         && propertTypeEqualsTo(defaultProperties, propertyName, propertyType)) {
5779                                 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, propertyName);
5780                         }
5781                         validProperty = new ComponentInstanceProperty();
5782                         validProperty.setName(propertyName);
5783                         if (property.getValue() != null) {
5784                                 validProperty.setValue(property.getValue()
5785                                                 .toString());
5786                         }
5787                         validProperty.setDescription(property.getDescription());
5788                         validProperty.setPassword(property.isPassword());
5789                         validProperties.add(validProperty);
5790                 }
5791                 defaultCapability.setProperties(validProperties);
5792         }
5793
5794         private boolean propertTypeEqualsTo(Map<String, PropertyDefinition> defaultProperties, String propertyName,
5795                                                                                 String propertyType) {
5796                 return propertyType != null && !defaultProperties.get(propertyName)
5797                                 .getType()
5798                                 .equals(propertyType);
5799         }
5800
5801         private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(
5802                         List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle,
5803                         Resource resource, User user) {
5804
5805                 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(
5806                                 ArtifactOperationEnum.class);
5807                 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
5808                 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either
5809                                 .left(nodeTypeArtifactsToHandle);
5810                 try {
5811                         // add all found Csar artifacts to list to upload
5812                         List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
5813                         List<NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
5814                         List<NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
5815                         for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
5816                                 ArtifactDefinition foundArtifact;
5817
5818                                 if (!existingArtifactsToHandle.isEmpty()) {
5819                                         foundArtifact = existingArtifactsToHandle.stream()
5820                                                         .filter(a -> a.getArtifactName()
5821                                                                         .equals(currNewArtifact.getArtifactName()))
5822                                                         .findFirst()
5823                                                         .orElse(null);
5824                                         if (foundArtifact != null) {
5825                                                 if (foundArtifact.getArtifactType().equals(currNewArtifact.getArtifactType())) {
5826                                                         if (!foundArtifact.getArtifactChecksum()
5827                                                                         .equals(currNewArtifact.getArtifactChecksum())) {
5828                                                                 currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
5829                                                                 // if current artifact already exists, but has
5830                                                                 // different content, add him to the list to
5831                                                                 // update
5832                                                                 artifactsToUpdate.add(currNewArtifact);
5833                                                         }
5834                                                         // remove found artifact from the list of existing
5835                                                         // artifacts to handle, because it was already
5836                                                         // handled
5837                                                         existingArtifactsToHandle.remove(foundArtifact);
5838                                                         // and remove found artifact from the list to
5839                                                         // upload, because it should either be updated or be
5840                                                         // ignored
5841                                                         artifactsToUpload.remove(currNewArtifact);
5842                                                 } else {
5843                                                         log.debug("Can't upload two artifact with the same name {}.",
5844                                                                         currNewArtifact.getArtifactName());
5845                                                         ResponseFormat responseFormat = ResponseFormatManager.getInstance()
5846                                                                         .getResponseFormat(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
5847                                                                                         currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(),
5848                                                                                         foundArtifact.getArtifactType());
5849                                                         AuditingActionEnum auditingAction = artifactsBusinessLogic
5850                                                                         .detectAuditingType(new ArtifactOperationInfo(false, false,
5851                                                                                         ArtifactOperationEnum.CREATE), foundArtifact.getArtifactChecksum());
5852                                                         artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(),
5853                                                                         user, null, null, foundArtifact.getUniqueId(), responseFormat,
5854                                                                         resource.getComponentType(), null);
5855                                                         responseWrapper.setInnerElement(responseFormat);
5856                                                         break;
5857                                                 }
5858                                         }
5859                                 }
5860                         }
5861                         if (responseWrapper.isEmpty()) {
5862                                 for (ArtifactDefinition currArtifact : existingArtifactsToHandle) {
5863                                         if (currArtifact.getIsFromCsar()) {
5864                                                 artifactsToDelete.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null,
5865                                                         currArtifact.getArtifactType(),
5866                                                         currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(),
5867                                                         currArtifact.getIsFromCsar()));
5868                                         } else {
5869                                                 artifactsToUpdate.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null,
5870                                                         currArtifact.getArtifactType(),
5871                                                         currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(),
5872                                                         currArtifact.getIsFromCsar()));
5873
5874                                         }
5875                                 }
5876                         }
5877                         if (responseWrapper.isEmpty()) {
5878                                 if (!artifactsToUpload.isEmpty()) {
5879                                         nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
5880                                 }
5881                                 if (!artifactsToUpdate.isEmpty()) {
5882                                         nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
5883                                 }
5884                                 if (!artifactsToDelete.isEmpty()) {
5885                                         nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
5886                                 }
5887                         }
5888                         if (!responseWrapper.isEmpty()) {
5889                                 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
5890                         }
5891                 } catch (Exception e) {
5892                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5893                         responseWrapper.setInnerElement(responseFormat);
5894                         log.debug("Exception occurred when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
5895                 }
5896                 return nodeTypeArtifactsToHandleRes;
5897         }
5898
5899         ImmutablePair<String, String> buildNestedToscaResourceName(final String nodeResourceType,
5900                                                                                                                            final String vfResourceName,
5901                                                                                                                            final String nodeTypeFullName) {
5902                 String actualType;
5903                 String actualVfName;
5904                 if (ResourceTypeEnum.CVFC.name()
5905                         .equals(nodeResourceType)) {
5906                         actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name();
5907                         actualType = ResourceTypeEnum.VFC.name();
5908                 } else {
5909                         actualVfName = vfResourceName;
5910                         actualType = nodeResourceType;
5911                 }
5912                 String nameWithouNamespacePrefix;
5913                 try {
5914                         final String nodeTypeNamePrefix = getNodeTypeNamePrefix(nodeTypeFullName);
5915                         log.debug("####### buildNestedToscaResourceName nodeResourceType {}, vfResourceName {}, "
5916                                         + "nodeTypeFullName {}, actualType {}, vfResourceName {} ",     nodeResourceType, vfResourceName,
5917                                 nodeTypeFullName, actualType, vfResourceName);
5918                         final StringBuilder toscaResourceName = new StringBuilder(nodeTypeNamePrefix);
5919
5920                         if (!nodeTypeFullName.contains(nodeTypeNamePrefix)) {
5921                                 nameWithouNamespacePrefix = nodeTypeFullName;
5922                         } else {
5923                                 nameWithouNamespacePrefix = nodeTypeFullName.substring(nodeTypeNamePrefix.length());
5924                         }
5925                         final String[] findTypes = nameWithouNamespacePrefix.split("\\.");
5926                         String actualName;
5927                         if (nodeResourceType.equalsIgnoreCase(findTypes[0])){
5928                                 actualName = nameWithouNamespacePrefix.substring(nodeResourceType.length());
5929                         } else {
5930                                 actualName = "." + nameWithouNamespacePrefix;
5931                         }
5932
5933                         if (actualName.startsWith(Constants.ABSTRACT)) {
5934                                 toscaResourceName.append(nodeResourceType.toLowerCase()).append('.')
5935                                         .append(ValidationUtils.convertToSystemName(actualVfName));
5936                         } else {
5937                                 toscaResourceName.append(actualType.toLowerCase()).append('.')
5938                                         .append(ValidationUtils.convertToSystemName(actualVfName)).append('.').append(Constants.ABSTRACT);
5939                         }
5940                         final StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName);
5941                         final String[] actualNames = actualName.split("\\.");
5942                         if (actualNames.length < 3) {
5943                                 return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
5944                                         previousToscaResourceName.append(actualName).toString());
5945                         }
5946                         return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
5947                                 previousToscaResourceName.append(actualName.substring(actualNames[1].length() + 1)
5948                                         .toLowerCase()).toString());
5949                 } catch (final Exception e) {
5950                         log.debug("Exception occured when buildNestedToscaResourceName, error is:{}", e.getMessage(), e);
5951                         throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfResourceName);
5952                 }
5953         }
5954
5955         /**
5956          * Extracts a Node Type Name prefix from the given Node Type Name.
5957          *
5958          * @param fullName Node Type Name
5959          * @return Node Type Name Prefix
5960          */
5961         private String getNodeTypeNamePrefix(final String fullName) {
5962                 String tempPrefix = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX;
5963                 final List<String> definedNodeTypeNamespaceList = getDefinedNodeTypeNamespaceList();
5964                 log.debug("************* getPrefiX fullName {} FROM {}", fullName, definedNodeTypeNamespaceList);
5965                 final Optional<String> validNameSpace = validateNodeTypeNamePrefix(fullName, definedNodeTypeNamespaceList);
5966                 if (validNameSpace.isPresent()) {
5967                         tempPrefix = validNameSpace.get();
5968                 }
5969                 log.debug("************* getNodeTypeNamePrefix return fullName {} ", tempPrefix);
5970                 return tempPrefix;
5971         }
5972
5973         @Override
5974         public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId,
5975                                                                                                                                                                                                    List<String> dataParamsToReturn) {
5976
5977                 ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
5978                 Either<Resource, StorageOperationStatus> resourceResultEither =
5979                                 toscaOperationFacade.getToscaElement(resourceId,
5980                                 paramsToRetuen);
5981
5982                 if (resourceResultEither.isRight()) {
5983                         if (resourceResultEither.right().value() == StorageOperationStatus.NOT_FOUND) {
5984                                 log.debug("Failed to found resource with id {} ", resourceId);
5985                                 Either
5986                                                 .right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
5987                         }
5988
5989                         log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn);
5990                         return Either.right(componentsUtils
5991                                         .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceResultEither.right()
5992                                                         .value()), ""));
5993                 }
5994
5995                 Resource resource = resourceResultEither.left().value();
5996                 if (dataParamsToReturn.contains(ComponentFieldsEnum.INPUTS.getValue())) {
5997                         ListUtils.emptyIfNull(resource.getInputs())
5998                                         .forEach(input -> input.setConstraints(setInputConstraint(input)));
5999                 }
6000
6001                 UiComponentDataTransfer dataTransfer = uiComponentDataConverter.getUiDataTransferFromResourceByParams(resource,
6002                                 dataParamsToReturn);
6003                 return Either.left(dataTransfer);
6004         }
6005
6006         @Override
6007         public Either<Component, ActionStatus> shouldUpgradeToLatestDerived(Component clonedComponent) {
6008                 Resource resource = (Resource) clonedComponent;
6009                 if (ModelConverter.isAtomicComponent(resource.getResourceType())) {
6010                         Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived = toscaOperationFacade
6011                                         .shouldUpgradeToLatestDerived(resource);
6012                         if (shouldUpgradeToLatestDerived.isRight()) {
6013                                 return Either.right(componentsUtils.convertFromStorageResponse(shouldUpgradeToLatestDerived.right()
6014                                                 .value()));
6015                         }
6016                         return Either.left(shouldUpgradeToLatestDerived.left()
6017                                         .value());
6018                 } else {
6019                         return super.shouldUpgradeToLatestDerived(clonedComponent);
6020                 }
6021         }
6022 }