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