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