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