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