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