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