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