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