fix a typo
[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             Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade
3328                     .overrideComponent(newResource, oldResource);
3329
3330             if (overrideResource.isRight()) {
3331                 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
3332                         componentsUtils.convertFromStorageResponse(overrideResource.right().value()), newResource);
3333                 componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE);
3334
3335                 throwComponentException(responseFormat);
3336             }
3337
3338             log.debug("Resource updated successfully!!!");
3339             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3340             componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
3341                     ResourceVersionInfo.newBuilder()
3342                             .state(oldResource.getLifecycleState()
3343                                     .name())
3344                             .version(oldResource.getVersion())
3345                             .build());
3346
3347             resourcePair = new ImmutablePair<>(overrideResource.left().value(),
3348                     ActionStatus.OK);
3349             return resourcePair;
3350         } finally {
3351             if (resourcePair == null) {
3352                 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
3353                 titanDao.rollback();
3354             } else if (!inTransaction) {
3355                 titanDao.commit();
3356             }
3357             if (needLock) {
3358                 log.debug("unlock resource {}", lockedResourceId);
3359                 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
3360             }
3361         }
3362
3363     }
3364
3365     /**
3366      * Merge old resource with new. Keep old category and vendor name without
3367      * change
3368      *
3369      * @param oldResource
3370      * @param newResource
3371      */
3372     private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
3373
3374         // keep old category and vendor name without change
3375         // merge the rest of the resource metadata
3376         if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
3377             newResource.setTags(oldResource.getTags());
3378         }
3379
3380         if (newResource.getDescription() == null) {
3381             newResource.setDescription(oldResource.getDescription());
3382         }
3383
3384         if (newResource.getVendorRelease() == null) {
3385             newResource.setVendorRelease(oldResource.getVendorRelease());
3386         }
3387
3388         if (newResource.getResourceVendorModelNumber() == null) {
3389             newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber());
3390         }
3391
3392         if (newResource.getContactId() == null) {
3393             newResource.setContactId(oldResource.getContactId());
3394         }
3395
3396         newResource.setCategories(oldResource.getCategories());
3397         if (newResource.getVendorName() == null) {
3398             newResource.setVendorName(oldResource.getVendorName());
3399         }
3400     }
3401
3402     private Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user,
3403                                               boolean inTransaction, boolean needLock) {
3404
3405         if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) {
3406             // checkout
3407             return lifecycleBusinessLogic.changeState(
3408                     oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
3409                     new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock)
3410                     .left()
3411                     .on(response -> failOnChangeState(response, user, oldResource, newResource));
3412         }
3413         return oldResource;
3414     }
3415
3416     private Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) {
3417         log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(),
3418                 response.getFormattedMessage());
3419         componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
3420                 ResourceVersionInfo.newBuilder()
3421                         .state(oldResource.getLifecycleState().name())
3422                         .version(oldResource.getVersion())
3423                         .build());
3424         throw new ComponentException(response);
3425     }
3426
3427     public Resource validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction, CsarInfo csarInfo) {
3428
3429         validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
3430         validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
3431         validateLifecycleTypesCreate(user, resource, actionEnum);
3432         validateResourceType(user, resource, actionEnum);
3433         resource.setCreatorUserId(user.getUserId());
3434         resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
3435         resource.setContactId(resource.getContactId().toLowerCase());
3436         if (StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) {
3437             String resourceSystemName;
3438             if (csarInfo != null && StringUtils.isNotEmpty(csarInfo.getVfResourceName())) {
3439                 resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName());
3440             } else {
3441                 resourceSystemName = resource.getSystemName();
3442             }
3443             resource.setToscaResourceName(CommonBeUtils
3444                     .generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
3445         }
3446
3447         // Generate invariant UUID - must be here and not in operation since it
3448         // should stay constant during clone
3449         // TODO
3450         String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
3451         resource.setInvariantUUID(invariantUUID);
3452
3453         return resource;
3454     }
3455
3456     private Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource,
3457                                                                  AuditingActionEnum actionEnum) {
3458         Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
3459         if (resource.getResourceType() == null) {
3460             log.debug("Invalid resource type for resource");
3461             ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3462             eitherResult = Either.right(errorResponse);
3463             componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
3464         }
3465         return eitherResult;
3466     }
3467
3468     private Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource,
3469                                                                          AuditingActionEnum actionEnum) {
3470         Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
3471         if (resource.getInterfaces() != null && resource.getInterfaces().size() > 0) {
3472             log.debug("validate interface lifecycle Types Exist");
3473             Iterator<InterfaceDefinition> intItr = resource.getInterfaces().values().iterator();
3474             while (intItr.hasNext() && eitherResult.isLeft()) {
3475                 InterfaceDefinition interfaceDefinition = intItr.next();
3476                 String intType = interfaceDefinition.getUniqueId();
3477                 Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation
3478                         .getInterface(intType);
3479                 if (eitherCapTypeFound.isRight()) {
3480                     if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
3481                         BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
3482                                 "Create Resource - validateLifecycleTypesCreate", "Interface", intType);
3483                         log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB",
3484                                 intType, resource.getName());
3485                         BeEcompErrorManager.getInstance()
3486                                 .logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
3487                         log.debug("request to data model failed with error: {}",
3488                                 eitherCapTypeFound.right().value().name());
3489                     }
3490
3491                     ResponseFormat errorResponse = componentsUtils
3492                             .getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
3493                     eitherResult = Either.right(errorResponse);
3494                     componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
3495                 }
3496
3497             }
3498         }
3499         return eitherResult;
3500     }
3501
3502     private Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user,
3503                                                                           ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
3504                                                                           boolean inTransaction) {
3505
3506         Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
3507         if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) {
3508             log.debug("validate capability Types Exist - capabilities section");
3509
3510             for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities().entrySet()) {
3511
3512                 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum,
3513                         eitherResult, typeEntry, inTransaction);
3514                 if (eitherResult.isRight()) {
3515                     return Either.right(eitherResult.right().value());
3516                 }
3517             }
3518         }
3519
3520         if (resource.getRequirements() != null && resource.getRequirements().size() > 0) {
3521             log.debug("validate capability Types Exist - requirements section");
3522             for (String type : resource.getRequirements().keySet()) {
3523                 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource,
3524                         resource.getRequirements().get(type), actionEnum, eitherResult, type, inTransaction);
3525                 if (eitherResult.isRight()) {
3526                     return Either.right(eitherResult.right().value());
3527                 }
3528             }
3529         }
3530
3531         return eitherResult;
3532     }
3533
3534     // @param typeObject- the object to which the validation is done
3535     private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
3536                                                                          ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List<?> validationObjects,
3537                                                                          AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type,
3538                                                                          boolean inTransaction) {
3539         Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
3540                 .getCapabilityType(type, inTransaction);
3541         if (eitherCapTypeFound.isRight()) {
3542             if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
3543                 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
3544                         CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", type);
3545                 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type,
3546                         resource.getName());
3547                 BeEcompErrorManager.getInstance()
3548                         .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
3549             }
3550             log.debug("Trying to get capability type {} failed with error: {}", type,
3551                     eitherCapTypeFound.right().value().name());
3552             ResponseFormat errorResponse = null;
3553             if (type != null) {
3554                 errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
3555             } else {
3556                 errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE,
3557                         validationObjects);
3558             }
3559             eitherResult = Either.right(errorResponse);
3560             componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
3561         }
3562         return eitherResult;
3563     }
3564
3565     private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
3566                                                                          ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
3567                                                                          Either<Boolean, ResponseFormat> eitherResult, Entry<String, List<CapabilityDefinition>> typeEntry,
3568                                                                          boolean inTransaction) {
3569         Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
3570                 .getCapabilityType(typeEntry.getKey(), inTransaction);
3571         if (eitherCapTypeFound.isRight()) {
3572             if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
3573                 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
3574                         CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", typeEntry.getKey());
3575                 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB",
3576                         typeEntry.getKey(), resource.getName());
3577                 BeEcompErrorManager.getInstance()
3578                         .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
3579             }
3580             log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(),
3581                     eitherCapTypeFound.right().value().name());
3582             ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE,
3583                     typeEntry.getKey());
3584             eitherResult = Either.right(errorResponse);
3585             componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
3586         }
3587         CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
3588         if (capabilityTypeDefinition.getProperties() != null) {
3589             for (CapabilityDefinition capDef : typeEntry.getValue()) {
3590                 List<ComponentInstanceProperty> properties = capDef.getProperties();
3591                 if (properties == null || properties.isEmpty()) {
3592                     properties = new ArrayList<>();
3593                     for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
3594                         ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
3595                         properties.add(newProp);
3596                     }
3597                 } else {
3598                     for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
3599                         PropertyDefinition porpFromDef = prop.getValue();
3600                         List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
3601                         for (ComponentInstanceProperty cip : properties) {
3602                             if (!cip.getName().equals(porpFromDef.getName())) {
3603                                 ComponentInstanceProperty newProp = new ComponentInstanceProperty(porpFromDef);
3604                                 propsToAdd.add(newProp);
3605                             }
3606                         }
3607                         if (!propsToAdd.isEmpty()) {
3608                             properties.addAll(propsToAdd);
3609                         }
3610                     }
3611                 }
3612                 capDef.setProperties(properties);
3613             }
3614         }
3615         return eitherResult;
3616     }
3617
3618     public Resource createResourceByDao(Resource resource, User user,
3619                                         AuditingActionEnum actionEnum, boolean isNormative, boolean inTransaction) {
3620         // create resource
3621
3622         // lock new resource name in order to avoid creation resource with same
3623         // name
3624         Resource createdResource = null;
3625         if (!inTransaction) {
3626             Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
3627                     CREATE_RESOURCE);
3628             if (lockResult.isRight()) {
3629                 ResponseFormat responseFormat = lockResult.right().value();
3630                 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
3631                 throw new ComponentException(responseFormat);
3632             }
3633
3634             log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
3635         }
3636         try {
3637             if (resource.deriveFromGeneric()) {
3638                 handleResourceGenericType(resource);
3639             }
3640            createdResource = createResourceTransaction(resource, user, isNormative
3641            );
3642             componentsUtils.auditResource(componentsUtils.getResponseFormat(ActionStatus.CREATED), user,
3643                     createdResource, actionEnum);
3644             ASDCKpiApi.countCreatedResourcesKPI();
3645         } catch(ComponentException e) {
3646             ResponseFormat responseFormat = e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
3647             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
3648             throw e;
3649         } catch (StorageException e){
3650             ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
3651             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
3652             throw e;
3653         }
3654         finally {
3655             if (!inTransaction) {
3656                 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
3657                         NodeTypeEnum.Resource);
3658             }
3659         }
3660         return createdResource;
3661     }
3662
3663     private Resource createResourceTransaction(Resource resource, User user,
3664                                                boolean isNormative) {
3665         // validate resource name uniqueness
3666         log.debug("validate resource name");
3667         Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(
3668                 resource.getName(), resource.getResourceType(), resource.getComponentType());
3669         if (eitherValidation.isRight()) {
3670             log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(),
3671                     eitherValidation.right().value());
3672             ResponseFormat errorResponse = componentsUtils
3673                     .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
3674             throw new ComponentException(errorResponse);
3675         }
3676         if (eitherValidation.left().value()) {
3677             log.debug("resource with name: {}, already exists", resource.getName());
3678             ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
3679                     ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
3680             throw new ComponentException(errorResponse);
3681         }
3682
3683         log.debug("send resource {} to dao for create", resource.getName());
3684
3685         createArtifactsPlaceHolderData(resource, user);
3686         // enrich object
3687         if (!isNormative) {
3688             log.debug("enrich resource with creator, version and state");
3689             resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
3690             resource.setVersion(INITIAL_VERSION);
3691             resource.setHighestVersion(true);
3692             if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC) {
3693                 resource.setAbstract(false);
3694             }
3695         }
3696         return toscaOperationFacade.createToscaComponent(resource)
3697                 .left()
3698                 .on(r->throwComponentExceptionByResource(r, resource));
3699     }
3700
3701     private Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) {
3702         ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
3703                 componentsUtils.convertFromStorageResponse(status), resource);
3704         throw new ComponentException(responseFormat);
3705     }
3706
3707     private void createArtifactsPlaceHolderData(Resource resource, User user) {
3708         // create mandatory artifacts
3709
3710         // TODO it must be removed after that artifact uniqueId creation will be
3711         // moved to ArtifactOperation
3712
3713         setInformationalArtifactsPlaceHolder(resource, user);
3714         setDeploymentArtifactsPlaceHolder(resource, user);
3715         setToscaArtifactsPlaceHolders(resource, user);
3716     }
3717
3718     @SuppressWarnings("unchecked")
3719     @Override
3720     public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
3721         Resource resource = (Resource) component;
3722         Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
3723         if (artifactMap == null) {
3724             artifactMap = new HashMap<>();
3725         }
3726         Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
3727                 .getConfiguration().getDeploymentResourceArtifacts();
3728         if (deploymentResourceArtifacts != null) {
3729             Map<String, ArtifactDefinition> finalArtifactMap = artifactMap;
3730             deploymentResourceArtifacts.forEach((k, v)->processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k,v));
3731         }
3732         resource.setDeploymentArtifacts(artifactMap);
3733     }
3734
3735     private void processDeploymentResourceArtifacts(User user, Resource resource, Map<String, ArtifactDefinition> artifactMap, String k, Object v) {
3736         boolean shouldCreateArtifact = true;
3737         Map<String, Object> artifactDetails = (Map<String, Object>) v;
3738         Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
3739         if (object != null) {
3740             List<String> artifactTypes = (List<String>) object;
3741             if (!artifactTypes.contains(resource.getResourceType().name())) {
3742                 shouldCreateArtifact = false;
3743                 return;
3744             }
3745         } else {
3746             log.info("resource types for artifact placeholder {} were not defined. default is all resources",
3747                     k);
3748         }
3749         if (shouldCreateArtifact) {
3750             if (artifactsBusinessLogic != null) {
3751                 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
3752                         resource.getUniqueId(), k, (Map<String, Object>) v,
3753                         user, ArtifactGroupTypeEnum.DEPLOYMENT);
3754                 if (artifactDefinition != null
3755                         && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
3756                     artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
3757                 }
3758             }
3759         }
3760     }
3761
3762     @SuppressWarnings("unchecked")
3763     private void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
3764         Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
3765         if (artifactMap == null) {
3766             artifactMap = new HashMap<>();
3767         }
3768         String resourceUniqueId = resource.getUniqueId();
3769         List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration()
3770                 .getExcludeResourceCategory();
3771         List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration()
3772                 .getExcludeResourceType();
3773         Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager()
3774                 .getConfiguration().getInformationalResourceArtifacts();
3775         List<CategoryDefinition> categories = resource.getCategories();
3776         boolean isCreateArtifact = true;
3777         if (exludeResourceCategory != null) {
3778             String category = categories.get(0).getName();
3779             isCreateArtifact = exludeResourceCategory.stream().noneMatch(e->e.equalsIgnoreCase(category));
3780         }
3781         if (isCreateArtifact && exludeResourceType != null) {
3782             String resourceType = resource.getResourceType().name();
3783             isCreateArtifact = exludeResourceType.stream().noneMatch(e->e.equalsIgnoreCase(resourceType));
3784         }
3785         if (informationalResourceArtifacts != null && isCreateArtifact) {
3786             Set<String> keys = informationalResourceArtifacts.keySet();
3787             for (String informationalResourceArtifactName : keys) {
3788                 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts
3789                         .get(informationalResourceArtifactName);
3790                 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
3791                         resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
3792                         ArtifactGroupTypeEnum.INFORMATIONAL);
3793                 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
3794
3795             }
3796         }
3797         resource.setArtifacts(artifactMap);
3798     }
3799
3800     /**
3801      * deleteResource
3802      *
3803      * @param resourceId
3804      * @param user
3805      * @return
3806      */
3807     public ResponseFormat deleteResource(String resourceId, User user) {
3808         ResponseFormat responseFormat;
3809         validateUserExists(user, DELETE_RESOURCE, false);
3810
3811         Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId);
3812         if (resourceStatus.isRight()) {
3813             log.debug("failed to get resource {}", resourceId);
3814             return componentsUtils
3815                     .getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), "");
3816         }
3817
3818         Resource resource = resourceStatus.left().value();
3819
3820         StorageOperationStatus result = StorageOperationStatus.OK;
3821         Either<Boolean, ResponseFormat> lockResult = lockComponent(resourceId, resource, "Mark resource to delete");
3822         if (lockResult.isRight()) {
3823             return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3824         }
3825
3826         try {
3827
3828             result = markComponentToDelete(resource);
3829             if (result.equals(StorageOperationStatus.OK)) {
3830                 responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
3831             } else {
3832                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
3833                 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
3834             }
3835             return responseFormat;
3836
3837         } finally {
3838             if (result == null || !result.equals(StorageOperationStatus.OK)) {
3839                 titanDao.rollback();
3840             } else {
3841                 titanDao.commit();
3842             }
3843             graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
3844         }
3845
3846     }
3847
3848     public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) {
3849         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
3850         validateUserExists(user, DELETE_RESOURCE, false);
3851         Resource resource = null;
3852         StorageOperationStatus result = StorageOperationStatus.OK;
3853         try {
3854
3855             Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade
3856                     .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version);
3857             if (resourceStatus.isRight()) {
3858                 log.debug("failed to get resource {} version {}", resourceName, version);
3859                 return componentsUtils.getResponseFormatByResource(
3860                         componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), resourceName);
3861             }
3862
3863             resource = resourceStatus.left().value();
3864
3865         } finally {
3866             if (result == null || !result.equals(StorageOperationStatus.OK)) {
3867                 titanDao.rollback();
3868                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
3869                 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resourceName);
3870             } else {
3871                 titanDao.commit();
3872             }
3873         }
3874         if (resource != null) {
3875             Either<Boolean, ResponseFormat> lockResult = lockComponent(resource.getUniqueId(), resource,
3876                     DELETE_RESOURCE);
3877             if (lockResult.isRight()) {
3878                 result = StorageOperationStatus.GENERAL_ERROR;
3879                 return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3880             }
3881             try {
3882                 result = markComponentToDelete(resource);
3883                 if (!result.equals(StorageOperationStatus.OK)) {
3884                     ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
3885                     responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
3886                     return responseFormat;
3887                 }
3888
3889             } finally {
3890                 if (result == null || !result.equals(StorageOperationStatus.OK)) {
3891                     titanDao.rollback();
3892                 } else {
3893                     titanDao.commit();
3894                 }
3895                 graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource);
3896             }
3897         }
3898         return responseFormat;
3899     }
3900
3901     public Either<Resource, ResponseFormat> getResource(String resourceId, User user) {
3902
3903         if (user != null) {
3904             validateUserExists(user, CREATE_RESOURCE, false);
3905         }
3906
3907         Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId);
3908         if (storageStatus.isRight()) {
3909             log.debug("failed to get resource by id {}", resourceId);
3910             return Either.right(componentsUtils.getResponseFormatByResource(
3911                     componentsUtils.convertFromStorageResponse(storageStatus.right().value()), resourceId));
3912         }
3913         if (!(storageStatus.left().value() instanceof Resource)) {
3914             return Either.right(componentsUtils.getResponseFormatByResource(
3915                     componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId));
3916         }
3917         return Either.left(storageStatus.left().value());
3918
3919     }
3920
3921     public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion,
3922                                                                         String userId) {
3923
3924         validateUserExists(userId, "get Resource By Name And Version", false);
3925
3926         Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade
3927                 .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion);
3928         if (getResource.isRight()) {
3929             log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion);
3930             return Either.right(componentsUtils.getResponseFormatByResource(
3931                     componentsUtils.convertFromStorageResponse(getResource.right().value()), resourceName));
3932         }
3933         return Either.left(getResource.left().value());
3934     }
3935
3936     /**
3937      * updateResourceMetadata
3938      *
3939      * @param user               - modifier data (userId)
3940      * @param inTransaction      TODO
3941      * @param resourceIdToUpdate - the resource identifier
3942      * @param newResource
3943      * @return Either<Resource ,   responseFormat>
3944      */
3945     public Resource updateResourceMetadata(String resourceIdToUpdate, Resource newResource,
3946                                            Resource currentResource, User user, boolean inTransaction) {
3947
3948         validateUserExists(user.getUserId(), "update Resource Metadata", false);
3949
3950         log.debug("Get resource with id {}", resourceIdToUpdate);
3951         boolean needToUnlock = false;
3952         boolean rollbackNeeded = true;
3953
3954         try {
3955             if (currentResource == null) {
3956                 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade
3957                         .getToscaElement(resourceIdToUpdate);
3958                 if (storageStatus.isRight()) {
3959                     throw new ComponentException(componentsUtils.getResponseFormatByResource(
3960                             componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
3961                 }
3962
3963                 currentResource = storageStatus.left().value();
3964             }
3965             // verify that resource is checked-out and the user is the last
3966             // updater
3967             if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) {
3968                 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3969             }
3970
3971             // lock resource
3972             StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate,
3973                     NodeTypeEnum.Resource);
3974             if (!lockResult.equals(StorageOperationStatus.OK)) {
3975                 BeEcompErrorManager.getInstance().logBeFailedLockObjectError("Upload Artifact - lock ",
3976                         NodeTypeEnum.Resource.getName(), resourceIdToUpdate);
3977                 log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult);
3978                 ResponseFormat responseFormat = componentsUtils
3979                         .getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
3980                 throw new ComponentException(responseFormat);
3981             }
3982
3983             needToUnlock = true;
3984
3985             // critical section starts here
3986             // convert json to object
3987
3988             // Update and updated resource must have a non-empty "derivedFrom"
3989             // list
3990             // This code is not called from import resources, because of root
3991             // VF "derivedFrom" should be null (or ignored)
3992             if (ModelConverter.isAtomicComponent(currentResource)) {
3993                 validateDerivedFromNotEmpty(null, newResource, null);
3994                 validateDerivedFromNotEmpty(null, currentResource, null);
3995             } else {
3996                 newResource.setDerivedFrom(null);
3997             }
3998
3999             Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource,
4000                     user, currentResource, false, true);
4001             if (dataModelResponse.isRight()) {
4002                 log.debug("failed to update resource metadata!!!");
4003                 rollbackNeeded = true;
4004                 throw new ComponentException(dataModelResponse.right().value());
4005             }
4006
4007             log.debug("Resource metadata updated successfully!!!");
4008             rollbackNeeded = false;
4009             return dataModelResponse.left().value();
4010
4011         } catch (ComponentException|StorageException e){
4012             rollback(inTransaction, newResource, null, null);
4013             throw e;
4014         }
4015         finally {
4016             if (!inTransaction) {
4017                 titanDao.commit();
4018             }
4019             if (needToUnlock) {
4020                 graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
4021             }
4022         }
4023     }
4024
4025     private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource,
4026                                                                     User user, Resource currentResource, boolean shouldLock, boolean inTransaction) {
4027         updateVfModuleGroupsNames(currentResource, newResource);
4028         validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction, false);
4029         // Setting last updater and uniqueId
4030         newResource.setContactId(newResource.getContactId().toLowerCase());
4031         newResource.setLastUpdaterUserId(user.getUserId());
4032         newResource.setUniqueId(resourceIdToUpdate);
4033         // Cannot set highest version through UI
4034         newResource.setHighestVersion(currentResource.isHighestVersion());
4035         newResource.setCreationDate(currentResource.getCreationDate());
4036
4037         Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource,
4038                 newResource, user.getUserId(), inTransaction);
4039
4040         if (processUpdateOfDerivedFrom.isRight()) {
4041             log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate);
4042             return Either.right(processUpdateOfDerivedFrom.right().value());
4043         }
4044
4045         log.debug("send resource {} to dao for update", newResource.getUniqueId());
4046         if (isNotEmpty(newResource.getGroups())) {
4047             for (GroupDefinition group : newResource.getGroups()) {
4048                 if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) {
4049                     groupBusinessLogic.validateAndUpdateGroupMetadata(
4050                             newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId(),
4051                             user, newResource.getComponentType(), group, true, false);
4052                 }
4053             }
4054         }
4055         Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade
4056                 .updateToscaElement(newResource);
4057
4058         if (dataModelResponse.isRight()) {
4059             ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
4060                     componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), newResource);
4061             return Either.right(responseFormat);
4062         } else if (dataModelResponse.left().value() == null) {
4063             log.debug("No response from updateResource");
4064             return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4065         }
4066         return Either.left(dataModelResponse.left().value());
4067     }
4068
4069
4070     private void updateVfModuleGroupsNames(Resource currentResource, Resource newResource) {
4071         if(currentResource.getGroups() != null && !currentResource.getName().equals(newResource.getName())){
4072             List<GroupDefinition> updatedGroups = currentResource.getGroups()
4073                     .stream()
4074                     .map(group -> getUpdatedGroup(group, currentResource.getName(), newResource.getName()))
4075                     .collect(toList());
4076             newResource.setGroups(updatedGroups);
4077         }
4078     }
4079
4080     private GroupDefinition getUpdatedGroup(GroupDefinition currGroup, String replacePattern, String with) {
4081         GroupDefinition updatedGroup = new GroupDefinition(currGroup);
4082         if(updatedGroup.isSamePrefix(replacePattern) && updatedGroup.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)){
4083             String prefix = updatedGroup.getName().substring(0, replacePattern.length());
4084             String newGroupName = updatedGroup.getName().replaceFirst(prefix, with);
4085             updatedGroup.setName(newGroupName);
4086         }
4087         return updatedGroup;
4088     }
4089     /**
4090      * validateResourceFieldsBeforeCreate
4091      *
4092      * @param user - modifier data (userId)
4093      * @return Either<Boolean   ,       ErrorResponse>
4094      */
4095     private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, Resource resource,
4096                                                                                AuditingActionEnum actionEnum, boolean inTransaction) {
4097         validateComponentFieldsBeforeCreate(user, resource, actionEnum);
4098         // validate category
4099         log.debug("validate category");
4100         validateCategory(user, resource, actionEnum, inTransaction);
4101         // validate vendor name & release & model number
4102         log.debug("validate vendor name");
4103         validateVendorName(user, resource, actionEnum);
4104         log.debug("validate vendor release");
4105         validateVendorReleaseName(user, resource, actionEnum);
4106         log.debug("validate resource vendor model number");
4107         validateResourceVendorModelNumber(user, resource, actionEnum);
4108         // validate cost
4109         log.debug("validate cost");
4110         validateCost(resource);
4111         // validate licenseType
4112         log.debug("validate licenseType");
4113         validateLicenseType(user, resource, actionEnum);
4114         // validate template (derived from)
4115         log.debug("validate derived from");
4116         if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
4117             resource.setDerivedFrom(null);
4118         }
4119         validateDerivedFromExist(user, resource, actionEnum);
4120         // warn about non-updatable fields
4121         checkComponentFieldsForOverrideAttempt(resource);
4122         String currentCreatorFullName = resource.getCreatorFullName();
4123         if (currentCreatorFullName != null) {
4124             log.debug("Resource Creator fullname is automatically set and cannot be updated");
4125         }
4126
4127         String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
4128         if (currentLastUpdaterFullName != null) {
4129             log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
4130         }
4131
4132         Long currentLastUpdateDate = resource.getLastUpdateDate();
4133         if (currentLastUpdateDate != null) {
4134             log.debug("Resource last update date is automatically set and cannot be updated");
4135         }
4136
4137         Boolean currentAbstract = resource.isAbstract();
4138         if (currentAbstract != null) {
4139             log.debug("Resource abstract is automatically set and cannot be updated");
4140         }
4141
4142         return Either.left(true);
4143     }
4144
4145     /**
4146      * validateResourceFieldsBeforeUpdate
4147      *
4148      * @param currentResource - Resource object to validate
4149      * @param isNested
4150      */
4151     private void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource,
4152                                                     boolean inTransaction, boolean isNested) {
4153         validateFields(currentResource, updateInfoResource, inTransaction, isNested);
4154         warnNonEditableFields(currentResource, updateInfoResource);
4155     }
4156
4157     private void warnNonEditableFields(Resource currentResource, Resource updateInfoResource) {
4158         String currentResourceVersion = currentResource.getVersion();
4159         String updatedResourceVersion = updateInfoResource.getVersion();
4160
4161         if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) {
4162             log.debug("Resource version is automatically set and cannot be updated");
4163         }
4164
4165         String currentCreatorUserId = currentResource.getCreatorUserId();
4166         String updatedCreatorUserId = updateInfoResource.getCreatorUserId();
4167
4168         if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) {
4169             log.debug("Resource Creator UserId is automatically set and cannot be updated");
4170         }
4171
4172         String currentCreatorFullName = currentResource.getCreatorFullName();
4173         String updatedCreatorFullName = updateInfoResource.getCreatorFullName();
4174
4175         if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) {
4176             log.debug("Resource Creator fullname is automatically set and cannot be updated");
4177         }
4178
4179         String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId();
4180         String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId();
4181
4182         if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) {
4183             log.debug("Resource LastUpdater userId is automatically set and cannot be updated");
4184         }
4185
4186         String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName();
4187         String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName();
4188
4189         if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) {
4190             log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
4191         }
4192
4193         Long currentCreationDate = currentResource.getCreationDate();
4194         Long updatedCreationDate = updateInfoResource.getCreationDate();
4195
4196         if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) {
4197             log.debug("Resource Creation date is automatically set and cannot be updated");
4198         }
4199
4200         Long currentLastUpdateDate = currentResource.getLastUpdateDate();
4201         Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate();
4202
4203         if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) {
4204             log.debug("Resource last update date is automatically set and cannot be updated");
4205         }
4206
4207         LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState();
4208         LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState();
4209
4210         if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) {
4211             log.debug("Resource lifecycle state date is automatically set and cannot be updated");
4212         }
4213
4214         Boolean currentAbstract = currentResource.isAbstract();
4215         Boolean updatedAbstract = updateInfoResource.isAbstract();
4216
4217         if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) {
4218             log.debug("Resource abstract is automatically set and cannot be updated");
4219         }
4220
4221         Boolean currentHighestVersion = currentResource.isHighestVersion();
4222         Boolean updatedHighestVersion = updateInfoResource.isHighestVersion();
4223
4224         if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) {
4225             log.debug("Resource highest version is automatically set and cannot be updated");
4226         }
4227
4228         String currentUuid = currentResource.getUUID();
4229         String updatedUuid = updateInfoResource.getUUID();
4230
4231         if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) {
4232             log.debug("Resource UUID is automatically set and cannot be updated");
4233         }
4234
4235         ResourceTypeEnum currentResourceType = currentResource.getResourceType();
4236         ResourceTypeEnum updatedResourceType = updateInfoResource.getResourceType();
4237
4238         if ((updatedResourceType != null) && (!updatedResourceType.equals(currentResourceType))) {
4239             log.debug("Resource Type  cannot be updated");
4240
4241         }
4242         updateInfoResource.setResourceType(currentResource.getResourceType());
4243
4244         String currentInvariantUuid = currentResource.getInvariantUUID();
4245         String updatedInvariantUuid = updateInfoResource.getInvariantUUID();
4246
4247         if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
4248             log.debug("Resource invariant UUID is automatically set and cannot be updated");
4249             updateInfoResource.setInvariantUUID(currentInvariantUuid);
4250         }
4251     }
4252
4253     private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) {
4254         boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
4255         log.debug("validate resource name before update");
4256         validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested);
4257         log.debug("validate description before update");
4258         validateDescriptionAndCleanup(null, updateInfoResource, null);
4259         log.debug("validate icon before update");
4260         validateIcon(currentResource, updateInfoResource, hasBeenCertified);
4261         log.debug("validate tags before update");
4262         validateTagsListAndRemoveDuplicates(null, updateInfoResource, null);
4263         log.debug("validate vendor name before update");
4264         validateVendorName(null, updateInfoResource, null);
4265         log.debug("validate resource vendor model number before update");
4266         validateResourceVendorModelNumber(currentResource, updateInfoResource);
4267         log.debug("validate vendor release before update");
4268         validateVendorReleaseName(null, updateInfoResource, null);
4269         log.debug("validate contact info before update");
4270         validateContactId(null, updateInfoResource, null);
4271         log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
4272         validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified);
4273         log.debug("validate category before update");
4274         validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction);
4275     }
4276
4277
4278     private boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) {
4279         String resourceNameUpdated = updateInfoResource.getName();
4280         String resourceNameCurrent = currentResource.getName();
4281         if (resourceNameCurrent.equals(resourceNameUpdated)) {
4282             return true;
4283         }
4284         // In case of CVFC type we should support the case of old VF with CVFC
4285         // instances that were created without the "Cvfc" suffix
4286         return currentResource.getResourceType().equals(ResourceTypeEnum.CVFC) &&
4287                 resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent));
4288     }
4289
4290     private String addCvfcSuffixToResourceName(String resourceName) {
4291         return resourceName + "Cvfc";
4292     }
4293
4294     private void validateResourceName(Resource currentResource, Resource updateInfoResource,
4295                                       boolean hasBeenCertified, boolean isNested) {
4296         String resourceNameUpdated = updateInfoResource.getName();
4297         if (!isResourceNameEquals(currentResource, updateInfoResource)) {
4298             if (isNested || !hasBeenCertified) {
4299                 validateComponentName(null, updateInfoResource, null);
4300                 validateResourceNameUniqueness(updateInfoResource);
4301                 currentResource.setName(resourceNameUpdated);
4302                 currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
4303                 currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
4304
4305             } else {
4306                 log.info("Resource name: {}, cannot be updated once the resource has been certified once.",
4307                         resourceNameUpdated);
4308                 throw new ComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
4309             }
4310         }
4311     }
4312
4313     private void validateIcon(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
4314         String iconUpdated = updateInfoResource.getIcon();
4315         String iconCurrent = currentResource.getIcon();
4316         if (!iconCurrent.equals(iconUpdated)) {
4317             if (!hasBeenCertified) {
4318                 validateIcon(null, updateInfoResource, null);
4319             } else {
4320                 log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated);
4321                 throw new ComponentException(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
4322             }
4323         }
4324     }
4325
4326     private void validateResourceVendorModelNumber(Resource currentResource, Resource updateInfoResource) {
4327         String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber();
4328         String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber();
4329         if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) {
4330             validateResourceVendorModelNumber(null, updateInfoResource, null);
4331         }
4332     }
4333
4334     private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource,
4335                                                              boolean hasBeenCertified, boolean inTransaction) {
4336         validateCategory(null, updateInfoResource, null, inTransaction);
4337         if (hasBeenCertified) {
4338             CategoryDefinition currentCategory = currentResource.getCategories().get(0);
4339             SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories().get(0);
4340             CategoryDefinition updateCategory = updateInfoResource.getCategories().get(0);
4341             SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories().get(0);
4342             if (!currentCategory.getName().equals(updateCategory.getName())
4343                     || !currentSubCategory.getName().equals(updtaeSubCategory.getName())) {
4344                 log.info("Category {} cannot be updated once the resource has been certified once.",
4345                         currentResource.getCategories());
4346                 ResponseFormat errorResponse = componentsUtils
4347                         .getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
4348                 return Either.right(errorResponse);
4349             }
4350         }
4351         return Either.left(true);
4352     }
4353
4354     private Either<Boolean, ResponseFormat> validateDerivedFromDuringUpdate(Resource currentResource,
4355                                                                             Resource updateInfoResource, boolean hasBeenCertified) {
4356
4357         List<String> currentDerivedFrom = currentResource.getDerivedFrom();
4358         List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
4359         if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
4360                 || updatedDerivedFrom.isEmpty()) {
4361             log.trace("Update normative types");
4362             return Either.left(true);
4363         }
4364
4365         String derivedFromCurrent = currentDerivedFrom.get(0);
4366         String derivedFromUpdated = updatedDerivedFrom.get(0);
4367
4368         if (!derivedFromCurrent.equals(derivedFromUpdated)) {
4369             if (!hasBeenCertified) {
4370                 validateDerivedFromExist(null, updateInfoResource, null);
4371             } else {
4372                 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
4373                         currentResource, updateInfoResource, null);
4374
4375                 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
4376                     log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
4377                     return validateDerivedFromExtending;
4378                 }
4379             }
4380         } else {
4381             // For derived from, we must know whether it was actually changed,
4382             // otherwise we must do no action.
4383             // Due to changes it inflicts on data model (remove artifacts,
4384             // properties...), it's not like a flat field which can be
4385             // overwritten if not changed.
4386             // So we must indicate that derived from is not changed
4387             updateInfoResource.setDerivedFrom(null);
4388         }
4389         return Either.left(true);
4390     }
4391
4392     private Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource,
4393                                                                                   Resource updateInfoResource, boolean hasBeenCertified) {
4394
4395         List<String> currentDerivedFrom = currentResource.getDerivedFrom();
4396         List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
4397         if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
4398                 || updatedDerivedFrom.isEmpty()) {
4399             log.trace("Update normative types");
4400             return Either.left(true);
4401         }
4402
4403         String derivedFromCurrent = currentDerivedFrom.get(0);
4404         String derivedFromUpdated = updatedDerivedFrom.get(0);
4405
4406         if (!derivedFromCurrent.equals(derivedFromUpdated)) {
4407             if (!hasBeenCertified) {
4408                 validateDerivedFromExist(null, updateInfoResource, null);
4409             } else {
4410                 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
4411                         currentResource, updateInfoResource, null);
4412
4413                 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
4414                     log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
4415                     return validateDerivedFromExtending;
4416                 }
4417             }
4418         }
4419         return Either.left(true);
4420     }
4421
4422     private void validateDerivedFromExist(User user, Resource resource,  AuditingActionEnum actionEnum) {
4423         if (resource.getDerivedFrom() == null || resource.getDerivedFrom().isEmpty()) {
4424             return;
4425         }
4426         String templateName = resource.getDerivedFrom().get(0);
4427         Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
4428                 .validateToscaResourceNameExists(templateName);
4429         if (dataModelResponse.isRight()) {
4430             StorageOperationStatus storageStatus = dataModelResponse.right().value();
4431             BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist");
4432             log.debug("request to data model failed with error: {}", storageStatus);
4433             ResponseFormat responseFormat = componentsUtils
4434                     .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
4435             log.trace("audit before sending response");
4436             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4437             throw new ComponentException(componentsUtils.convertFromStorageResponse(storageStatus));
4438         } else if (!dataModelResponse.left().value()) {
4439             log.info("resource template with name: {}, does not exists", templateName);
4440             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
4441             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4442             throw new ComponentException(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
4443         }
4444     }
4445
4446     // Tal G for extending inheritance US815447
4447     private Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource,
4448                                                                          Resource updateInfoResource, AuditingActionEnum actionEnum) {
4449         String currentTemplateName = currentResource.getDerivedFrom().get(0);
4450         String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0);
4451
4452         Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
4453                 .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName);
4454         if (dataModelResponse.isRight()) {
4455             StorageOperationStatus storageStatus = dataModelResponse.right().value();
4456             BeEcompErrorManager.getInstance()
4457                     .logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
4458             ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
4459                     componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
4460             log.trace("audit before sending response");
4461             componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
4462             return Either.right(responseFormat);
4463         }
4464
4465         if (!dataModelResponse.left().value()) {
4466             log.info("resource template with name {} does not inherit as original {}", updatedTemplateName,
4467                     currentTemplateName);
4468             ResponseFormat responseFormat = componentsUtils
4469                     .getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
4470             componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
4471
4472             return Either.right(responseFormat);
4473
4474         }
4475         return Either.left(true);
4476     }
4477
4478     public void validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
4479         log.debug("validate resource derivedFrom field");
4480         if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty())
4481                 || (resource.getDerivedFrom().get(0)) == null || (resource.getDerivedFrom().get(0).trim().isEmpty())) {
4482             log.info("derived from (template) field is missing for the resource");
4483             ResponseFormat responseFormat = componentsUtils
4484                     .getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
4485             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4486
4487             throw new ComponentException(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
4488         }
4489     }
4490
4491     private void validateResourceNameUniqueness(Resource resource) {
4492
4493         Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade
4494                 .validateComponentNameExists(resource.getName(), resource.getResourceType(),
4495                         resource.getComponentType());
4496         if (resourceOperationResponse.isLeft() && resourceOperationResponse.left().value()) {
4497             log.debug("resource with name: {}, already exists", resource.getName());
4498             throw new ComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(),
4499                     resource.getName());
4500         } else if(resourceOperationResponse.isRight()){
4501             log.debug("error while validateResourceNameExists for resource: {}", resource.getName());
4502             throw new StorageException(resourceOperationResponse.right().value());
4503         }
4504     }
4505
4506
4507     private void validateCategory(User user, Resource resource,
4508                                   AuditingActionEnum actionEnum, boolean inTransaction) {
4509
4510         List<CategoryDefinition> categories = resource.getCategories();
4511         if (CollectionUtils.isEmpty(categories)) {
4512             log.debug(CATEGORY_IS_EMPTY);
4513             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
4514                     ComponentTypeEnum.RESOURCE.getValue());
4515             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4516             throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
4517                     ComponentTypeEnum.RESOURCE.getValue());
4518         }
4519         if (categories.size() > 1) {
4520             log.debug("Must be only one category for resource");
4521             throw new ComponentException(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.RESOURCE.getValue());
4522         }
4523         CategoryDefinition category = categories.get(0);
4524         List<SubCategoryDefinition> subcategories = category.getSubcategories();
4525         if (CollectionUtils.isEmpty(subcategories)) {
4526             log.debug("Missinig subcategory for resource");
4527             throw new ComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
4528         }
4529         if (subcategories.size() > 1) {
4530             log.debug("Must be only one sub category for resource");
4531             throw new ComponentException(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
4532         }
4533
4534         SubCategoryDefinition subcategory = subcategories.get(0);
4535
4536         if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
4537             log.debug(CATEGORY_IS_EMPTY);
4538             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
4539                     ComponentTypeEnum.RESOURCE.getValue());
4540             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4541             throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
4542                     ComponentTypeEnum.RESOURCE.getValue());
4543         }
4544         if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
4545             log.debug(CATEGORY_IS_EMPTY);
4546             ResponseFormat responseFormat = componentsUtils.getResponseFormat(
4547                     ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
4548             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4549             throw new ComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
4550         }
4551
4552         validateCategoryListed(category, subcategory, user, resource, actionEnum, inTransaction);
4553     }
4554
4555     private void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory,
4556                                         User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
4557         ResponseFormat responseFormat;
4558         if (category != null && subcategory != null) {
4559             log.debug("validating resource category {} against valid categories list", category);
4560             Either<List<CategoryDefinition>, ActionStatus> categories = elementDao
4561                     .getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
4562             if (categories.isRight()) {
4563                 log.debug("failed to retrive resource categories from Titan");
4564                 responseFormat = componentsUtils.getResponseFormat(categories.right().value());
4565                 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4566                 throw new ComponentException(categories.right().value());
4567             }
4568             List<CategoryDefinition> categoryList = categories.left().value();
4569             Optional<CategoryDefinition> foundCategory = categoryList.stream()
4570                     .filter(cat -> cat.getName().equals(category.getName()))
4571                     .findFirst();
4572             if(!foundCategory.isPresent()){
4573                 log.debug("Category {} is not part of resource category group. Resource category valid values are {}",
4574                         category, categoryList);
4575                 failOnInvalidCategory(user, resource, actionEnum);
4576             }
4577             Optional<SubCategoryDefinition> foundSubcategory = foundCategory.get()
4578                     .getSubcategories()
4579                     .stream()
4580                     .filter(subcat -> subcat.getName().equals(subcategory.getName()))
4581                     .findFirst();
4582             if(!foundSubcategory.isPresent()){
4583                 log.debug("SubCategory {} is not part of resource category group. Resource subcategory valid values are {}",
4584                         subcategory, foundCategory.get().getSubcategories());
4585                 failOnInvalidCategory(user, resource, actionEnum);
4586             }
4587         }
4588     }
4589
4590     private void failOnInvalidCategory(User user, Resource resource, AuditingActionEnum actionEnum) {
4591         ResponseFormat responseFormat;
4592         responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY,
4593                 ComponentTypeEnum.RESOURCE.getValue());
4594         componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4595         throw new ComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY,
4596                 ComponentTypeEnum.RESOURCE.getValue());
4597     }
4598
4599     public void validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) {
4600         String vendorRelease = resource.getVendorRelease();
4601         log.debug("validate vendor relese name");
4602         if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) {
4603             log.info("vendor relese name is missing.");
4604             ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
4605             componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4606             throw new ComponentException(ActionStatus.MISSING_VENDOR_RELEASE);
4607         }
4608
4609         validateVendorReleaseName(vendorRelease, user, resource, actionEnum);
4610     }
4611
4612     public void validateVendorReleaseName(String vendorRelease, User user, Resource resource, AuditingActionEnum actionEnum) {
4613         if (vendorRelease != null) {
4614             if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
4615                 log.info("vendor release exceds limit.");
4616                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
4617                         ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
4618                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4619                 throw new ComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
4620             }
4621
4622             if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
4623                 log.info("vendor release  is not valid.");
4624                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
4625                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4626                 throw new ComponentException(ActionStatus.INVALID_VENDOR_RELEASE);
4627             }
4628         }
4629     }
4630
4631     private void validateVendorName(User user, Resource resource,
4632                                     AuditingActionEnum actionEnum) {
4633         String vendorName = resource.getVendorName();
4634         if (!ValidationUtils.validateStringNotEmpty(vendorName)) {
4635             log.info("vendor name is missing.");
4636             ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME);
4637             componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4638             throw new ComponentException(ActionStatus.MISSING_VENDOR_NAME);
4639         }
4640         validateVendorName(vendorName, user, resource, actionEnum);
4641     }
4642
4643     private void validateVendorName(String vendorName, User user, Resource resource,
4644                                     AuditingActionEnum actionEnum) {
4645         if (vendorName != null) {
4646             if (!ValidationUtils.validateVendorNameLength(vendorName)) {
4647                 log.info("vendor name exceds limit.");
4648                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
4649                         "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
4650                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4651                 throw new ComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
4652                         "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
4653             }
4654
4655             if (!ValidationUtils.validateVendorName(vendorName)) {
4656                 log.info("vendor name  is not valid.");
4657                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
4658                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4659                 throw new ComponentException(ActionStatus.INVALID_VENDOR_NAME);
4660             }
4661         }
4662     }
4663
4664     private void validateResourceVendorModelNumber(User user, Resource resource, AuditingActionEnum actionEnum) {
4665         String resourceVendorModelNumber = resource.getResourceVendorModelNumber();
4666         if (StringUtils.isNotEmpty(resourceVendorModelNumber)) {
4667             if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
4668                 log.info("resource vendor model number exceeds limit.");
4669                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
4670                         ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
4671                         "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
4672                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4673                 throw new ComponentException(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
4674                         "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
4675             }
4676             // resource vendor model number is currently validated as vendor
4677             // name
4678             if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) {
4679                 log.info("resource vendor model number  is not valid.");
4680                 ResponseFormat errorResponse = componentsUtils
4681                         .getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
4682                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4683                 throw new ComponentException(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
4684             }
4685         }
4686     }
4687
4688
4689     private void validateCost(Resource resource) {
4690         String cost = resource.getCost();
4691         if (cost != null) {
4692             if (!ValidationUtils.validateCost(cost)) {
4693                 log.debug("resource cost is invalid.");
4694                 throw new ComponentException(ActionStatus.INVALID_CONTENT);
4695             }
4696         }
4697     }
4698
4699     private void validateLicenseType(User user, Resource resource,
4700                                      AuditingActionEnum actionEnum) {
4701         log.debug("validate licenseType");
4702         String licenseType = resource.getLicenseType();
4703         if (licenseType != null) {
4704             List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration()
4705                     .getLicenseTypes();
4706             if (!licenseTypes.contains(licenseType)) {
4707                 log.debug("License type {} isn't configured", licenseType);
4708                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
4709                 if (actionEnum != null) {
4710                     // In update case, no audit is required
4711                     componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4712                 }
4713                 throw new ComponentException(ActionStatus.INVALID_CONTENT);
4714             }
4715         }
4716     }
4717
4718     private Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom(Resource currentResource,
4719                                                                        Resource updatedResource, String userId, boolean inTransaction) {
4720         Either<Operation, ResponseFormat> deleteArtifactByInterface;
4721         if (updatedResource.getDerivedFrom() != null) {
4722             log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId());
4723             log.debug("1. Removing interface artifacts from graph");
4724             // Remove all interface artifacts of resource
4725             String resourceId = updatedResource.getUniqueId();
4726             Map<String, InterfaceDefinition> interfaces = currentResource.getInterfaces();
4727
4728             if (interfaces != null) {
4729                 Collection<InterfaceDefinition> values = interfaces.values();
4730                 for (InterfaceDefinition interfaceDefinition : values) {
4731                     String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition);
4732
4733                     log.trace("Starting interface artifacts removal for interface type {}", interfaceType);
4734                     Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
4735                     if (operations != null) {
4736                         for (Entry<String, Operation> operationEntry : operations.entrySet()) {
4737                             Operation operation = operationEntry.getValue();
4738                             ArtifactDefinition implementation = operation.getImplementationArtifact();
4739                             if (implementation != null) {
4740                                 String uniqueId = implementation.getUniqueId();
4741                                 log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}",
4742                                         uniqueId, operationEntry.getKey(), interfaceType);
4743                                 // only thing that transacts and locks here
4744                                 deleteArtifactByInterface = artifactsBusinessLogic.deleteArtifactByInterface(resourceId,
4745                                         userId, uniqueId,
4746                                         true);
4747                                 if (deleteArtifactByInterface.isRight()) {
4748                                     log.debug("Couldn't remove artifact definition with id {}", uniqueId);
4749                                     if (!inTransaction) {
4750                                         titanDao.rollback();
4751                                     }
4752                                     return Either.right(deleteArtifactByInterface.right().value());
4753                                 }
4754                             } else {
4755                                 log.trace("No implementation found for operation {} - nothing to delete",
4756                                         operationEntry.getKey());
4757                             }
4758                         }
4759                     } else {
4760                         log.trace("No operations found for interface type {}", interfaceType);
4761                     }
4762                 }
4763             }
4764             log.debug("2. Removing properties");
4765             Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = propertyOperation
4766                     .deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId);
4767
4768             if (findPropertiesOfNode.isRight()
4769                     && !findPropertiesOfNode.right().value().equals(StorageOperationStatus.OK)) {
4770                 log.debug("Failed to remove all properties of resource");
4771                 if (!inTransaction) {
4772                     titanDao.rollback();
4773                 }
4774                 return Either.right(componentsUtils.getResponseFormat(
4775                         componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right().value())));
4776             }
4777
4778         } else {
4779             log.debug("Derived from wasn't changed during update");
4780         }
4781
4782         if (inTransaction) {
4783             return Either.left(true);
4784         }
4785         titanDao.commit();
4786         return Either.left(true);
4787
4788     }
4789
4790     /**** Auditing *******************/
4791
4792     protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) {
4793         WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
4794                 .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
4795
4796         WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
4797
4798         return webApplicationContext.getBean(class1);
4799     }
4800
4801     public ICapabilityTypeOperation getCapabilityTypeOperation() {
4802         return capabilityTypeOperation;
4803     }
4804
4805     public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) {
4806         this.capabilityTypeOperation = capabilityTypeOperation;
4807     }
4808
4809     public Either<Boolean, ResponseFormat> validatePropertiesDefaultValues(Resource resource) {
4810         log.debug("validate resource properties default values");
4811         Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4812         List<PropertyDefinition> properties = resource.getProperties();
4813         if (properties != null) {
4814             eitherResult = iterateOverProperties(properties);
4815         }
4816         return eitherResult;
4817     }
4818
4819     public Either<Boolean, ResponseFormat> iterateOverProperties(List<PropertyDefinition> properties){
4820         Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4821         String type = null;
4822         String innerType = null;
4823         for (PropertyDefinition property : properties) {
4824             if (!propertyOperation.isPropertyTypeValid(property)) {
4825                 log.info("Invalid type for property {}", property);
4826                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
4827                         ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
4828                 eitherResult = Either.right(responseFormat);
4829                 break;
4830             }
4831
4832             Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(
4833                     applicationDataTypeCache);
4834             if (allDataTypes.isRight()) {
4835                 return Either.right(allDataTypes.right().value());
4836             }
4837
4838             type = property.getType();
4839
4840             if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
4841                 ResponseFormat responseFormat = validateMapOrListPropertyType(property, innerType, allDataTypes.left().value());
4842                 if(responseFormat != null) {
4843                     break;
4844                 }
4845             }
4846             eitherResult = validateDefaultPropertyValue(property, allDataTypes.left().value(), type, innerType);
4847         }
4848         return eitherResult;
4849     }
4850
4851     private Either<Boolean,ResponseFormat> validateDefaultPropertyValue(PropertyDefinition property, Map<String, DataTypeDefinition> allDataTypes, String type, String innerType) {
4852         if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes)) {
4853             log.info("Invalid default value for property {}", property);
4854             ResponseFormat responseFormat;
4855             if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
4856                 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE,
4857                         property.getName(), type, innerType, property.getDefaultValue());
4858             } else {
4859                 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE,
4860                         property.getName(), type, property.getDefaultValue());
4861             }
4862             return Either.right(responseFormat);
4863
4864         }
4865         return Either.left(true);
4866     }
4867
4868     private ResponseFormat validateMapOrListPropertyType(PropertyDefinition property, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
4869         ResponseFormat responseFormat = null;
4870         ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation
4871                 .isPropertyInnerTypeValid(property, allDataTypes);
4872         innerType = propertyInnerTypeValid.getLeft();
4873         if (!propertyInnerTypeValid.getRight().booleanValue()) {
4874             log.info("Invalid inner type for property {}", property);
4875             responseFormat = componentsUtils.getResponseFormat(
4876                     ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
4877         }
4878         return responseFormat;
4879     }
4880
4881     @Override
4882     public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
4883         return deleteMarkedComponents(ComponentTypeEnum.RESOURCE);
4884     }
4885
4886     @Override
4887     public ComponentInstanceBusinessLogic getComponentInstanceBL() {
4888         return componentInstanceBusinessLogic;
4889     }
4890
4891     private String getComponentTypeForResponse(Component component) {
4892         String componentTypeForResponse = "SERVICE";
4893         if (component instanceof Resource) {
4894             componentTypeForResponse = ((Resource) component).getResourceType().name();
4895         }
4896         return componentTypeForResponse;
4897     }
4898
4899     public Either<Resource, ResponseFormat> getLatestResourceFromCsarUuid(String csarUuid, User user) {
4900         // validate user
4901         if (user != null) {
4902             validateUserExists(user, "Get resource from csar UUID",
4903                     false);
4904         }
4905         // get resource from csar uuid
4906         Either<Resource, StorageOperationStatus> either = toscaOperationFacade
4907                 .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, "");
4908         if (either.isRight()) {
4909             ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND,
4910                     csarUuid);
4911             return Either.right(resp);
4912         }
4913
4914         return Either.left(either.left().value());
4915     }
4916
4917     @Override
4918     public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(
4919             String componentId, String userId) {
4920         return null;
4921     }
4922
4923     private Map<String, List<CapabilityDefinition>> getValidComponentInstanceCapabilities(
4924             String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities,
4925             Map<String, List<UploadCapInfo>> uploadedCapabilities) {
4926
4927         Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
4928         uploadedCapabilities.forEach((k,v)->addValidComponentInstanceCapabilities(k,v,resourceId,defaultCapabilities,validCapabilitiesMap));
4929         return validCapabilitiesMap;
4930     }
4931
4932     private void addValidComponentInstanceCapabilities(String key, List<UploadCapInfo> capabilities, String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities, Map<String, List<CapabilityDefinition>> validCapabilitiesMap){
4933         String capabilityType = capabilities.get(0).getType();
4934         if (defaultCapabilities.containsKey(capabilityType)) {
4935             CapabilityDefinition defaultCapability = getCapability(resourceId, defaultCapabilities, capabilityType);
4936             validateCapabilityProperties(capabilities, resourceId, defaultCapability);
4937             List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
4938             validCapabilityList.add(defaultCapability);
4939             validCapabilitiesMap.put(key, validCapabilityList);
4940         } else {
4941             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType));
4942         }
4943     }
4944
4945     private void validateCapabilityProperties(List<UploadCapInfo> capabilities, String resourceId, CapabilityDefinition defaultCapability) {
4946         if (CollectionUtils.isEmpty(defaultCapability.getProperties())
4947                 && isNotEmpty(capabilities.get(0).getProperties())) {
4948             log.debug("Failed to validate capability {} of component {}. Property list is empty. ",
4949                     defaultCapability.getName(), resourceId);
4950             log.debug(
4951                     "Failed to update capability property values. Property list of fetched capability {} is empty. ",
4952                     defaultCapability.getName());
4953             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, resourceId));
4954         } else if (isNotEmpty(capabilities.get(0).getProperties())) {
4955             validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, capabilities.get(0));
4956         }
4957     }
4958
4959     private CapabilityDefinition getCapability(String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities, String capabilityType) {
4960         CapabilityDefinition defaultCapability;
4961         if (isNotEmpty(defaultCapabilities.get(capabilityType).get(0).getProperties())) {
4962             defaultCapability = defaultCapabilities.get(capabilityType).get(0);
4963         } else {
4964             Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade
4965                     .getToscaFullElement(resourceId);
4966             if (getFullComponentRes.isRight()) {
4967                 log.debug("Failed to get full component {}. Status is {}. ", resourceId,
4968                         getFullComponentRes.right().value());
4969                 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND,
4970                         resourceId));
4971             }
4972             defaultCapability = getFullComponentRes.left().value().getCapabilities().get(capabilityType).get(0);
4973         }
4974         return defaultCapability;
4975     }
4976
4977     private void validateUniquenessUpdateUploadedComponentInstanceCapability(
4978             CapabilityDefinition defaultCapability, UploadCapInfo uploadedCapability) {
4979         List<ComponentInstanceProperty> validProperties = new ArrayList<>();
4980         Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties().stream()
4981                 .collect(toMap(PropertyDefinition::getName, Function.identity()));
4982         List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
4983         for (UploadPropInfo property : uploadedProperties) {
4984             String propertyName = property.getName().toLowerCase();
4985             String propertyType = property.getType();
4986             ComponentInstanceProperty validProperty;
4987             if (defaultProperties.containsKey(propertyName) && propertTypeEqualsTo(defaultProperties, propertyName, propertyType)) {
4988                 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS,
4989                         propertyName));
4990             }
4991             validProperty = new ComponentInstanceProperty();
4992             validProperty.setName(propertyName);
4993             if (property.getValue() != null) {
4994                 validProperty.setValue(property.getValue().toString());
4995             }
4996             validProperty.setDescription(property.getDescription());
4997             validProperty.setPassword(property.isPassword());
4998             validProperties.add(validProperty);
4999         }
5000         defaultCapability.setProperties(validProperties);
5001     }
5002
5003     private boolean propertTypeEqualsTo(Map<String, PropertyDefinition> defaultProperties, String propertyName, String propertyType) {
5004         return propertyType != null && !defaultProperties.get(propertyName).getType().equals(propertyType);
5005     }
5006
5007     private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(
5008             List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle,
5009             Resource resource, User user) {
5010
5011         EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(
5012                 ArtifactOperationEnum.class);
5013         Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
5014         Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either
5015                 .left(nodeTypeArtifactsToHandle);
5016         try {
5017             // add all found Csar artifacts to list to upload
5018             List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
5019             List<NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
5020             List<NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
5021             for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
5022                 ArtifactDefinition foundArtifact;
5023
5024                 if (!existingArtifactsToHandle.isEmpty()) {
5025                     foundArtifact = existingArtifactsToHandle.stream()
5026                             .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst()
5027                             .orElse(null);
5028                     if (foundArtifact != null) {
5029                         if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()) == currNewArtifact
5030                                 .getArtifactType()) {
5031                             if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
5032                                 currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
5033                                 // if current artifact already exists, but has
5034                                 // different content, add him to the list to
5035                                 // update
5036                                 artifactsToUpdate.add(currNewArtifact);
5037                             }
5038                             // remove found artifact from the list of existing
5039                             // artifacts to handle, because it was already
5040                             // handled
5041                             existingArtifactsToHandle.remove(foundArtifact);
5042                             // and remove found artifact from the list to
5043                             // upload, because it should either be updated or be
5044                             // ignored
5045                             artifactsToUpload.remove(currNewArtifact);
5046                         } else {
5047                             log.debug("Can't upload two artifact with the same name {}.",
5048                                     currNewArtifact.getArtifactName());
5049                             ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(
5050                                     ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
5051                                     currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType().name(),
5052                                     foundArtifact.getArtifactType());
5053                             AuditingActionEnum auditingAction = artifactsBusinessLogic
5054                                     .detectAuditingType(artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
5055                                             ArtifactOperationEnum.CREATE), foundArtifact.getArtifactChecksum());
5056                             artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(),
5057                                     user, null, null, foundArtifact.getUniqueId(), responseFormat,
5058                                     resource.getComponentType(), null);
5059                             responseWrapper.setInnerElement(responseFormat);
5060                             break;
5061                         }
5062                     }
5063                 }
5064             }
5065             if (responseWrapper.isEmpty()) {
5066                 for (ArtifactDefinition currArtifact : existingArtifactsToHandle) {
5067                     if (currArtifact.getIsFromCsar()) {
5068                         artifactsToDelete.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
5069                     } else {
5070                         artifactsToUpdate.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
5071
5072                     }
5073                 }
5074             }
5075             if (responseWrapper.isEmpty()) {
5076                 if (!artifactsToUpload.isEmpty()) {
5077                     nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
5078                 }
5079                 if (!artifactsToUpdate.isEmpty()) {
5080                     nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
5081                 }
5082                 if (!artifactsToDelete.isEmpty()) {
5083                     nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
5084                 }
5085             }
5086             if (!responseWrapper.isEmpty()) {
5087                 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
5088             }
5089         } catch (Exception e) {
5090             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5091             responseWrapper.setInnerElement(responseFormat);
5092             log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
5093             nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
5094         }
5095         return nodeTypeArtifactsToHandleRes;
5096     }
5097
5098     ImmutablePair<String, String> buildNestedToscaResourceName(String nodeResourceType, String vfResourceName,
5099                                                                String nodeTypeFullName) {
5100         String actualType;
5101         String actualVfName;
5102         if (ResourceTypeEnum.CVFC.name().equals(nodeResourceType)) {
5103             actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name();
5104             actualType = ResourceTypeEnum.VFC.name();
5105         } else {
5106             actualVfName = vfResourceName;
5107             actualType = nodeResourceType;
5108         }
5109
5110         try {
5111             StringBuilder toscaResourceName = new StringBuilder(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
5112             String nameWithouNamespacePrefix = nodeTypeFullName
5113                     .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
5114             String[] findTypes = nameWithouNamespacePrefix.split("\\.");
5115             String resourceType = findTypes[0];
5116             String actualName = nameWithouNamespacePrefix.substring(resourceType.length());
5117
5118             if (actualName.startsWith(Constants.ABSTRACT)) {
5119                 toscaResourceName.append(resourceType.toLowerCase()).append('.')
5120                         .append(ValidationUtils.convertToSystemName(actualVfName));
5121             } else {
5122                 toscaResourceName.append(actualType.toLowerCase()).append('.')
5123                         .append(ValidationUtils.convertToSystemName(actualVfName)).append('.').append(Constants.ABSTRACT);
5124             }
5125             StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName);
5126             return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
5127                     previousToscaResourceName
5128                             .append(actualName.substring(actualName.split("\\.")[1].length() + 1).toLowerCase())
5129                             .toString());
5130         } catch (Exception e) {
5131             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
5132             log.debug("Exception occured when buildNestedToscaResourceName, error is:{}", e.getMessage(), e);
5133             throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfResourceName);
5134         }
5135     }
5136
5137     public ICacheMangerOperation getCacheManagerOperation() {
5138         return cacheManagerOperation;
5139     }
5140
5141     public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) {
5142         this.cacheManagerOperation = cacheManagerOperation;
5143     }
5144
5145     @Override
5146     public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId, List<String> dataParamsToReturn) {
5147
5148         ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
5149         Either<Resource, StorageOperationStatus> resourceResultEither = toscaOperationFacade.getToscaElement(resourceId,
5150                 paramsToRetuen);
5151
5152         if (resourceResultEither.isRight()) {
5153             if (resourceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
5154                 log.debug("Failed to found resource with id {} ", resourceId);
5155                 Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
5156             }
5157
5158             log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn);
5159             return Either.right(componentsUtils.getResponseFormatByResource(
5160                     componentsUtils.convertFromStorageResponse(resourceResultEither.right().value()), ""));
5161         }
5162
5163         Resource resource = resourceResultEither.left().value();
5164         UiComponentDataTransfer dataTransfer = uiComponentDataConverter.getUiDataTransferFromResourceByParams(resource,
5165                 dataParamsToReturn);
5166         return Either.left(dataTransfer);
5167     }
5168
5169     @Override
5170     public Either<Component, ActionStatus> shouldUpgradeToLatestDerived(Component clonedComponent) {
5171         Resource resource = (Resource) clonedComponent;
5172         if (ModelConverter.isAtomicComponent(resource.getResourceType())) {
5173             Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived = toscaOperationFacade
5174                     .shouldUpgradeToLatestDerived(resource);
5175             if (shouldUpgradeToLatestDerived.isRight()) {
5176                 return Either.right(
5177                         componentsUtils.convertFromStorageResponse(shouldUpgradeToLatestDerived.right().value()));
5178             }
5179             return Either.left(shouldUpgradeToLatestDerived.left().value());
5180         } else {
5181             return super.shouldUpgradeToLatestDerived(clonedComponent);
5182         }
5183     }
5184 }