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