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