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