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