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