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