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