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