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