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