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