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