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