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