Service Import - Node Template Relationship Template
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / components / impl / ServiceImportBusinessLogic.java
1 /*
2  * Copyright (C) 2020 CMCC, Inc. and others. All rights reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.openecomp.sdc.be.components.impl;
17
18 import static java.util.stream.Collectors.joining;
19 import static java.util.stream.Collectors.toList;
20 import static java.util.stream.Collectors.toMap;
21 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
22 import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaStringElement;
23 import static org.openecomp.sdc.be.components.impl.ImportUtils.getPropertyJsonStringValue;
24 import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN;
25
26 import com.google.gson.Gson;
27 import fj.data.Either;
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.EnumMap;
31 import java.util.HashMap;
32 import java.util.HashSet;
33 import java.util.Iterator;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.Optional;
37 import java.util.Set;
38 import java.util.regex.Pattern;
39 import lombok.Getter;
40 import lombok.Setter;
41 import org.apache.commons.collections.CollectionUtils;
42 import org.apache.commons.collections.MapUtils;
43 import org.apache.commons.lang3.StringUtils;
44 import org.apache.commons.lang3.tuple.ImmutablePair;
45 import org.openecomp.sdc.be.components.csar.CsarArtifactsAndGroupsBusinessLogic;
46 import org.openecomp.sdc.be.components.csar.CsarBusinessLogic;
47 import org.openecomp.sdc.be.components.csar.CsarInfo;
48 import org.openecomp.sdc.be.components.distribution.engine.IDistributionEngine;
49 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
50 import org.openecomp.sdc.be.components.impl.artifact.ArtifactOperationInfo;
51 import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException;
52 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
53 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
54 import org.openecomp.sdc.be.components.impl.utils.CINodeFilterUtils;
55 import org.openecomp.sdc.be.components.impl.utils.CreateServiceFromYamlParameter;
56 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
57 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
58 import org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic;
59 import org.openecomp.sdc.be.components.path.ForwardingPathValidator;
60 import org.openecomp.sdc.be.components.validation.NodeFilterValidator;
61 import org.openecomp.sdc.be.components.validation.ServiceDistributionValidation;
62 import org.openecomp.sdc.be.components.validation.component.ComponentContactIdValidator;
63 import org.openecomp.sdc.be.components.validation.component.ComponentDescriptionValidator;
64 import org.openecomp.sdc.be.components.validation.component.ComponentIconValidator;
65 import org.openecomp.sdc.be.components.validation.component.ComponentNameValidator;
66 import org.openecomp.sdc.be.components.validation.component.ComponentProjectCodeValidator;
67 import org.openecomp.sdc.be.components.validation.component.ComponentTagsValidator;
68 import org.openecomp.sdc.be.components.validation.component.ComponentValidator;
69 import org.openecomp.sdc.be.config.BeEcompErrorManager;
70 import org.openecomp.sdc.be.config.ConfigurationManager;
71 import org.openecomp.sdc.be.dao.api.ActionStatus;
72 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphDao;
73 import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils;
74 import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
75 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
76 import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition;
77 import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
78 import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition;
79 import org.openecomp.sdc.be.datatypes.elements.RequirementSubstitutionFilterPropertyDataDefinition;
80 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
81 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
82 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
83 import org.openecomp.sdc.be.impl.ComponentsUtils;
84 import org.openecomp.sdc.be.info.NodeTypeInfoToUpdateArtifacts;
85 import org.openecomp.sdc.be.model.ArtifactDefinition;
86 import org.openecomp.sdc.be.model.AttributeDefinition;
87 import org.openecomp.sdc.be.model.CapabilityDefinition;
88 import org.openecomp.sdc.be.model.CapabilityRequirementRelationship;
89 import org.openecomp.sdc.be.model.Component;
90 import org.openecomp.sdc.be.model.ComponentInstance;
91 import org.openecomp.sdc.be.model.ComponentInstanceInput;
92 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
93 import org.openecomp.sdc.be.model.ComponentParametersView;
94 import org.openecomp.sdc.be.model.DataTypeDefinition;
95 import org.openecomp.sdc.be.model.DistributionStatusEnum;
96 import org.openecomp.sdc.be.model.GroupDefinition;
97 import org.openecomp.sdc.be.model.InputDefinition;
98 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
99 import org.openecomp.sdc.be.model.LifecycleStateEnum;
100 import org.openecomp.sdc.be.model.NodeTypeInfo;
101 import org.openecomp.sdc.be.model.Operation;
102 import org.openecomp.sdc.be.model.OutputDefinition;
103 import org.openecomp.sdc.be.model.ParsedToscaYamlInfo;
104 import org.openecomp.sdc.be.model.PolicyDefinition;
105 import org.openecomp.sdc.be.model.PropertyDefinition;
106 import org.openecomp.sdc.be.model.RelationshipImpl;
107 import org.openecomp.sdc.be.model.RelationshipInfo;
108 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
109 import org.openecomp.sdc.be.model.RequirementDefinition;
110 import org.openecomp.sdc.be.model.Resource;
111 import org.openecomp.sdc.be.model.Service;
112 import org.openecomp.sdc.be.model.UploadAttributeInfo;
113 import org.openecomp.sdc.be.model.UploadComponentInstanceInfo;
114 import org.openecomp.sdc.be.model.UploadNodeFilterInfo;
115 import org.openecomp.sdc.be.model.UploadPropInfo;
116 import org.openecomp.sdc.be.model.UploadReqInfo;
117 import org.openecomp.sdc.be.model.UploadResourceInfo;
118 import org.openecomp.sdc.be.model.User;
119 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
120 import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement;
121 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
122 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
123 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeFilterOperation;
124 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
125 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
126 import org.openecomp.sdc.be.model.operations.StorageException;
127 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
128 import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
129 import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
130 import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
131 import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
132 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
133 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
134 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
135 import org.openecomp.sdc.be.tosca.CsarUtils;
136 import org.openecomp.sdc.be.ui.model.OperationUi;
137 import org.openecomp.sdc.be.utils.TypeUtils;
138 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
139 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
140 import org.openecomp.sdc.common.api.Constants;
141 import org.openecomp.sdc.common.datastructure.Wrapper;
142 import org.openecomp.sdc.common.kpi.api.ASDCKpiApi;
143 import org.openecomp.sdc.common.log.wrappers.Logger;
144 import org.openecomp.sdc.common.util.ValidationUtils;
145 import org.openecomp.sdc.exception.ResponseFormat;
146 import org.yaml.snakeyaml.Yaml;
147
148 @Getter
149 @Setter
150 @org.springframework.stereotype.Component("serviceImportBusinessLogic")
151 public class ServiceImportBusinessLogic {
152
153     protected static final String CREATE_RESOURCE = "Create Resource";
154     private static final String INITIAL_VERSION = "0.1";
155     private static final String IN_RESOURCE = " in resource {} ";
156     private static final String COMPONENT_INSTANCE_WITH_NAME = "component instance with name ";
157     private static final String COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE = "component instance with name {}  in resource {} ";
158     private static final String CERTIFICATION_ON_IMPORT = "certification on import";
159     private static final String VALIDATE_DERIVED_BEFORE_UPDATE = "validate derived before update";
160     private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
161     private static final String CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES = "Create Resource - validateCapabilityTypesCreate";
162     private static final String CATEGORY_IS_EMPTY = "Resource category is empty";
163     private static final Logger log = Logger.getLogger(ServiceImportBusinessLogic.class);
164
165     private final ComponentsUtils componentsUtils;
166     private final ToscaOperationFacade toscaOperationFacade;
167     private final UiComponentDataConverter uiComponentDataConverter;
168     private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
169     private final ServiceBusinessLogic serviceBusinessLogic;
170     private final CsarBusinessLogic csarBusinessLogic;
171     private final CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic;
172     private final LifecycleBusinessLogic lifecycleBusinessLogic;
173     private final CompositionBusinessLogic compositionBusinessLogic;
174     private final ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic;
175     private final ServiceImportParseLogic serviceImportParseLogic;
176     private final ComponentNodeFilterBusinessLogic componentNodeFilterBusinessLogic;
177     private final GroupBusinessLogic groupBusinessLogic;
178     private final PolicyBusinessLogic policyBusinessLogic;
179     private final JanusGraphDao janusGraphDao;
180     private final ArtifactsBusinessLogic artifactsBusinessLogic;
181     private final IGraphLockOperation graphLockOperation;
182
183     public ServiceImportBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
184                                       IGroupTypeOperation groupTypeOperation, GroupBusinessLogic groupBusinessLogic,
185                                       InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
186                                       ArtifactsBusinessLogic artifactsBusinessLogic, IDistributionEngine distributionEngine,
187                                       ComponentInstanceBusinessLogic componentInstanceBusinessLogic,
188                                       ServiceDistributionValidation serviceDistributionValidation, ForwardingPathValidator forwardingPathValidator,
189                                       UiComponentDataConverter uiComponentDataConverter, NodeFilterOperation serviceFilterOperation,
190                                       NodeFilterValidator serviceFilterValidator, ArtifactsOperations artifactToscaOperation,
191                                       ComponentContactIdValidator componentContactIdValidator, ComponentNameValidator componentNameValidator,
192                                       ComponentTagsValidator componentTagsValidator, ComponentValidator componentValidator,
193                                       ComponentIconValidator componentIconValidator, ComponentProjectCodeValidator componentProjectCodeValidator,
194                                       ComponentDescriptionValidator componentDescriptionValidator, final ComponentsUtils componentsUtils,
195                                       final ToscaOperationFacade toscaOperationFacade, final ServiceBusinessLogic serviceBusinessLogic,
196                                       final CsarBusinessLogic csarBusinessLogic,
197                                       final CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic,
198                                       final LifecycleBusinessLogic lifecycleBusinessLogic, final CompositionBusinessLogic compositionBusinessLogic,
199                                       final ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic,
200                                       final ServiceImportParseLogic serviceImportParseLogic,
201                                       final ComponentNodeFilterBusinessLogic componentNodeFilterBusinessLogic,
202                                       final PolicyBusinessLogic policyBusinessLogic, final JanusGraphDao janusGraphDao,
203                                       final IGraphLockOperation graphLockOperation) {
204         this.componentInstanceBusinessLogic = componentInstanceBusinessLogic;
205         this.uiComponentDataConverter = uiComponentDataConverter;
206         this.componentsUtils = componentsUtils;
207         this.toscaOperationFacade = toscaOperationFacade;
208         this.serviceBusinessLogic = serviceBusinessLogic;
209         this.csarBusinessLogic = csarBusinessLogic;
210         this.csarArtifactsAndGroupsBusinessLogic = csarArtifactsAndGroupsBusinessLogic;
211         this.lifecycleBusinessLogic = lifecycleBusinessLogic;
212         this.compositionBusinessLogic = compositionBusinessLogic;
213         this.resourceDataMergeBusinessLogic = resourceDataMergeBusinessLogic;
214         this.serviceImportParseLogic = serviceImportParseLogic;
215         this.componentNodeFilterBusinessLogic = componentNodeFilterBusinessLogic;
216         this.groupBusinessLogic = groupBusinessLogic;
217         this.policyBusinessLogic = policyBusinessLogic;
218         this.janusGraphDao = janusGraphDao;
219         this.artifactsBusinessLogic = artifactsBusinessLogic;
220         this.graphLockOperation = graphLockOperation;
221     }
222
223     public Service createService(Service service, AuditingActionEnum auditingAction, User user, Map<String, byte[]> csarUIPayload,
224                                  String payloadName) {
225         log.debug("enter createService");
226         service.setCreatorUserId(user.getUserId());
227         service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
228         service.setVersion(INITIAL_VERSION);
229         service.setConformanceLevel(ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel());
230         service.setDistributionStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED);
231         try {
232             final var serviceBeforeCreate = serviceBusinessLogic.validateServiceBeforeCreate(service, user, auditingAction);
233             if (serviceBeforeCreate.isRight()) {
234                 throw new ComponentException(ActionStatus.GENERAL_ERROR);
235             }
236             log.debug("enter createService,validateServiceBeforeCreate success");
237             String csarUUID = payloadName == null ? service.getCsarUUID() : payloadName;
238             log.debug("enter createService,get csarUUID:{}", csarUUID);
239             csarBusinessLogic.validateCsarBeforeCreate(service, csarUUID);
240             log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID);
241             return createServiceFromCsar(service, user, csarUIPayload, csarUUID);
242         } catch (Exception e) {
243             log.debug("Exception occured when createService,error is:{}", e.getMessage(), e);
244             throw new ComponentException(ActionStatus.GENERAL_ERROR);
245         }
246     }
247
248     protected Service createServiceFromCsar(Service service, User user, Map<String, byte[]> csarUIPayload, String csarUUID) {
249         log.trace("************* created successfully from YAML, resource TOSCA ");
250         try {
251             CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(service, null, user, csarUIPayload, csarUUID);
252             Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractTypesInfo();
253             Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = serviceImportParseLogic
254                 .findNodeTypesArtifactsToHandle(nodeTypesInfo, csarInfo, service);
255             if (findNodeTypesArtifactsToHandleRes.isRight()) {
256                 log.debug("failed to find node types for update with artifacts during import csar {}. ", csarInfo.getCsarUUID());
257                 throw new ComponentException(findNodeTypesArtifactsToHandleRes.right().value());
258             }
259             return createServiceFromYaml(service, csarInfo.getMainTemplateContent(), csarInfo.getMainTemplateName(), nodeTypesInfo, csarInfo,
260                 findNodeTypesArtifactsToHandleRes.left().value(), true, false, null, user.getUserId());
261         } catch (Exception e) {
262             log.debug("Exception occured when createServiceFromCsar,error is:{}", e.getMessage(), e);
263             throw new ComponentException(ActionStatus.GENERAL_ERROR);
264         }
265     }
266
267     protected Service createServiceFromYaml(Service service, String topologyTemplateYaml, String yamlName, Map<String, NodeTypeInfo> nodeTypesInfo,
268                                             CsarInfo csarInfo,
269                                             Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
270                                             boolean shouldLock, boolean inTransaction, String nodeName, final String userId)
271         throws BusinessLogicException {
272         List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
273         Service createdService;
274         CreateServiceFromYamlParameter csfyp = new CreateServiceFromYamlParameter();
275         try {
276             ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic
277                 .getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName, service);
278             log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", service.getName());
279             csfyp.setYamlName(yamlName);
280             csfyp.setParsedToscaYamlInfo(parsedToscaYamlInfo);
281             csfyp.setCreatedArtifacts(createdArtifacts);
282             csfyp.setTopologyTemplateYaml(topologyTemplateYaml);
283             csfyp.setNodeTypesInfo(nodeTypesInfo);
284             csfyp.setCsarInfo(csarInfo);
285             csfyp.setNodeName(nodeName);
286             createdService = createServiceAndRIsFromYaml(service, false, nodeTypesArtifactsToCreate, shouldLock, inTransaction, csfyp, userId);
287             log.debug("#createResourceFromYaml - The resource {} has been created ", service.getName());
288         } catch (ComponentException | BusinessLogicException e) {
289             log.debug("Create Service from yaml failed", e);
290             throw e;
291         } catch (StorageException e) {
292             log.debug("create Service From Yaml failed,get StorageException:{}", e);
293             throw e;
294         }
295         return createdService;
296     }
297
298     protected Service createServiceAndRIsFromYaml(Service service, boolean isNormative,
299                                                   Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
300                                                   boolean shouldLock, boolean inTransaction, CreateServiceFromYamlParameter csfyp,
301                                                   final String userId)
302         throws BusinessLogicException {
303         List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
304         String yamlName = csfyp.getYamlName();
305         ParsedToscaYamlInfo parsedToscaYamlInfo = csfyp.getParsedToscaYamlInfo();
306         List<ArtifactDefinition> createdArtifacts = csfyp.getCreatedArtifacts();
307         String topologyTemplateYaml = csfyp.getTopologyTemplateYaml();
308         Map<String, NodeTypeInfo> nodeTypesInfo = csfyp.getNodeTypesInfo();
309         CsarInfo csarInfo = csfyp.getCsarInfo();
310         String nodeName = csfyp.getNodeName();
311         if (shouldLock) {
312             Either<Boolean, ResponseFormat> lockResult = serviceBusinessLogic.lockComponentByName(service.getSystemName(), service, CREATE_RESOURCE);
313             if (lockResult.isRight()) {
314                 serviceImportParseLogic.rollback(inTransaction, service, createdArtifacts, nodeTypesNewCreatedArtifacts);
315                 throw new ComponentException(lockResult.right().value());
316             }
317             log.debug("name is locked {} status = {}", service.getSystemName(), lockResult);
318         }
319         try {
320             log.trace("************* Adding properties to service from interface yaml {}", yamlName);
321             Map<String, PropertyDefinition> properties = parsedToscaYamlInfo.getProperties();
322             if (properties != null && !properties.isEmpty()) {
323                 final List<PropertyDefinition> propertiesList = new ArrayList<>();
324                 properties.forEach((propertyName, propertyDefinition) -> {
325                     propertyDefinition.setName(propertyName);
326                     propertiesList.add(propertyDefinition);
327                 });
328                 service.setProperties(propertiesList);
329             }
330             log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
331             service = serviceImportParseLogic.createServiceTransaction(service, csarInfo.getModifier(), isNormative);
332             log.trace("************* Going to add inputs from yaml {}", yamlName);
333             Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
334             service = serviceImportParseLogic.createInputsOnService(service, inputs);
335             log.trace("************* Finished to add inputs from yaml {}", yamlName);
336             ListDataDefinition<RequirementSubstitutionFilterPropertyDataDefinition> substitutionFilterProperties = parsedToscaYamlInfo.getSubstitutionFilterProperties();
337             service = serviceImportParseLogic.createSubstitutionFilterOnService(service, substitutionFilterProperties);
338             log.trace("************* Added Substitution filter from interface yaml {}", yamlName);
339             Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo.getInstances();
340             log.trace("************* Going to create nodes, RI's and Relations  from yaml {}", yamlName);
341             service = createRIAndRelationsFromYaml(yamlName, service, uploadComponentInstanceInfoMap, topologyTemplateYaml,
342                 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, nodeName);
343             log.trace("************* Finished to create nodes, RI and Relation  from yaml {}", yamlName);
344             log.trace("************* Going to add outputs from yaml {}", yamlName);
345             Map<String, OutputDefinition> outputs = parsedToscaYamlInfo.getOutputs();
346             service = serviceImportParseLogic.createOutputsOnService(service, outputs, userId);
347             log.trace("************* Finished to add outputs from yaml {}", yamlName);
348
349             Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes
350                 = groupBusinessLogic.validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), service.getSystemName());
351             if (validateUpdateVfGroupNamesRes.isRight()) {
352                 serviceImportParseLogic.rollback(inTransaction, service, createdArtifacts, nodeTypesNewCreatedArtifacts);
353                 throw new ComponentException(validateUpdateVfGroupNamesRes.right().value());
354             }
355             Map<String, GroupDefinition> groups;
356             log.trace("************* Going to add groups from yaml {}", yamlName);
357             if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
358                 groups = validateUpdateVfGroupNamesRes.left().value();
359             } else {
360                 groups = parsedToscaYamlInfo.getGroups();
361             }
362             Either<Service, ResponseFormat> createGroupsOnResource = createGroupsOnResource(service, groups);
363             if (createGroupsOnResource.isRight()) {
364                 serviceImportParseLogic.rollback(inTransaction, service, createdArtifacts, nodeTypesNewCreatedArtifacts);
365                 throw new ComponentException(createGroupsOnResource.right().value());
366             }
367             service = createGroupsOnResource.left().value();
368
369             Either<Service, ResponseFormat> createPoliciesOnResource = createPoliciesOnResource(service, parsedToscaYamlInfo.getPolicies());
370             if (createPoliciesOnResource.isRight()) {
371                 serviceImportParseLogic.rollback(inTransaction, service, createdArtifacts, nodeTypesNewCreatedArtifacts);
372                 throw new ComponentException(createPoliciesOnResource.right().value());
373             }
374             service = createPoliciesOnResource.left().value();
375             log.trace("************* Going to add artifacts from yaml {}", yamlName);
376             NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToCreate);
377             Either<Service, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE,
378                 createdArtifacts, yamlName, csarInfo, service, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
379             if (createArtifactsEither.isRight()) {
380                 serviceImportParseLogic.rollback(inTransaction, service, createdArtifacts, nodeTypesNewCreatedArtifacts);
381                 throw new ComponentException(createArtifactsEither.right().value());
382             }
383             service = serviceImportParseLogic.getServiceWithGroups(createArtifactsEither.left().value().getUniqueId());
384             ASDCKpiApi.countCreatedResourcesKPI();
385             return service;
386         } catch (ComponentException | StorageException | BusinessLogicException e) {
387             serviceImportParseLogic.rollback(inTransaction, service, createdArtifacts, nodeTypesNewCreatedArtifacts);
388             throw e;
389         } finally {
390             if (!inTransaction) {
391                 janusGraphDao.commit();
392             }
393             if (shouldLock) {
394                 graphLockOperation.unlockComponentByName(service.getSystemName(), service.getUniqueId(), NodeTypeEnum.Resource);
395             }
396         }
397     }
398
399     protected Either<Resource, ResponseFormat> createOrUpdateArtifacts(ArtifactsBusinessLogic.ArtifactOperationEnum operation,
400                                                                        List<ArtifactDefinition> createdArtifacts, String yamlFileName,
401                                                                        CsarInfo csarInfo, Resource preparedResource,
402                                                                        NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts,
403                                                                        boolean inTransaction, boolean shouldLock) {
404         String nodeName = nodeTypeInfoToUpdateArtifacts.getNodeName();
405         Resource resource = preparedResource;
406         Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts
407             .getNodeTypesArtifactsToHandle();
408         if (preparedResource.getResourceType() == ResourceTypeEnum.VF) {
409             if (nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null && !nodeTypesArtifactsToHandle.get(nodeName).isEmpty()) {
410                 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = handleNodeTypeArtifacts(preparedResource,
411                     nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(), inTransaction, true);
412                 if (handleNodeTypeArtifactsRes.isRight()) {
413                     return Either.right(handleNodeTypeArtifactsRes.right().value());
414                 }
415             }
416         } else {
417             Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource, csarInfo, createdArtifacts,
418                 new ArtifactOperationInfo(false, false, operation), shouldLock, inTransaction);
419             log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
420             if (createdCsarArtifactsEither.isRight()) {
421                 return createdCsarArtifactsEither;
422             }
423             resource = createdCsarArtifactsEither.left().value();
424         }
425         return Either.left(resource);
426     }
427
428     protected Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo, List<ArtifactDefinition> createdArtifacts,
429                                                                      ArtifactOperationInfo artifactOperation, boolean shouldLock,
430                                                                      boolean inTransaction) {
431         if (csarInfo.getCsar() != null) {
432             createOrUpdateSingleNonMetaArtifactToComstants(resource, csarInfo, artifactOperation, shouldLock, inTransaction);
433             Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource, createdArtifacts, shouldLock,
434                 inTransaction, artifactOperation);
435             if (eitherCreateResult.isRight()) {
436                 return Either.right(eitherCreateResult.right().value());
437             }
438             Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
439             if (eitherGerResource.isRight()) {
440                 ResponseFormat responseFormat = componentsUtils
441                     .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
442                 return Either.right(responseFormat);
443             }
444             resource = eitherGerResource.left().value();
445             Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils
446                 .getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
447             if (artifacsMetaCsarStatus.isLeft()) {
448                 return getResourceResponseFormatEither(resource, csarInfo, createdArtifacts, artifactOperation, shouldLock, inTransaction,
449                     artifacsMetaCsarStatus);
450             } else {
451                 return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(resource, csarInfo, shouldLock, inTransaction);
452             }
453         }
454         return Either.left(resource);
455     }
456
457     protected void createOrUpdateSingleNonMetaArtifactToComstants(Resource resource, CsarInfo csarInfo, ArtifactOperationInfo artifactOperation,
458                                                                   boolean shouldLock, boolean inTransaction) {
459         String vendorLicenseModelId = null;
460         String vfLicenseModelId = null;
461         if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE) {
462             Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts();
463             if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
464                 for (Map.Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
465                     if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) {
466                         vendorLicenseModelId = artifactEntry.getValue().getUniqueId();
467                     }
468                     if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) {
469                         vfLicenseModelId = artifactEntry.getValue().getUniqueId();
470                     }
471                 }
472             }
473         }
474         createOrUpdateSingleNonMetaArtifact(resource, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL,
475             Constants.VENDOR_LICENSE_MODEL, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
476             Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId,
477             artifactOperation, null, true, shouldLock, inTransaction);
478         createOrUpdateSingleNonMetaArtifact(resource, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
479             ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL, Constants.VF_LICENSE_DISPLAY_NAME,
480             Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, artifactOperation, null, true, shouldLock, inTransaction);
481     }
482
483     private Either<Resource, ResponseFormat> getResourceResponseFormatEither(Resource resource, CsarInfo csarInfo,
484                                                                              List<ArtifactDefinition> createdArtifacts,
485                                                                              ArtifactOperationInfo artifactOperation, boolean shouldLock,
486                                                                              boolean inTransaction,
487                                                                              Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus) {
488         try {
489             String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
490             String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
491             Either<Resource, ResponseFormat> createArtifactsFromCsar;
492             if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
493                 createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic
494                     .createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts);
495             } else {
496                 Either<Component, ResponseFormat> result = csarArtifactsAndGroupsBusinessLogic
497                     .updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock,
498                         inTransaction);
499                 if ((result.left().value() instanceof Resource) && result.isLeft()) {
500                     Resource service1 = (Resource) result.left().value();
501                     createArtifactsFromCsar = Either.left(service1);
502                 } else {
503                     createArtifactsFromCsar = Either.right(result.right().value());
504                 }
505             }
506             if (createArtifactsFromCsar.isRight()) {
507                 log.debug("Couldn't create artifacts from artifacts.meta");
508                 return Either.right(createArtifactsFromCsar.right().value());
509             }
510             return Either.left(createArtifactsFromCsar.left().value());
511         } catch (Exception e) {
512             log.debug("Exception occured in getResourceResponseFormatEither, message:{}", e.getMessage(), e);
513             return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
514         }
515     }
516
517     private <T extends Component> Either<T, ResponseFormat> createOrUpdateNonMetaArtifactsComp(CsarInfo csarInfo, T component,
518                                                                                                List<ArtifactDefinition> createdArtifacts,
519                                                                                                boolean shouldLock, boolean inTransaction,
520                                                                                                ArtifactOperationInfo artifactOperation) {
521         Either<T, ResponseFormat> resStatus = null;
522         Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
523         try {
524             Either<List<CsarUtils.NonMetaArtifactInfo>, String> artifactPathAndNameList = getValidArtifactNames(csarInfo, collectedWarningMessages);
525             if (artifactPathAndNameList.isRight()) {
526                 return Either.right(
527                     getComponentsUtils().getResponseFormatByArtifactId(ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right().value()));
528             }
529             EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
530             if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
531                 vfCsarArtifactsToHandle = new EnumMap<>(ArtifactsBusinessLogic.ArtifactOperationEnum.class);
532                 vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left().value());
533             } else {
534                 Either<EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(
535                     component, artifactPathAndNameList.left().value(), csarInfo.getModifier());
536                 if (findVfCsarArtifactsToHandleRes.isRight()) {
537                     resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value());
538                 }
539                 if (resStatus == null) {
540                     vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left().value();
541                 }
542             }
543             if (resStatus == null && vfCsarArtifactsToHandle != null) {
544                 resStatus = processCsarArtifacts(csarInfo, component, createdArtifacts, shouldLock, inTransaction, resStatus,
545                     vfCsarArtifactsToHandle);
546             }
547             if (resStatus == null) {
548                 resStatus = Either.left(component);
549             }
550         } catch (Exception e) {
551             resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
552             log.debug("Exception occured in createNonMetaArtifacts, message:{}", e.getMessage(), e);
553         } finally {
554             CsarUtils.handleWarningMessages(collectedWarningMessages);
555         }
556         return resStatus;
557     }
558
559     protected Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource,
560                                                                               List<ArtifactDefinition> createdArtifacts, boolean shouldLock,
561                                                                               boolean inTransaction, ArtifactOperationInfo artifactOperation) {
562         return createOrUpdateNonMetaArtifactsComp(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, artifactOperation);
563     }
564
565     protected <T extends Component> Either<T, ResponseFormat> processCsarArtifacts(CsarInfo csarInfo, Component comp,
566                                                                                    List<ArtifactDefinition> createdArtifacts, boolean shouldLock,
567                                                                                    boolean inTransaction, Either<T, ResponseFormat> resStatus,
568                                                                                    EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>> vfCsarArtifactsToHandle) {
569         for (Map.Entry<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle
570             .entrySet()) {
571             Optional<ResponseFormat> optionalCreateInDBError = currArtifactOperationPair.getValue().stream().map(
572                 e -> createOrUpdateSingleNonMetaArtifact(comp, csarInfo, e.getPath(), e.getArtifactName(), e.getArtifactType(),
573                     e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(), CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(),
574                     new ArtifactOperationInfo(false, false, currArtifactOperationPair.getKey()), createdArtifacts, e.isFromCsar(), shouldLock,
575                     inTransaction)).filter(Either::isRight).map(e -> e.right().value()).findAny();
576             if (optionalCreateInDBError.isPresent()) {
577                 resStatus = Either.right(optionalCreateInDBError.get());
578                 break;
579             }
580         }
581         return resStatus;
582     }
583
584     protected Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Component component, CsarInfo csarInfo, String artifactPath,
585                                                                                   String artifactFileName, String artifactType,
586                                                                                   ArtifactGroupTypeEnum artifactGroupType, String artifactLabel,
587                                                                                   String artifactDisplayName, String artifactDescription,
588                                                                                   String artifactId, ArtifactOperationInfo operation,
589                                                                                   List<ArtifactDefinition> createdArtifacts, boolean isFromCsar,
590                                                                                   boolean shouldLock, boolean inTransaction) {
591         byte[] artifactFileBytes = null;
592         if (csarInfo.getCsar().containsKey(artifactPath)) {
593             artifactFileBytes = csarInfo.getCsar().get(artifactPath);
594         }
595         Either<Boolean, ResponseFormat> result = Either.left(true);
596         if (operation.getArtifactOperationEnum() == ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE
597             || operation.getArtifactOperationEnum() == ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE) {
598             if (serviceImportParseLogic.isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) {
599                 Either<ArtifactDefinition, ResponseFormat> handleDelete = artifactsBusinessLogic
600                     .handleDelete(component.getUniqueId(), artifactId, csarInfo.getModifier(), component, shouldLock, inTransaction);
601                 if (handleDelete.isRight()) {
602                     result = Either.right(handleDelete.right().value());
603                 }
604                 return result;
605             }
606             if (org.apache.commons.lang.StringUtils.isEmpty(artifactId) && artifactFileBytes != null) {
607                 operation = new ArtifactOperationInfo(false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE);
608             }
609         }
610         if (artifactFileBytes != null) {
611             Map<String, Object> vendorLicenseModelJson = ArtifactUtils
612                 .buildJsonForUpdateArtifact(artifactId, artifactFileName, artifactType, artifactGroupType, artifactLabel, artifactDisplayName,
613                     artifactDescription, artifactFileBytes, null, isFromCsar);
614             Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic
615                 .createOrUpdateCsarArtifactFromJson(component, csarInfo.getModifier(), vendorLicenseModelJson, operation);
616             serviceImportParseLogic.addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
617             if (eitherNonMetaArtifacts.isRight()) {
618                 BeEcompErrorManager.getInstance().logInternalFlowError("UploadLicenseArtifact",
619                     "Failed to upload license artifact: " + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(),
620                     BeEcompErrorManager.ErrorSeverity.WARNING);
621                 return Either.right(eitherNonMetaArtifacts.right().value());
622             }
623         }
624         return result;
625     }
626
627     private Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource,
628                                                                                      Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
629                                                                                      List<ArtifactDefinition> createdArtifacts, User user,
630                                                                                      boolean inTransaction, boolean ignoreLifecycleState) {
631         List<ArtifactDefinition> handleNodeTypeArtifactsRequestRes;
632         Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null;
633         Either<Resource, ResponseFormat> changeStateResponse;
634         try {
635             changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction);
636             if (changeStateResponse.isRight()) {
637                 return Either.right(changeStateResponse.right().value());
638             }
639             nodeTypeResource = changeStateResponse.left().value();
640             List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>();
641             log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName());
642             for (Map.Entry<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle
643                 .entrySet()) {
644                 ArtifactsBusinessLogic.ArtifactOperationEnum curOperation = curOperationEntry.getKey();
645                 List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue();
646                 if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) {
647                     log.debug("************* Going to {} artifact to vfc {}", curOperation.name(), nodeTypeResource.getName());
648                     handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic
649                         .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user, createdArtifacts,
650                             new ArtifactOperationInfo(false, ignoreLifecycleState, curOperation), false, inTransaction);
651                     if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(curOperation)) {
652                         createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes);
653                     }
654                     handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes);
655                 }
656             }
657             if (handleNodeTypeArtifactsRes == null) {
658                 handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts);
659             }
660         } catch (Exception e) {
661             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
662             handleNodeTypeArtifactsRes = Either.right(responseFormat);
663             log.debug("Exception occured when handleVfcArtifacts, error is:{}", e.getMessage(), e);
664         }
665         return handleNodeTypeArtifactsRes;
666     }
667
668     private Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) {
669         Either<Resource, ResponseFormat> checkoutResourceRes;
670         try {
671             if (!resource.getComponentMetadataDefinition().getMetadataDataDefinition().getState()
672                 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
673                 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic
674                     .changeComponentState(resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
675                         new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
676                             LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR), inTransaction, true);
677                 if (checkoutRes.isRight()) {
678                     checkoutResourceRes = Either.right(checkoutRes.right().value());
679                 } else {
680                     checkoutResourceRes = Either.left((Resource) checkoutRes.left().value());
681                 }
682             } else {
683                 checkoutResourceRes = Either.left(resource);
684             }
685         } catch (Exception e) {
686             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
687             checkoutResourceRes = Either.right(responseFormat);
688             log.debug("Exception occured when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(), e);
689         }
690         return checkoutResourceRes;
691     }
692
693     protected Either<Service, ResponseFormat> createOrUpdateArtifacts(ArtifactOperationEnum operation, List<ArtifactDefinition> createdArtifacts,
694                                                                       String yamlFileName, CsarInfo csarInfo, Service preparedService,
695                                                                       NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts,
696                                                                       boolean inTransaction, boolean shouldLock) {
697         Either<Service, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedService, csarInfo, createdArtifacts,
698             new ArtifactOperationInfo(false, false, operation), shouldLock, inTransaction);
699         log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
700         if (createdCsarArtifactsEither.isRight()) {
701             return createdCsarArtifactsEither;
702         }
703         return Either.left(createdCsarArtifactsEither.left().value());
704     }
705
706     protected Either<Service, ResponseFormat> handleVfCsarArtifacts(Service service, CsarInfo csarInfo, List<ArtifactDefinition> createdArtifacts,
707                                                                     ArtifactOperationInfo artifactOperation, boolean shouldLock,
708                                                                     boolean inTransaction) {
709         if (csarInfo.getCsar() != null) {
710             String vendorLicenseModelId = null;
711             String vfLicenseModelId = null;
712             if (artifactOperation.getArtifactOperationEnum() == ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE) {
713                 Map<String, ArtifactDefinition> deploymentArtifactsMap = service.getDeploymentArtifacts();
714                 if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
715                     for (Map.Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
716                         if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) {
717                             vendorLicenseModelId = artifactEntry.getValue().getUniqueId();
718                         }
719                         if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) {
720                             vfLicenseModelId = artifactEntry.getValue().getUniqueId();
721                         }
722                     }
723                 }
724             }
725             createOrUpdateSingleNonMetaArtifact(service, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL,
726                 Constants.VENDOR_LICENSE_MODEL, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
727                 Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId,
728                 artifactOperation, null, true, shouldLock, inTransaction);
729             createOrUpdateSingleNonMetaArtifact(service, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
730                 ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL,
731                 Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, artifactOperation, null, true, shouldLock,
732                 inTransaction);
733             Either<Service, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, service, createdArtifacts, shouldLock,
734                 inTransaction, artifactOperation);
735             if (eitherCreateResult.isRight()) {
736                 return Either.right(eitherCreateResult.right().value());
737             }
738             Either<Service, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
739             if (eitherGerResource.isRight()) {
740                 ResponseFormat responseFormat = componentsUtils
741                     .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), service,
742                         ComponentTypeEnum.SERVICE);
743                 return Either.right(responseFormat);
744             }
745             service = eitherGerResource.left().value();
746             Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils
747                 .getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
748             if (artifacsMetaCsarStatus.isLeft()) {
749                 String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
750                 String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
751                 Either<Service, ResponseFormat> createArtifactsFromCsar;
752                 if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
753                     createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic
754                         .createResourceArtifactsFromCsar(csarInfo, service, artifactsContents, artifactsFileName, createdArtifacts);
755                 } else {
756                     Either<Component, ResponseFormat> result = csarArtifactsAndGroupsBusinessLogic
757                         .updateResourceArtifactsFromCsar(csarInfo, service, artifactsContents, artifactsFileName, createdArtifacts, shouldLock,
758                             inTransaction);
759                     if ((result.left().value() instanceof Service) && result.isLeft()) {
760                         Service service1 = (Service) result.left().value();
761                         createArtifactsFromCsar = Either.left(service1);
762                     } else {
763                         createArtifactsFromCsar = Either.right(result.right().value());
764                     }
765                 }
766                 if (createArtifactsFromCsar.isRight()) {
767                     log.debug("Couldn't create artifacts from artifacts.meta");
768                     return Either.right(createArtifactsFromCsar.right().value());
769                 }
770                 return Either.left(createArtifactsFromCsar.left().value());
771             } else {
772                 return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(service, csarInfo, shouldLock, inTransaction);
773             }
774         }
775         return Either.left(service);
776     }
777
778     protected Either<Service, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Service resource,
779                                                                              List<ArtifactDefinition> createdArtifacts, boolean shouldLock,
780                                                                              boolean inTransaction, ArtifactOperationInfo artifactOperation) {
781         return createOrUpdateNonMetaArtifactsComp(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, artifactOperation);
782     }
783
784     protected Either<EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(
785         Component component, List<CsarUtils.NonMetaArtifactInfo> artifactPathAndNameList, User user) {
786         List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
787         if (component.getDeploymentArtifacts() != null && !component.getDeploymentArtifacts().isEmpty()) {
788             existingArtifacts.addAll(component.getDeploymentArtifacts().values());
789         }
790         if (component.getArtifacts() != null && !component.getArtifacts().isEmpty()) {
791             existingArtifacts.addAll(component.getArtifacts().values());
792         }
793         existingArtifacts = existingArtifacts.stream().filter(this::isNonMetaArtifact).collect(toList());
794         List<String> artifactsToIgnore = new ArrayList<>();
795         if (component.getGroups() != null) {
796             component.getGroups().forEach(g -> {
797                 if (g.getArtifacts() != null && !g.getArtifacts().isEmpty()) {
798                     artifactsToIgnore.addAll(g.getArtifacts());
799                 }
800             });
801         }
802         existingArtifacts = existingArtifacts.stream().filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(toList());
803         return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, component, user);
804     }
805
806     private boolean isNonMetaArtifact(ArtifactDefinition artifact) {
807         boolean result = true;
808         if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) {
809             result = false;
810         }
811         return result;
812     }
813
814     private boolean isValidArtifactType(ArtifactDefinition artifact) {
815         final String artifactType = artifact.getArtifactType();
816         return artifactType != null
817             && !ArtifactTypeEnum.VENDOR_LICENSE.getType().equals(ArtifactTypeEnum.findType(artifactType))
818             && !ArtifactTypeEnum.VF_LICENSE.getType().equals(ArtifactTypeEnum.findType(artifactType));
819     }
820
821     protected Either<EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(
822         List<CsarUtils.NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle, Component component,
823         User user) {
824         EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(
825             ArtifactsBusinessLogic.ArtifactOperationEnum.class);
826         Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
827         Either<EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either
828             .left(nodeTypeArtifactsToHandle);
829         try {
830             List<CsarUtils.NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
831             List<CsarUtils.NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
832             List<CsarUtils.NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
833             for (CsarUtils.NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
834                 ArtifactDefinition foundArtifact;
835                 if (!existingArtifactsToHandle.isEmpty()) {
836                     foundArtifact = existingArtifactsToHandle.stream().filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName()))
837                         .findFirst().orElse(null);
838                     if (foundArtifact != null) {
839                         if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()).equals(currNewArtifact.getArtifactType())) {
840                             if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
841                                 currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
842                                 artifactsToUpdate.add(currNewArtifact);
843                             }
844                             existingArtifactsToHandle.remove(foundArtifact);
845                             artifactsToUpload.remove(currNewArtifact);
846                         } else {
847                             log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
848                             ResponseFormat responseFormat = ResponseFormatManager.getInstance()
849                                 .getResponseFormat(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(),
850                                     currNewArtifact.getArtifactType(), foundArtifact.getArtifactType());
851                             AuditingActionEnum auditingAction = artifactsBusinessLogic.detectAuditingType(
852                                 new ArtifactOperationInfo(false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE),
853                                 foundArtifact.getArtifactChecksum());
854                             artifactsBusinessLogic.handleAuditing(auditingAction, component, component.getUniqueId(), user, null, null,
855                                 foundArtifact.getUniqueId(), responseFormat, component.getComponentType(), null);
856                             responseWrapper.setInnerElement(responseFormat);
857                             break;
858                         }
859                     }
860                 }
861             }
862             if (responseWrapper.isEmpty()) {
863                 for (ArtifactDefinition currArtifact : existingArtifactsToHandle) {
864                     if (currArtifact.getIsFromCsar()) {
865                         artifactsToDelete.add(new CsarUtils.NonMetaArtifactInfo(currArtifact.getArtifactName(), null,
866                             ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null,
867                             currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
868                     } else {
869                         artifactsToUpdate.add(new CsarUtils.NonMetaArtifactInfo(currArtifact.getArtifactName(), null,
870                             ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null,
871                             currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
872                     }
873                 }
874             }
875             if (responseWrapper.isEmpty()) {
876                 if (!artifactsToUpload.isEmpty()) {
877                     nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE, artifactsToUpload);
878                 }
879                 if (!artifactsToUpdate.isEmpty()) {
880                     nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE, artifactsToUpdate);
881                 }
882                 if (!artifactsToDelete.isEmpty()) {
883                     nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE, artifactsToDelete);
884                 }
885             }
886             if (!responseWrapper.isEmpty()) {
887                 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
888             }
889         } catch (Exception e) {
890             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
891             responseWrapper.setInnerElement(responseFormat);
892             log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
893             nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
894         }
895         return nodeTypeArtifactsToHandleRes;
896     }
897
898     protected Either<List<CsarUtils.NonMetaArtifactInfo>, String> getValidArtifactNames(CsarInfo csarInfo,
899                                                                                         Map<String, Set<List<String>>> collectedWarningMessages) {
900         List<CsarUtils.NonMetaArtifactInfo> artifactPathAndNameList = csarInfo.getCsar().entrySet().stream()
901             .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
902             .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), collectedWarningMessages)).filter(Either::isLeft)
903             .map(e -> e.left().value()).collect(toList());
904         Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
905         for (CsarUtils.NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
906             if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) {
907                 return Either.right(nonMetaArtifactInfo.getArtifactName());
908             }
909         }
910         return Either.left(artifactPathAndNameList);
911     }
912
913     protected Either<Service, ResponseFormat> createGroupsOnResource(Service service, Map<String, GroupDefinition> groups) {
914         if (groups != null && !groups.isEmpty()) {
915             List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, service);
916             serviceImportParseLogic.handleGroupsProperties(service, groups);
917             serviceImportParseLogic.fillGroupsFinalFields(groupsAsList);
918             Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(service, groupsAsList, true);
919             if (createGroups.isRight()) {
920                 return Either.right(createGroups.right().value());
921             }
922         } else {
923             return Either.left(service);
924         }
925         return getServiceResponseFormatEither(service);
926     }
927
928     private Either<Service, ResponseFormat> createPoliciesOnResource(Service service,
929                                                                      Map<String, PolicyDefinition> policies) {
930         if (MapUtils.isNotEmpty(policies)) {
931             policyBusinessLogic.createPolicies(service, policies);
932         } else {
933             return Either.left(service);
934         }
935         return getServiceResponseFormatEither(service);
936     }
937
938     private Either<Service, ResponseFormat> getServiceResponseFormatEither(Service service) {
939         Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
940         if (updatedResource.isRight()) {
941             ResponseFormat responseFormat = componentsUtils
942                 .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service,
943                     ComponentTypeEnum.SERVICE);
944             return Either.right(responseFormat);
945         }
946         return Either.left(updatedResource.left().value());
947     }
948
949     protected List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, Service component) {
950         List<GroupDefinition> result = new ArrayList<>();
951         List<ComponentInstance> componentInstances = component.getComponentInstances();
952         if (groups != null) {
953             for (Map.Entry<String, GroupDefinition> entry : groups.entrySet()) {
954                 String groupName = entry.getKey();
955                 GroupDefinition groupDefinition = entry.getValue();
956                 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
957                 updatedGroupDefinition.setMembers(null);
958                 Map<String, String> members = groupDefinition.getMembers();
959                 if (members != null) {
960                     serviceImportParseLogic.updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members);
961                 }
962                 result.add(updatedGroupDefinition);
963             }
964         }
965         return result;
966     }
967
968     protected Resource createRIAndRelationsFromYaml(String yamlName, Resource resource,
969                                                     Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap,
970                                                     String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
971                                                     Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
972                                                     Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
973                                                     String nodeName) {
974         try {
975             log.debug("************* Going to create all nodes {}", yamlName);
976             handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts, nodeTypesInfo,
977                 csarInfo, nodeName);
978             log.debug("************* Going to create all resource instances {}", yamlName);
979             resource = createResourceInstances(yamlName, resource, uploadComponentInstanceInfoMap, csarInfo.getCreatedNodes());
980             log.debug("************* Finished to create all resource instances {}", yamlName);
981             resource = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap);
982             log.debug("************* Going to create positions {}", yamlName);
983             compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier().getUserId());
984             log.debug("************* Finished to set positions {}", yamlName);
985             return resource;
986         } catch (Exception e) {
987             throw new ComponentException(ActionStatus.GENERAL_ERROR);
988         }
989     }
990
991     protected Resource createResourceInstancesRelations(User user, String yamlName, Resource resource,
992                                                         Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
993         log.debug("#createResourceInstancesRelations - Going to create relations ");
994         List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
995         if (((MapUtils.isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)) &&
996             resource.getResourceType() != ResourceTypeEnum.PNF)) { // PNF can have no resource instances
997             log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ",
998                 resource.getUniqueId(), yamlName);
999             BeEcompErrorManager.getInstance()
1000                 .logInternalDataError("createResourceInstancesRelations", "No instances found in a resource or nn yaml template. ",
1001                     BeEcompErrorManager.ErrorSeverity.ERROR);
1002             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName));
1003         }
1004         Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
1005         Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
1006         Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
1007         Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
1008         Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
1009         Map<String, List<AttributeDefinition>> instAttributes = new HashMap<>();
1010         Map<String, Resource> originCompMap = new HashMap<>();
1011         List<RequirementCapabilityRelDef> relations = new ArrayList<>();
1012         Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
1013         Map<String, UploadNodeFilterInfo> instNodeFilter = new HashMap<>();
1014
1015         log.debug("enter ServiceImportBusinessLogic createResourceInstancesRelations#createResourceInstancesRelations - Before get all datatypes. ");
1016         final ApplicationDataTypeCache applicationDataTypeCache = serviceBusinessLogic.applicationDataTypeCache;
1017         if (applicationDataTypeCache != null) {
1018             Resource finalResource = resource;
1019             uploadResInstancesMap.values().forEach(
1020                 i -> processComponentInstance(yamlName, finalResource, componentInstancesList,
1021                     componentsUtils.getAllDataTypes(applicationDataTypeCache, finalResource.getModel()), instProperties, instCapabilities,
1022                     instRequirements, instDeploymentArtifacts, instArtifacts, instAttributes, originCompMap, instInputs, instNodeFilter, i));
1023         }
1024         serviceImportParseLogic.associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties);
1025         serviceImportParseLogic.associateComponentInstanceInputsToComponent(yamlName, resource, instInputs);
1026         serviceImportParseLogic.associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts);
1027         serviceImportParseLogic.associateArtifactsToInstances(yamlName, resource, instArtifacts);
1028         serviceImportParseLogic.associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements);
1029         serviceImportParseLogic.associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes);
1030         resource = serviceImportParseLogic.getResourceAfterCreateRelations(resource);
1031         serviceImportParseLogic.addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations);
1032         serviceImportParseLogic.associateResourceInstances(yamlName, resource, relations);
1033         handleSubstitutionMappings(resource, uploadResInstancesMap);
1034         log.debug("************* in create relations, getResource start");
1035         Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
1036         log.debug("************* in create relations, getResource end");
1037         if (eitherGetResource.isRight()) {
1038             throw new ComponentException(
1039                 componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource));
1040         }
1041         return eitherGetResource.left().value();
1042     }
1043
1044     protected void processProperty(Resource resource, ComponentInstance currentCompInstance, Map<String, DataTypeDefinition> allDataTypes,
1045                                    Map<String, InputDefinition> currPropertiesMap, List<ComponentInstanceInput> instPropList,
1046                                    List<UploadPropInfo> propertyList) {
1047         UploadPropInfo propertyInfo = propertyList.get(0);
1048         String propName = propertyInfo.getName();
1049         if (!currPropertiesMap.containsKey(propName)) {
1050             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName));
1051         }
1052         processProperty(allDataTypes, currPropertiesMap, instPropList, propertyInfo, propName, resource.getInputs());
1053     }
1054
1055     private void processProperty(Map<String, DataTypeDefinition> allDataTypes, Map<String, InputDefinition> currPropertiesMap,
1056                                  List<ComponentInstanceInput> instPropList, UploadPropInfo propertyInfo, String propName,
1057                                  List<InputDefinition> inputs2) {
1058         InputDefinition curPropertyDef = currPropertiesMap.get(propName);
1059         ComponentInstanceInput property = null;
1060         String value = null;
1061         List<GetInputValueDataDefinition> getInputs = null;
1062         boolean isValidate = true;
1063         if (propertyInfo.getValue() != null) {
1064             getInputs = propertyInfo.getGet_input();
1065             isValidate = getInputs == null || getInputs.isEmpty();
1066             if (isValidate) {
1067                 value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
1068             } else {
1069                 value = getPropertyJsonStringValue(propertyInfo.getValue(), TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
1070             }
1071         }
1072         property = new ComponentInstanceInput(curPropertyDef, value, null);
1073         String validPropertyVAlue = serviceBusinessLogic.validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
1074         property.setValue(validPropertyVAlue);
1075         if (isNotEmpty(getInputs)) {
1076             List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
1077             for (GetInputValueDataDefinition getInput : getInputs) {
1078                 List<InputDefinition> inputs = inputs2;
1079                 if (CollectionUtils.isEmpty(inputs)) {
1080                     throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1081                 }
1082                 Optional<InputDefinition> optional = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findAny();
1083                 if (!optional.isPresent()) {
1084                     throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1085                 }
1086                 InputDefinition input = optional.get();
1087                 getInput.setInputId(input.getUniqueId());
1088                 getInputValues.add(getInput);
1089                 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
1090                 processGetInput(getInputValues, inputs, getInputIndex);
1091             }
1092             property.setGetInputValues(getInputValues);
1093         }
1094         instPropList.add(property);
1095         currPropertiesMap.remove(property.getName());
1096     }
1097
1098     protected void handleSubstitutionMappings(Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
1099         if (resource.getResourceType() == ResourceTypeEnum.VF) {
1100             Either<Resource, StorageOperationStatus> getResourceRes = toscaOperationFacade.getToscaFullElement(resource.getUniqueId());
1101             if (getResourceRes.isRight()) {
1102                 ResponseFormat responseFormat = componentsUtils
1103                     .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
1104                 throw new ComponentException(responseFormat);
1105             }
1106             getResourceRes = updateCalculatedCapReqWithSubstitutionMappings(getResourceRes.left().value(), uploadResInstancesMap);
1107             if (getResourceRes.isRight()) {
1108                 ResponseFormat responseFormat = componentsUtils
1109                     .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
1110                 throw new ComponentException(responseFormat);
1111             }
1112         }
1113     }
1114
1115     protected Resource createResourceInstances(String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
1116                                                Map<String, Resource> nodeNamespaceMap) {
1117         Either<Resource, ResponseFormat> eitherResource = null;
1118         log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
1119         if (MapUtils.isEmpty(uploadResInstancesMap) && resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
1120             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
1121             throw new ComponentException(responseFormat);
1122         }
1123         Map<String, Resource> existingNodeTypeMap = new HashMap<>();
1124         if (MapUtils.isNotEmpty(nodeNamespaceMap)) {
1125             nodeNamespaceMap.forEach((k, v) -> existingNodeTypeMap.put(v.getToscaResourceName(), v));
1126         }
1127         Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
1128         uploadResInstancesMap.values()
1129             .forEach(i -> createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap, existingNodeTypeMap, resourcesInstancesMap));
1130         if (MapUtils.isNotEmpty(resourcesInstancesMap)) {
1131             try {
1132                 toscaOperationFacade.associateComponentInstancesToComponent(resource, resourcesInstancesMap, false, false);
1133             } catch (StorageException exp) {
1134                 if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) {
1135                     log.debug("Failed to add component instances to container component {}", resource.getName());
1136                     ResponseFormat responseFormat = componentsUtils
1137                         .getResponseFormat(componentsUtils.convertFromStorageResponse(exp.getStorageOperationStatus()));
1138                     eitherResource = Either.right(responseFormat);
1139                     throw new ByResponseFormatComponentException(eitherResource.right().value());
1140                 }
1141             }
1142         }
1143         log.debug("*************Going to get resource {}", resource.getUniqueId());
1144         Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
1145             .getToscaElement(resource.getUniqueId(), serviceImportParseLogic.getComponentWithInstancesFilter());
1146         log.debug("*************finished to get resource {}", resource.getUniqueId());
1147         if (eitherGetResource.isRight()) {
1148             ResponseFormat responseFormat = componentsUtils
1149                 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
1150             throw new ComponentException(responseFormat);
1151         }
1152         if (CollectionUtils.isEmpty(eitherGetResource.left().value().getComponentInstances()) &&
1153             resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
1154             log.debug("Error when create resource instance from csar. ComponentInstances list empty");
1155             BeEcompErrorManager.getInstance().logBeDaoSystemError("Error when create resource instance from csar. ComponentInstances list empty");
1156             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
1157         }
1158         return eitherGetResource.left().value();
1159     }
1160
1161     protected void handleNodeTypes(String yamlName, Resource resource, String topologyTemplateYaml, boolean needLock,
1162                                    Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1163                                    List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1164                                    String nodeName) {
1165         try {
1166             for (Map.Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
1167                 if (nodeTypeEntry.getValue().isNested()) {
1168                     handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
1169                         nodeTypeEntry.getKey());
1170                     log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
1171                 }
1172             }
1173             Map<String, Object> mappedToscaTemplate = null;
1174             if (org.apache.commons.lang.StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo) && nodeTypesInfo
1175                 .containsKey(nodeName)) {
1176                 mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
1177             }
1178             if (MapUtils.isEmpty(mappedToscaTemplate)) {
1179                 mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
1180             }
1181             createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle,
1182                 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
1183         } catch (ComponentException e) {
1184             ResponseFormat responseFormat =
1185                 e.getResponseFormat() != null ? e.getResponseFormat() : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
1186             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
1187             throw e;
1188         } catch (StorageException e) {
1189             ResponseFormat responseFormat = componentsUtils
1190                 .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
1191             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
1192             throw e;
1193         } catch (Exception e) {
1194             log.debug("Exception occured when handleNodeTypes, error is:{}", e.getMessage(), e);
1195             throw new ComponentException(ActionStatus.GENERAL_ERROR);
1196         }
1197     }
1198
1199     protected Resource handleNestedVfc(Service service,
1200                                        Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1201                                        List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1202                                        String nodeName) {
1203         try {
1204             String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
1205             Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
1206             createResourcesFromYamlNodeTypesList(yamlName, service, nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
1207                 csarInfo);
1208             log.debug("************* Finished to create node types from yaml {}", yamlName);
1209             if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
1210                 log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
1211                 return handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName);
1212             }
1213             return new Resource();
1214         } catch (Exception e) {
1215             log.debug("Exception occured when handleNestedVFc, error is:{}", e.getMessage(), e);
1216             throw new ComponentException(ActionStatus.GENERAL_ERROR);
1217         }
1218     }
1219
1220     protected Resource handleNestedVfc(Resource resource,
1221                                        Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1222                                        List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1223                                        String nodeName) {
1224         String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
1225         Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
1226         log.debug("************* Going to create node types from yaml {}", yamlName);
1227         createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
1228             csarInfo);
1229         if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
1230             log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
1231             resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName);
1232         }
1233         return resource;
1234     }
1235
1236     protected Resource handleComplexVfc(Resource resource,
1237                                         Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1238                                         List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1239                                         String nodeName, String yamlName) {
1240         Resource oldComplexVfc = null;
1241         Resource newComplexVfc = serviceImportParseLogic.buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo);
1242         Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade
1243             .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
1244         if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
1245             oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
1246                 serviceImportParseLogic.buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName).getRight());
1247         }
1248         if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
1249             throw new ComponentException(ActionStatus.GENERAL_ERROR);
1250         } else if (oldComplexVfcRes.isLeft()) {
1251             log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
1252             Either<Boolean, ResponseFormat> eitherValidation = serviceImportParseLogic
1253                 .validateNestedDerivedFromDuringUpdate(oldComplexVfcRes.left().value(), newComplexVfc,
1254                     ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
1255             if (eitherValidation.isLeft()) {
1256                 oldComplexVfc = oldComplexVfcRes.left().value();
1257             }
1258         }
1259         newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName, oldComplexVfc,
1260             newComplexVfc);
1261         csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
1262         LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1263             LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1264         log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
1265         final Resource result = serviceImportParseLogic
1266             .propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, true);
1267         csarInfo.getCreatedNodes().put(nodeName, result);
1268         csarInfo.removeNodeFromQueue();
1269         return result;
1270     }
1271
1272     private Map<String, Resource> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, Map<String, Object> mappedToscaTemplate,
1273                                                                        boolean needLock,
1274                                                                        Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1275                                                                        List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1276                                                                        Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
1277         Either<String, ImportUtils.ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate,
1278             TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
1279         if (toscaVersion.isRight()) {
1280             throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE);
1281         }
1282         Map<String, Object> mapToConvert = new HashMap<>();
1283         mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left().value());
1284         Map<String, Object> nodeTypes = serviceImportParseLogic.getNodeTypesFromTemplate(mappedToscaTemplate);
1285         createNodeTypes(yamlName, resource, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, mapToConvert,
1286             nodeTypes);
1287         return csarInfo.getCreatedNodes();
1288     }
1289
1290     protected void createNodeTypes(String yamlName, Resource resource, boolean needLock,
1291                                    Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1292                                    List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1293                                    Map<String, Object> mapToConvert, Map<String, Object> nodeTypes) {
1294         Iterator<Map.Entry<String, Object>> nodesNameValueIter = nodeTypes.entrySet().iterator();
1295         Resource vfcCreated = null;
1296         while (nodesNameValueIter.hasNext()) {
1297             Map.Entry<String, Object> nodeType = nodesNameValueIter.next();
1298             Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle =
1299                 nodeTypesArtifactsToHandle == null || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey());
1300             if (nodeTypesInfo.containsKey(nodeType.getKey())) {
1301                 log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
1302                 vfcCreated = handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
1303                     nodeType.getKey());
1304                 log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
1305             } else if (csarInfo.getCreatedNodesToscaResourceNames() != null && !csarInfo.getCreatedNodesToscaResourceNames()
1306                 .containsKey(nodeType.getKey())) {
1307                 log.trace("************* Going to create node {}", nodeType.getKey());
1308                 ImmutablePair<Resource, ActionStatus> resourceCreated = createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(),
1309                     mapToConvert, resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, csarInfo, true);
1310                 log.debug("************* Finished to create node {}", nodeType.getKey());
1311                 vfcCreated = resourceCreated.getLeft();
1312                 csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(), vfcCreated.getToscaResourceName());
1313             }
1314             if (vfcCreated != null) {
1315                 csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated);
1316             }
1317             mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName());
1318         }
1319     }
1320
1321     protected ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(String yamlName, Map.Entry<String, Object> nodeNameValue,
1322                                                                                    User user, Map<String, Object> mapToConvert, Resource resourceVf,
1323                                                                                    boolean needLock,
1324                                                                                    Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1325                                                                                    List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1326                                                                                    boolean forceCertificationAllowed, CsarInfo csarInfo,
1327                                                                                    boolean isNested) {
1328         UploadResourceInfo resourceMetaData = serviceImportParseLogic.fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
1329         String singleVfcYaml = serviceImportParseLogic.buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.getResourceType(), csarInfo);
1330         user = serviceBusinessLogic.validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
1331         return serviceImportParseLogic.createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock, nodeTypeArtifactsToHandle,
1332             nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeNameValue.getKey(), isNested);
1333     }
1334
1335     protected Service createRIAndRelationsFromYaml(String yamlName, Service service,
1336                                                    Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap,
1337                                                    String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1338                                                    Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1339                                                    Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1340                                                    String nodeName) {
1341         log.debug("************* Going to create all nodes {}", yamlName);
1342         handleServiceNodeTypes(yamlName, service, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts,
1343             nodeTypesInfo, csarInfo, nodeName);
1344         if (MapUtils.isNotEmpty(uploadComponentInstanceInfoMap)) {
1345             log.debug("************* Going to create all resource instances {}", yamlName);
1346             service = createServiceInstances(yamlName, service, uploadComponentInstanceInfoMap, csarInfo.getCreatedNodes());
1347             log.debug("************* Going to create all relations {}", yamlName);
1348             service = createServiceInstancesRelations(csarInfo.getModifier(), yamlName, service, uploadComponentInstanceInfoMap);
1349             log.debug("************* Going to create positions {}", yamlName);
1350             compositionBusinessLogic.setPositionsForComponentInstances(service, csarInfo.getModifier().getUserId());
1351             log.debug("************* Finished to set positions {}", yamlName);
1352         }
1353         return service;
1354     }
1355
1356     protected Service createServiceInstancesRelations(User user, String yamlName, Service service,
1357                                                       Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
1358         log.debug("#createResourceInstancesRelations - Going to create relations ");
1359         List<ComponentInstance> componentInstancesList = service.getComponentInstances();
1360         if (((MapUtils.isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)))) { // PNF can have no resource instances
1361             log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ",
1362                 service.getUniqueId(), yamlName);
1363             BeEcompErrorManager.getInstance()
1364                 .logInternalDataError("createResourceInstancesRelations", "No instances found in a component or nn yaml template. ",
1365                     BeEcompErrorManager.ErrorSeverity.ERROR);
1366             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName));
1367         }
1368         Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
1369         Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
1370         Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
1371         Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
1372         Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
1373         Map<String, List<AttributeDefinition>> instAttributes = new HashMap<>();
1374         Map<String, Resource> originCompMap = new HashMap<>();
1375         List<RequirementCapabilityRelDef> relations = new ArrayList<>();
1376         Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
1377         Map<String, UploadNodeFilterInfo> instNodeFilter = new HashMap<>();
1378         log.debug("enter ServiceImportBusinessLogic  createServiceInstancesRelations#createResourceInstancesRelations - Before get all datatypes. ");
1379         final ApplicationDataTypeCache applicationDataTypeCache = serviceBusinessLogic.applicationDataTypeCache;
1380         if (applicationDataTypeCache != null) {
1381             Service finalResource = service;
1382             uploadResInstancesMap.values().forEach(
1383                 i -> processComponentInstance(yamlName, finalResource, componentInstancesList,
1384                     componentsUtils.getAllDataTypes(applicationDataTypeCache, finalResource.getModel()), instProperties,
1385                     instCapabilities, instRequirements, instDeploymentArtifacts, instArtifacts, instAttributes, originCompMap, instInputs,
1386                     instNodeFilter, i));
1387         }
1388         serviceImportParseLogic.associateComponentInstancePropertiesToComponent(yamlName, service, instProperties);
1389         serviceImportParseLogic.associateComponentInstanceInputsToComponent(yamlName, service, instInputs);
1390         serviceImportParseLogic.associateCINodeFilterToComponent(yamlName, service, instNodeFilter);
1391         serviceImportParseLogic.associateDeploymentArtifactsToInstances(user, yamlName, service, instDeploymentArtifacts);
1392         serviceImportParseLogic.associateArtifactsToInstances(yamlName, service, instArtifacts);
1393         serviceImportParseLogic.associateOrAddCalculatedCapReq(yamlName, service, instCapabilities, instRequirements);
1394         log.debug("enter createServiceInstancesRelations test,instRequirements:{},instCapabilities:{}", instRequirements, instCapabilities);
1395         serviceImportParseLogic.associateInstAttributeToComponentToInstances(yamlName, service, instAttributes);
1396         ToscaElement serviceTemplate = ModelConverter.convertToToscaElement(service);
1397         Map<String, ListCapabilityDataDefinition> capabilities = serviceTemplate.getCapabilities();
1398         Map<String, ListRequirementDataDefinition> requirements = serviceTemplate.getRequirements();
1399         serviceImportParseLogic.associateCapabilitiesToService(yamlName, service, capabilities);
1400         serviceImportParseLogic.associateRequirementsToService(yamlName, service, requirements);
1401         service = getResourceAfterCreateRelations(service);
1402         addRelationsToRI(yamlName, service, uploadResInstancesMap, componentInstancesList, relations);
1403         serviceImportParseLogic.associateResourceInstances(yamlName, service, relations);
1404         log.debug("************* in create relations, getResource start");
1405         Either<Service, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
1406         log.debug("************* in create relations, getResource end");
1407         if (eitherGetResource.isRight()) {
1408             throw new ComponentException(componentsUtils
1409                 .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), service,
1410                     service.getComponentType()));
1411         }
1412         return eitherGetResource.left().value();
1413     }
1414
1415     protected void processComponentInstance(String yamlName, Component component, List<ComponentInstance> componentInstancesList,
1416                                             Map<String, DataTypeDefinition> allDataTypes,
1417                                             Map<String, List<ComponentInstanceProperty>> instProperties,
1418                                             Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
1419                                             Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements,
1420                                             Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
1421                                             Map<String, Map<String, ArtifactDefinition>> instArtifacts,
1422                                             Map<String, List<AttributeDefinition>> instAttributes, Map<String, Resource> originCompMap,
1423                                             Map<String, List<ComponentInstanceInput>> instInputs,
1424                                             Map<String, UploadNodeFilterInfo> instNodeFilter,
1425                                             UploadComponentInstanceInfo uploadComponentInstanceInfo) {
1426         log.debug("enter ServiceImportBusinessLogic processComponentInstance");
1427         Optional<ComponentInstance> currentCompInstanceOpt = componentInstancesList.stream()
1428             .filter(i -> i.getName().equals(uploadComponentInstanceInfo.getName())).findFirst();
1429         if (!currentCompInstanceOpt.isPresent()) {
1430             log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), component.getUniqueId());
1431             BeEcompErrorManager.getInstance()
1432                 .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, component.getUniqueId(),
1433                     BeEcompErrorManager.ErrorSeverity.ERROR);
1434             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
1435             throw new ComponentException(responseFormat);
1436         }
1437         ComponentInstance currentCompInstance = currentCompInstanceOpt.get();
1438         String resourceInstanceId = currentCompInstance.getUniqueId();
1439         Resource originResource = getOriginResource(yamlName, originCompMap, currentCompInstance);
1440         if (MapUtils.isNotEmpty(originResource.getRequirements())) {
1441             instRequirements.put(currentCompInstance, originResource.getRequirements());
1442         }
1443         if (MapUtils.isNotEmpty(originResource.getCapabilities())) {
1444             processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo, currentCompInstance, originResource);
1445         }
1446         if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty()) {
1447             instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
1448         }
1449         if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty()) {
1450             instArtifacts.put(resourceInstanceId, originResource.getArtifacts());
1451         }
1452         if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty()) {
1453             instAttributes.put(resourceInstanceId, originResource.getAttributes());
1454             addAttributeValueToResourceInstance(instAttributes, uploadComponentInstanceInfo.getAttributes());
1455         }
1456         if (uploadComponentInstanceInfo.getUploadNodeFilterInfo() != null) {
1457             instNodeFilter.put(resourceInstanceId, uploadComponentInstanceInfo.getUploadNodeFilterInfo());
1458         }
1459         if (originResource.getResourceType() != ResourceTypeEnum.VF) {
1460             ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, component, originResource,
1461                 currentCompInstance, instProperties, allDataTypes);
1462             if (addPropertiesValueToRiRes.getStatus() != 200) {
1463                 throw new ComponentException(addPropertiesValueToRiRes);
1464             }
1465         } else {
1466             addInputsValuesToRi(uploadComponentInstanceInfo, component, originResource, currentCompInstance, instInputs, allDataTypes);
1467         }
1468     }
1469
1470     protected void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Component component, Resource originResource,
1471                                        ComponentInstance currentCompInstance, Map<String, List<ComponentInstanceInput>> instInputs,
1472                                        Map<String, DataTypeDefinition> allDataTypes) {
1473         Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
1474         try {
1475             if (MapUtils.isNotEmpty(propMap)) {
1476                 Map<String, InputDefinition> currPropertiesMap = new HashMap<>();
1477                 List<ComponentInstanceInput> instPropList = new ArrayList<>();
1478                 if (CollectionUtils.isEmpty(originResource.getInputs())) {
1479                     log.debug("failed to find properties ");
1480                     throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND));
1481                 }
1482                 originResource.getInputs().forEach(p -> serviceImportParseLogic.addInput(currPropertiesMap, p));
1483                 for (List<UploadPropInfo> propertyList : propMap.values()) {
1484                     processProperty(component, currentCompInstance, allDataTypes, currPropertiesMap, instPropList, propertyList);
1485                 }
1486                 currPropertiesMap.values().forEach(p -> instPropList.add(new ComponentInstanceInput(p)));
1487                 instInputs.put(currentCompInstance.getUniqueId(), instPropList);
1488             }
1489         } catch (Exception e) {
1490             log.debug("failed to add Inputs Values To Ri");
1491             throw new ComponentException(ActionStatus.GENERAL_ERROR);
1492         }
1493     }
1494
1495     protected void processProperty(Component component, ComponentInstance currentCompInstance, Map<String, DataTypeDefinition> allDataTypes,
1496                                    Map<String, InputDefinition> currPropertiesMap, List<ComponentInstanceInput> instPropList,
1497                                    List<UploadPropInfo> propertyList) {
1498         UploadPropInfo propertyInfo = propertyList.get(0);
1499         String propName = propertyInfo.getName();
1500         if (!currPropertiesMap.containsKey(propName)) {
1501             log.debug("failed to find property {} ", propName);
1502             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName));
1503         }
1504         processProperty(allDataTypes, currPropertiesMap, instPropList, propertyInfo, propName, component.getInputs());
1505     }
1506
1507     protected void processGetInput(List<GetInputValueDataDefinition> getInputValues, List<InputDefinition> inputs,
1508                                    GetInputValueDataDefinition getInputIndex) {
1509         Optional<InputDefinition> optional;
1510         if (getInputIndex != null) {
1511             optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())).findAny();
1512             if (!optional.isPresent()) {
1513                 log.debug("Failed to find input {} ", getInputIndex.getInputName());
1514                 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1515             }
1516             InputDefinition inputIndex = optional.get();
1517             getInputIndex.setInputId(inputIndex.getUniqueId());
1518             getInputValues.add(getInputIndex);
1519         }
1520     }
1521
1522     private void addAttributeValueToResourceInstance(Map<String, List<AttributeDefinition>> instAttributes,
1523                                                      Map<String, UploadAttributeInfo> attributeMap) {
1524         if (attributeMap == null) {
1525             return;
1526         }
1527         attributeMap.forEach((attributeName, attributeValue) -> instAttributes.values()
1528             .forEach(value -> value.stream().filter(attr -> attr.getName().equals(attributeName)).forEach(attr -> {
1529                 if (attributeValue.getValue() instanceof Collection<?> || attributeValue.getValue() instanceof Map<?, ?>) {
1530                     Gson gson = new Gson();
1531                     String json = gson.toJson(attributeValue.getValue());
1532                     attr.setValue(json);
1533                 } else {
1534                     attr.setValue(String.valueOf(attributeValue.getValue()));
1535                 }
1536             })));
1537     }
1538
1539     protected ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Component component,
1540                                                    Resource originResource, ComponentInstance currentCompInstance,
1541                                                    Map<String, List<ComponentInstanceProperty>> instProperties,
1542                                                    Map<String, DataTypeDefinition> allDataTypes) {
1543         Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
1544         Map<String, PropertyDefinition> currPropertiesMap = new HashMap<>();
1545         List<PropertyDefinition> listFromMap = originResource.getProperties();
1546         if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) {
1547             log.debug("failed to find properties ");
1548             return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
1549         }
1550         if (listFromMap == null || listFromMap.isEmpty()) {
1551             return componentsUtils.getResponseFormat(ActionStatus.OK);
1552         }
1553         for (PropertyDefinition prop : listFromMap) {
1554             String propName = prop.getName();
1555             if (!currPropertiesMap.containsKey(propName)) {
1556                 currPropertiesMap.put(propName, prop);
1557             }
1558         }
1559         List<ComponentInstanceProperty> instPropList = new ArrayList<>();
1560         if (propMap != null && propMap.size() > 0) {
1561             for (List<UploadPropInfo> propertyList : propMap.values()) {
1562                 UploadPropInfo propertyInfo = propertyList.get(0);
1563                 String propName = propertyInfo.getName();
1564                 if (!currPropertiesMap.containsKey(propName)) {
1565                     log.debug("failed to find property {} ", propName);
1566                     return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
1567                 }
1568                 PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
1569                 ComponentInstanceProperty property = null;
1570                 String value = null;
1571                 List<GetInputValueDataDefinition> getInputs = null;
1572                 boolean isValidate = true;
1573                 if (propertyInfo.getValue() != null) {
1574                     getInputs = propertyInfo.getGet_input();
1575                     isValidate = getInputs == null || getInputs.isEmpty();
1576                     if (isValidate) {
1577                         value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
1578                     } else {
1579                         value = getPropertyJsonStringValue(propertyInfo.getValue(), TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
1580                     }
1581                 }
1582                 property = new ComponentInstanceProperty(curPropertyDef, value, null);
1583                 String validatePropValue = serviceBusinessLogic.validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
1584                 property.setValue(validatePropValue);
1585                 if (getInputs != null && !getInputs.isEmpty()) {
1586                     List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
1587                     for (GetInputValueDataDefinition getInput : getInputs) {
1588                         List<InputDefinition> inputs = component.getInputs();
1589                         if (inputs == null || inputs.isEmpty()) {
1590                             log.debug("Failed to add property {} to instance. Inputs list is empty ", property);
1591                             serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND,
1592                                 property.getGetInputValues().stream().map(GetInputValueDataDefinition::getInputName).collect(toList()).toString());
1593                         }
1594                         InputDefinition input = serviceImportParseLogic.findInputByName(inputs, getInput);
1595                         getInput.setInputId(input.getUniqueId());
1596                         getInputValues.add(getInput);
1597                         GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
1598                         if (getInputIndex != null) {
1599                             input = serviceImportParseLogic.findInputByName(inputs, getInputIndex);
1600                             getInputIndex.setInputId(input.getUniqueId());
1601                             getInputValues.add(getInputIndex);
1602                         }
1603                     }
1604                     property.setGetInputValues(getInputValues);
1605                 }
1606                 instPropList.add(property);
1607                 currPropertiesMap.remove(property.getName());
1608             }
1609         }
1610         if (!currPropertiesMap.isEmpty()) {
1611             for (PropertyDefinition value : currPropertiesMap.values()) {
1612                 instPropList.add(new ComponentInstanceProperty(value));
1613             }
1614         }
1615         instProperties.put(currentCompInstance.getUniqueId(), instPropList);
1616         return componentsUtils.getResponseFormat(ActionStatus.OK);
1617     }
1618
1619     protected void processComponentInstanceCapabilities(Map<String, DataTypeDefinition> allDataTypes,
1620                                                         Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
1621                                                         UploadComponentInstanceInfo uploadComponentInstanceInfo,
1622                                                         ComponentInstance currentCompInstance, Resource originResource) {
1623         log.debug("enter processComponentInstanceCapabilities");
1624         Map<String, List<CapabilityDefinition>> originCapabilities;
1625         if (MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) {
1626             originCapabilities = new HashMap<>();
1627             Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>();
1628             originResource.getCapabilities().forEach((k, v) -> serviceImportParseLogic.addCapabilities(originCapabilities, k, v));
1629             uploadComponentInstanceInfo.getCapabilities().values()
1630                 .forEach(l -> serviceImportParseLogic.addCapabilitiesProperties(newPropertiesMap, l));
1631             updateCapabilityPropertiesValues(allDataTypes, originCapabilities, newPropertiesMap);
1632         } else {
1633             originCapabilities = originResource.getCapabilities();
1634         }
1635         instCapabilties.put(currentCompInstance, originCapabilities);
1636     }
1637
1638     protected void updateCapabilityPropertiesValues(Map<String, DataTypeDefinition> allDataTypes,
1639                                                     Map<String, List<CapabilityDefinition>> originCapabilities,
1640                                                     Map<String, Map<String, UploadPropInfo>> newPropertiesMap) {
1641         originCapabilities.values().stream().flatMap(Collection::stream).filter(c -> newPropertiesMap.containsKey(c.getName()))
1642             .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()), allDataTypes));
1643     }
1644
1645     protected void updatePropertyValues(List<ComponentInstanceProperty> properties, Map<String, UploadPropInfo> newProperties,
1646                                         Map<String, DataTypeDefinition> allDataTypes) {
1647         properties.forEach(p -> updatePropertyValue(p, newProperties.get(p.getName()), allDataTypes));
1648     }
1649
1650     protected String updatePropertyValue(ComponentInstanceProperty property, UploadPropInfo propertyInfo,
1651                                          Map<String, DataTypeDefinition> allDataTypes) {
1652         String value = null;
1653         List<GetInputValueDataDefinition> getInputs = null;
1654         boolean isValidate = true;
1655         if (null != propertyInfo && propertyInfo.getValue() != null) {
1656             getInputs = propertyInfo.getGet_input();
1657             isValidate = getInputs == null || getInputs.isEmpty();
1658             if (isValidate) {
1659                 value = getPropertyJsonStringValue(propertyInfo.getValue(), property.getType());
1660             } else {
1661                 value = getPropertyJsonStringValue(propertyInfo.getValue(), TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
1662             }
1663         }
1664         property.setValue(value);
1665         return serviceBusinessLogic.validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
1666     }
1667
1668     protected Resource getOriginResource(String yamlName, Map<String, Resource> originCompMap, ComponentInstance currentCompInstance) {
1669         Resource originResource;
1670         log.debug("after enter ServiceImportBusinessLogic processComponentInstance, enter getOriginResource");
1671         if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
1672             Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade
1673                 .getToscaFullElement(currentCompInstance.getComponentUid());
1674             if (getOriginResourceRes.isRight()) {
1675                 ResponseFormat responseFormat = componentsUtils
1676                     .getResponseFormat(componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName);
1677                 throw new ComponentException(responseFormat);
1678             }
1679             originResource = getOriginResourceRes.left().value();
1680             originCompMap.put(originResource.getUniqueId(), originResource);
1681         } else {
1682             originResource = originCompMap.get(currentCompInstance.getComponentUid());
1683         }
1684         return originResource;
1685     }
1686
1687     protected Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource,
1688                                                                                                       Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
1689         Either<Resource, StorageOperationStatus> updateRes = null;
1690         Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>();
1691         Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>();
1692         StorageOperationStatus status = toscaOperationFacade.deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId());
1693         if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
1694             log.debug("Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}",
1695                 resource.getUniqueId(), status);
1696             updateRes = Either.right(status);
1697         }
1698         if (updateRes == null) {
1699             fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap, updatedInstCapabilities,
1700                 updatedInstRequirements);
1701             status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements, resource);
1702             if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
1703                 updateRes = Either.right(status);
1704             }
1705         }
1706         if (updateRes == null) {
1707             updateRes = Either.left(resource);
1708         }
1709         return updateRes;
1710     }
1711
1712     protected void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances,
1713                                                            Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
1714                                                            Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities,
1715                                                            Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) {
1716         componentInstances.stream().forEach(i -> {
1717             fillUpdatedInstCapabilities(updatedInstCapabilities, i, uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate());
1718             fillUpdatedInstRequirements(updatedInstRequirements, i, uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate());
1719         });
1720     }
1721
1722     protected void fillUpdatedInstCapabilities(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties,
1723                                                ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
1724         Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
1725         Set<String> updatedCapNames = new HashSet<>();
1726         if (MapUtils.isNotEmpty(capabilitiesNamesToUpdate)) {
1727             for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities().entrySet()) {
1728                 updatedCapabilities.put(requirements.getKey(), requirements.getValue().stream().filter(
1729                         c -> capabilitiesNamesToUpdate.containsKey(c.getName()) && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
1730                     .map(c -> {
1731                         c.setParentName(c.getName());
1732                         c.setName(capabilitiesNamesToUpdate.get(c.getName()));
1733                         updatedCapNames.add(c.getName());
1734                         return c;
1735                     }).collect(toList()));
1736             }
1737         }
1738         if (MapUtils.isNotEmpty(updatedCapabilities)) {
1739             updatedInstCapabilties.put(instance, updatedCapabilities);
1740         }
1741     }
1742
1743     protected void fillUpdatedInstRequirements(Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements,
1744                                                ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
1745         Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
1746         Set<String> updatedReqNames = new HashSet<>();
1747         if (MapUtils.isNotEmpty(requirementsNamesToUpdate)) {
1748             for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements().entrySet()) {
1749                 updatedRequirements.put(requirements.getKey(), requirements.getValue().stream().filter(
1750                         r -> requirementsNamesToUpdate.containsKey(r.getName()) && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
1751                     .map(r -> {
1752                         r.setParentName(r.getName());
1753                         r.setName(requirementsNamesToUpdate.get(r.getName()));
1754                         updatedReqNames.add(r.getName());
1755                         return r;
1756                     }).collect(toList()));
1757             }
1758         }
1759         if (MapUtils.isNotEmpty(updatedRequirements)) {
1760             updatedInstRequirements.put(instance, updatedRequirements);
1761         }
1762     }
1763
1764     protected void addRelationsToRI(String yamlName, Service service, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
1765                                     List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) {
1766         for (Map.Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
1767             UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
1768             ComponentInstance currentCompInstance = null;
1769             for (ComponentInstance compInstance : componentInstancesList) {
1770                 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
1771                     currentCompInstance = compInstance;
1772                     break;
1773                 }
1774             }
1775             if (currentCompInstance == null) {
1776                 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), service.getUniqueId());
1777                 BeEcompErrorManager.getInstance()
1778                     .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, service.getUniqueId(),
1779                         BeEcompErrorManager.ErrorSeverity.ERROR);
1780                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
1781                 throw new ComponentException(responseFormat);
1782             }
1783             ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, service, entry.getValue(), relations);
1784             if (addRelationToRiRes.getStatus() != 200) {
1785                 throw new ComponentException(addRelationToRiRes);
1786             }
1787         }
1788     }
1789
1790     protected ResponseFormat addRelationToRI(String yamlName, Service service, UploadComponentInstanceInfo nodesInfoValue,
1791                                              List<RequirementCapabilityRelDef> relations) {
1792         List<ComponentInstance> componentInstancesList = service.getComponentInstances();
1793         ComponentInstance currentCompInstance = null;
1794         for (ComponentInstance compInstance : componentInstancesList) {
1795             if (compInstance.getName().equals(nodesInfoValue.getName())) {
1796                 currentCompInstance = compInstance;
1797                 break;
1798             }
1799         }
1800         if (currentCompInstance == null) {
1801             log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), service.getUniqueId());
1802             BeEcompErrorManager.getInstance()
1803                 .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE, service.getUniqueId(),
1804                     BeEcompErrorManager.ErrorSeverity.ERROR);
1805             return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
1806         }
1807         String resourceInstanceId = currentCompInstance.getUniqueId();
1808         Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
1809         if (regMap != null) {
1810             Iterator<Map.Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
1811             while (nodesRegValue.hasNext()) {
1812                 Map.Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
1813                 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
1814                 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
1815                     log.debug("Going to create  relation {}", uploadRegInfo.getName());
1816                     String regName = uploadRegInfo.getName();
1817                     RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
1818                     regCapRelDef.setFromNode(resourceInstanceId);
1819                     log.debug("try to find available requirement {} ", regName);
1820                     Either<RequirementDefinition, ResponseFormat> eitherReqStatus = serviceImportParseLogic
1821                         .findAvailableRequirement(regName, yamlName, nodesInfoValue, currentCompInstance, uploadRegInfo.getCapabilityName());
1822                     if (eitherReqStatus.isRight()) {
1823                         log.debug("failed to find available requirement {} status is {}", regName, eitherReqStatus.right().value());
1824                         return eitherReqStatus.right().value();
1825                     }
1826                     RequirementDefinition validReq = eitherReqStatus.left().value();
1827                     List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef.getRelationships();
1828                     if (reqAndRelationshipPairList == null) {
1829                         reqAndRelationshipPairList = new ArrayList<>();
1830                     }
1831                     RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
1832                     reqAndRelationshipPair.setRequirement(regName);
1833                     reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
1834                     reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
1835                     RelationshipImpl relationship = new RelationshipImpl();
1836                     relationship.setType(validReq.getCapability());
1837                     reqAndRelationshipPair.setRelationships(relationship);
1838                     ComponentInstance currentCapCompInstance = null;
1839                     for (ComponentInstance compInstance : componentInstancesList) {
1840                         if (compInstance.getName().equals(uploadRegInfo.getNode())) {
1841                             currentCapCompInstance = compInstance;
1842                             break;
1843                         }
1844                     }
1845                     if (currentCapCompInstance == null) {
1846                         log.debug("The component instance  with name {} not found on resource {} ", uploadRegInfo.getNode(), service.getUniqueId());
1847                         BeEcompErrorManager.getInstance()
1848                             .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE, service.getUniqueId(),
1849                                 BeEcompErrorManager.ErrorSeverity.ERROR);
1850                         return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
1851                     }
1852                     regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
1853                     log.debug("try to find aviable Capability  req name is {} ", validReq.getName());
1854                     CapabilityDefinition aviableCapForRel = serviceImportParseLogic
1855                         .findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo);
1856                     if (aviableCapForRel == null) {
1857                         BeEcompErrorManager.getInstance().logInternalDataError(
1858                             "aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance
1859                                 .getUniqueId(), service.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
1860                         return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
1861                     }
1862                     reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
1863                     reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
1864                     reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
1865                     CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
1866                     capReqRel.setRelation(reqAndRelationshipPair);
1867                     if (StringUtils.isNotEmpty(uploadRegInfo.getRelationshipTemplate())) {
1868                         capReqRel.setOperations(getOperations(nodesInfoValue.getOperations(), uploadRegInfo.getRelationshipTemplate()));
1869                     }
1870                     reqAndRelationshipPairList.add(capReqRel);
1871                     regCapRelDef.setRelationships(reqAndRelationshipPairList);
1872                     relations.add(regCapRelDef);
1873                 }
1874             }
1875         }
1876         return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
1877     }
1878
1879     private List<OperationUi> getOperations(final Map<String, List<OperationUi>> operations, final String relationshipTemplate) {
1880         final List<OperationUi> operationUiList = new ArrayList<>();
1881         operations.forEach((operationKey, operationValues) -> {
1882             if (operationKey.equals(relationshipTemplate)) {
1883                 operationUiList.addAll(operationValues);
1884             }
1885         });
1886         return operationUiList;
1887     }
1888
1889     protected Service getResourceAfterCreateRelations(Service service) {
1890         ComponentParametersView parametersView = serviceImportParseLogic.getComponentFilterAfterCreateRelations();
1891         Either<Service, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(service.getUniqueId(), parametersView);
1892         if (eitherGetResource.isRight()) {
1893             serviceImportParseLogic.throwComponentExceptionByResource(eitherGetResource.right().value(), service);
1894         }
1895         return eitherGetResource.left().value();
1896     }
1897
1898     protected Service createServiceInstances(String yamlName, Service service, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
1899                                              Map<String, Resource> nodeNamespaceMap) {
1900         Either<Resource, ResponseFormat> eitherResource = null;
1901         log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
1902         if (MapUtils.isEmpty(uploadResInstancesMap)) { // PNF can have no resource instances
1903             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
1904             throw new ComponentException(responseFormat);
1905         }
1906         Map<String, Resource> existingNodeTypeMap = new HashMap<>();
1907         if (MapUtils.isNotEmpty(nodeNamespaceMap)) {
1908             nodeNamespaceMap.forEach((k, v) -> existingNodeTypeMap.put(v.getToscaResourceName(), v));
1909         }
1910         Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
1911         uploadResInstancesMap.values()
1912             .forEach(i -> createAndAddResourceInstance(i, yamlName, service, nodeNamespaceMap, existingNodeTypeMap, resourcesInstancesMap));
1913         if (MapUtils.isNotEmpty(resourcesInstancesMap)) {
1914             try {
1915                 toscaOperationFacade.associateComponentInstancesToComponent(service, resourcesInstancesMap, false, false);
1916             } catch (StorageException exp) {
1917                 if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) {
1918                     log.debug("Failed to add component instances to container component {}", service.getName());
1919                     ResponseFormat responseFormat = componentsUtils
1920                         .getResponseFormat(componentsUtils.convertFromStorageResponse(exp.getStorageOperationStatus()));
1921                     eitherResource = Either.right(responseFormat);
1922                     throw new ComponentException(eitherResource.right().value());
1923                 }
1924             }
1925         }
1926         Either<Service, StorageOperationStatus> eitherGetResource = toscaOperationFacade
1927             .getToscaElement(service.getUniqueId(), serviceImportParseLogic.getComponentWithInstancesFilter());
1928         log.debug("*************finished to get resource {}", service.getUniqueId());
1929         if (eitherGetResource.isRight()) {
1930             ResponseFormat responseFormat = componentsUtils
1931                 .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), service,
1932                     ComponentTypeEnum.SERVICE);
1933             throw new ComponentException(responseFormat);
1934         }
1935         if (CollectionUtils.isEmpty(eitherGetResource.left().value().getComponentInstances())) { // PNF can have no resource instances
1936             log.debug("Error when create resource instance from csar. ComponentInstances list empty");
1937             BeEcompErrorManager.getInstance().logBeDaoSystemError("Error when create resource instance from csar. ComponentInstances list empty");
1938             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
1939         }
1940         return eitherGetResource.left().value();
1941     }
1942
1943     protected void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName, Component component,
1944                                                 Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingnodeTypeMap,
1945                                                 Map<ComponentInstance, Resource> resourcesInstancesMap) {
1946         log.debug("*************Going to create  resource instances {}", uploadComponentInstanceInfo.getName());
1947         try {
1948             if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
1949                 uploadComponentInstanceInfo.setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
1950             }
1951             Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo, existingnodeTypeMap);
1952             ComponentInstance componentInstance = new ComponentInstance();
1953             componentInstance.setComponentUid(refResource.getUniqueId());
1954             Collection<String> directives = uploadComponentInstanceInfo.getDirectives();
1955             if (directives != null && !directives.isEmpty()) {
1956                 componentInstance.setDirectives(new ArrayList<>(directives));
1957             }
1958             UploadNodeFilterInfo uploadNodeFilterInfo = uploadComponentInstanceInfo.getUploadNodeFilterInfo();
1959             if (uploadNodeFilterInfo != null) {
1960                 componentInstance
1961                     .setNodeFilter(new CINodeFilterUtils().getNodeFilterDataDefinition(uploadNodeFilterInfo, componentInstance.getUniqueId()));
1962             }
1963             ComponentTypeEnum containerComponentType = component.getComponentType();
1964             NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
1965             if (containerNodeType.equals(NodeTypeEnum.Resource) && MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities()) && MapUtils
1966                 .isNotEmpty(refResource.getCapabilities())) {
1967                 serviceImportParseLogic.setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
1968                 Map<String, List<CapabilityDefinition>> validComponentInstanceCapabilities = serviceImportParseLogic
1969                     .getValidComponentInstanceCapabilities(refResource.getUniqueId(), refResource.getCapabilities(),
1970                         uploadComponentInstanceInfo.getCapabilities());
1971                 componentInstance.setCapabilities(validComponentInstanceCapabilities);
1972             }
1973             if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
1974                 ResponseFormat responseFormat = componentsUtils
1975                     .getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(),
1976                         uploadComponentInstanceInfo.getType());
1977                 throw new ComponentException(responseFormat);
1978             }
1979             Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
1980             componentInstance.setName(uploadComponentInstanceInfo.getName());
1981             componentInstance.setIcon(origResource.getIcon());
1982             resourcesInstancesMap.put(componentInstance, origResource);
1983         } catch (Exception e) {
1984             throw new ComponentException(ActionStatus.GENERAL_ERROR, e.getMessage());
1985         }
1986     }
1987
1988     protected Resource validateResourceInstanceBeforeCreate(String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo,
1989                                                             Map<String, Resource> nodeNamespaceMap) {
1990         Resource refResource;
1991         try {
1992             if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
1993                 refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType());
1994             } else {
1995                 Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade
1996                     .getLatestResourceByToscaResourceName(uploadComponentInstanceInfo.getType());
1997                 if (findResourceEither.isRight()) {
1998                     ResponseFormat responseFormat = componentsUtils
1999                         .getResponseFormat(componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
2000                     throw new ComponentException(responseFormat);
2001                 }
2002                 refResource = findResourceEither.left().value();
2003                 nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
2004             }
2005             String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState();
2006             if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
2007                 ResponseFormat responseFormat = componentsUtils
2008                     .getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE, refResource.getComponentType().getValue(), refResource.getName(),
2009                         componentState);
2010                 throw new ComponentException(responseFormat);
2011             }
2012             if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.VF) {
2013                 log.debug("validateResourceInstanceBeforeCreate -  ref resource type is  ", refResource.getResourceType());
2014                 ResponseFormat responseFormat = componentsUtils
2015                     .getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(),
2016                         uploadComponentInstanceInfo.getType());
2017                 throw new ComponentException(responseFormat);
2018             }
2019             return refResource;
2020         } catch (Exception e) {
2021             throw new ComponentException(ActionStatus.GENERAL_ERROR, e.getMessage());
2022         }
2023     }
2024
2025     protected void handleServiceNodeTypes(String yamlName, Service service, String topologyTemplateYaml, boolean needLock,
2026                                           Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
2027                                           List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
2028                                           CsarInfo csarInfo, String nodeName) {
2029         try {
2030             for (Map.Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
2031                 boolean isResourceNotExisted = validateResourceNotExisted(nodeTypeEntry.getKey());
2032                 if (nodeTypeEntry.getValue().isNested() && isResourceNotExisted) {
2033                     handleNestedVF(service, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
2034                         nodeTypeEntry.getKey());
2035                     log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
2036                 }
2037             }
2038             Map<String, Object> mappedToscaTemplate = null;
2039             if (org.apache.commons.lang.StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo) && nodeTypesInfo
2040                 .containsKey(nodeName)) {
2041                 mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
2042             }
2043             if (MapUtils.isEmpty(mappedToscaTemplate)) {
2044                 mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
2045             }
2046             createResourcesFromYamlNodeTypesList(yamlName, service, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle,
2047                 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
2048         } catch (ComponentException | StorageException e) {
2049             throw e;
2050         } catch (Exception e) {
2051             log.debug("Exception occured when handleServiceNodeTypes, error is:{}", e.getMessage(), e);
2052             throw new ComponentException(ActionStatus.GENERAL_ERROR);
2053         }
2054     }
2055
2056     protected boolean validateResourceNotExisted(String type) {
2057         try {
2058             Either<Resource, StorageOperationStatus> latestResource = toscaOperationFacade.getLatestResourceByToscaResourceName(type);
2059             return latestResource.isRight();
2060         } catch (Exception e) {
2061             log.debug("Exception occured when validateResourceNotExisted, error is:{}", e.getMessage(), e);
2062             throw new ComponentException(ActionStatus.GENERAL_ERROR);
2063         }
2064     }
2065
2066     protected Resource handleNestedVF(Service service,
2067                                       Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
2068                                       List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
2069                                       String nodeName) {
2070         try {
2071             String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
2072             Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
2073             createResourcesFromYamlNodeTypesList(yamlName, service, nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
2074                 csarInfo);
2075             log.debug("************* Finished to create node types from yaml {}", yamlName);
2076             if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
2077                 log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
2078                 return handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName);
2079             }
2080             return new Resource();
2081         } catch (Exception e) {
2082             log.debug("Exception occured when handleNestedVF, error is:{}", e.getMessage(), e);
2083             throw new ComponentException(ActionStatus.GENERAL_ERROR);
2084         }
2085     }
2086
2087     protected Resource handleComplexVfc(
2088         Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
2089         List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo, String nodeName, String yamlName) {
2090         try {
2091             Resource oldComplexVfc = null;
2092             Resource newComplexVfc = serviceImportParseLogic.buildValidComplexVfc(csarInfo, nodeName, nodesInfo);
2093             Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade
2094                 .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
2095             if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
2096                 oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
2097                     serviceImportParseLogic.buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName)
2098                         .getRight());
2099             }
2100             if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
2101                 log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ", newComplexVfc.getToscaResourceName(),
2102                     oldComplexVfcRes.right().value());
2103                 throw new ComponentException(ActionStatus.GENERAL_ERROR);
2104             } else if (oldComplexVfcRes.isLeft()) {
2105                 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
2106                 Either<Boolean, ResponseFormat> eitherValidation = serviceImportParseLogic
2107                     .validateNestedDerivedFromDuringUpdate(oldComplexVfcRes.left().value(), newComplexVfc,
2108                         ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
2109                 if (eitherValidation.isLeft()) {
2110                     oldComplexVfc = oldComplexVfcRes.left().value();
2111                 }
2112             }
2113             newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName, oldComplexVfc,
2114                 newComplexVfc);
2115             csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
2116             LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
2117                 LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR);
2118             log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
2119             final Resource result = serviceImportParseLogic
2120                 .propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, true);
2121             csarInfo.getCreatedNodes().put(nodeName, result);
2122             csarInfo.removeNodeFromQueue();
2123             return result;
2124         } catch (Exception e) {
2125             log.debug("Exception occured when handleComplexVfc, error is:{}", e.getMessage(), e);
2126             throw new ComponentException(ActionStatus.GENERAL_ERROR);
2127         }
2128     }
2129
2130     protected Resource handleComplexVfc(
2131         Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
2132         List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo, String nodeName, String yamlName,
2133         Resource oldComplexVfc, Resource newComplexVfc) {
2134         Resource handleComplexVfcRes;
2135         try {
2136             Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName).getMappedToscaTemplate();
2137             String yamlContent = new String(csarInfo.getCsar().get(yamlName));
2138             Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet().stream()
2139                 .collect(toMap(Map.Entry::getKey, e -> e.getValue().getUnmarkedCopy()));
2140             CsarInfo.markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
2141             if (oldComplexVfc == null) {
2142                 handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo, csarInfo, nodesArtifactsToHandle,
2143                     false, true, nodeName);
2144             } else {
2145                 handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc, AuditingActionEnum.UPDATE_RESOURCE_METADATA,
2146                     createdArtifacts, yamlContent, yamlName, csarInfo, newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true);
2147             }
2148             return handleComplexVfcRes;
2149         } catch (Exception e) {
2150             log.debug("Exception occured when handleComplexVfc, error is:{}", e.getMessage(), e);
2151             throw new ComponentException(ActionStatus.GENERAL_ERROR);
2152         }
2153     }
2154
2155     protected Resource updateResourceFromYaml(Resource oldRresource, Resource newRresource, AuditingActionEnum actionEnum,
2156                                               List<ArtifactDefinition> createdArtifacts, String yamlFileName, String yamlFileContent,
2157                                               CsarInfo csarInfo, Map<String, NodeTypeInfo> nodeTypesInfo,
2158                                               Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
2159                                               String nodeName, boolean isNested) {
2160         boolean inTransaction = true;
2161         boolean shouldLock = false;
2162         Resource preparedResource = null;
2163         ParsedToscaYamlInfo uploadComponentInstanceInfoMap = null;
2164         try {
2165             uploadComponentInstanceInfoMap = csarBusinessLogic
2166                 .getParsedToscaYamlInfo(yamlFileContent, yamlFileName, nodeTypesInfo, csarInfo, nodeName, oldRresource);
2167             Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.getInstances();
2168             if (MapUtils.isEmpty(instances) && newRresource.getResourceType() != ResourceTypeEnum.PNF) {
2169                 throw new ComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlFileName);
2170             }
2171             preparedResource = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(), inTransaction, shouldLock,
2172                 isNested).left;
2173             log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent);
2174             serviceImportParseLogic.handleResourceGenericType(preparedResource);
2175             handleNodeTypes(yamlFileName, preparedResource, yamlFileContent, shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo,
2176                 csarInfo, nodeName);
2177             preparedResource = serviceImportParseLogic.createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs());
2178             preparedResource = createResourceInstances(yamlFileName, preparedResource, instances, csarInfo.getCreatedNodes());
2179             preparedResource = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, instances);
2180         } catch (ComponentException e) {
2181             ResponseFormat responseFormat =
2182                 e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
2183             log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat);
2184             componentsUtils
2185                 .auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum);
2186             throw e;
2187         } catch (StorageException e) {
2188             ResponseFormat responseFormat = componentsUtils
2189                 .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
2190             log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat);
2191             componentsUtils
2192                 .auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum);
2193             throw e;
2194         }
2195         Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNames(
2196             uploadComponentInstanceInfoMap.getGroups(), preparedResource.getSystemName());
2197         if (validateUpdateVfGroupNamesRes.isRight()) {
2198             throw new ComponentException(validateUpdateVfGroupNamesRes.right().value());
2199         }
2200         Map<String, GroupDefinition> groups;
2201         if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
2202             groups = validateUpdateVfGroupNamesRes.left().value();
2203         } else {
2204             groups = uploadComponentInstanceInfoMap.getGroups();
2205         }
2206         serviceImportParseLogic.handleGroupsProperties(preparedResource, groups);
2207         preparedResource = serviceImportParseLogic.updateGroupsOnResource(preparedResource, groups);
2208         NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToHandle);
2209         Either<Resource, ResponseFormat> updateArtifactsEither = createOrUpdateArtifacts(ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE,
2210             createdArtifacts, yamlFileName, csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
2211         if (updateArtifactsEither.isRight()) {
2212             log.debug("failed to update artifacts {}", updateArtifactsEither.right().value());
2213             throw new ComponentException(updateArtifactsEither.right().value());
2214         }
2215         preparedResource = serviceImportParseLogic.getResourceWithGroups(updateArtifactsEither.left().value().getUniqueId());
2216         ActionStatus mergingPropsAndInputsStatus = resourceDataMergeBusinessLogic.mergeResourceEntities(oldRresource, preparedResource);
2217         if (mergingPropsAndInputsStatus != ActionStatus.OK) {
2218             ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus, preparedResource);
2219             throw new ComponentException(responseFormat);
2220         }
2221         compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier().getUserId());
2222         return preparedResource;
2223     }
2224
2225     protected Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml, String yamlName,
2226                                               Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
2227                                               Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
2228                                               boolean shouldLock, boolean inTransaction, String nodeName) {
2229         List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
2230         Resource createdResource;
2231         try {
2232             ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic
2233                 .getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName, resource);
2234             if (MapUtils.isEmpty(parsedToscaYamlInfo.getInstances()) && resource.getResourceType() != ResourceTypeEnum.PNF) {
2235                 throw new ComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2236             }
2237             log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", resource.getName());
2238             createdResource = createResourceAndRIsFromYaml(yamlName, resource, parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false,
2239                 createdArtifacts, topologyTemplateYaml, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
2240             log.debug("#createResourceFromYaml - The resource {} has been created ", resource.getName());
2241         } catch (ComponentException e) {
2242             ResponseFormat responseFormat =
2243                 e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
2244             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
2245             throw e;
2246         } catch (StorageException e) {
2247             ResponseFormat responseFormat = componentsUtils
2248                 .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
2249             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
2250             throw e;
2251         }
2252         return createdResource;
2253     }
2254
2255     protected Resource createResourceAndRIsFromYaml(String yamlName, Resource resource, ParsedToscaYamlInfo parsedToscaYamlInfo,
2256                                                     AuditingActionEnum actionEnum, boolean isNormative, List<ArtifactDefinition> createdArtifacts,
2257                                                     String topologyTemplateYaml, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
2258                                                     Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
2259                                                     boolean shouldLock, boolean inTransaction, String nodeName) {
2260         List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
2261         if (shouldLock) {
2262             Either<Boolean, ResponseFormat> lockResult = serviceBusinessLogic
2263                 .lockComponentByName(resource.getSystemName(), resource, CREATE_RESOURCE);
2264             if (lockResult.isRight()) {
2265                 serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
2266                 throw new ComponentException(lockResult.right().value());
2267             }
2268             log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
2269         }
2270         try {
2271             log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
2272             Resource genericResource = serviceBusinessLogic.fetchAndSetDerivedFromGenericType(resource);
2273             resource = createResourceTransaction(resource, csarInfo.getModifier(), isNormative);
2274             log.trace("************* Going to add inputs from yaml {}", yamlName);
2275             Map<String, Object> yamlMap = ImportUtils.loadYamlAsStrictMap(csarInfo.getMainTemplateContent());
2276             Map<String, Object> metadata = (Map<String, Object>) yamlMap.get("metadata");
2277             String type = (String) metadata.get("type");
2278             if (resource.shouldGenerateInputs() && !"Service".equalsIgnoreCase(type)) {
2279                 serviceBusinessLogic.generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
2280             }
2281             Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
2282             resource = serviceImportParseLogic.createInputsOnResource(resource, inputs);
2283             Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo.getInstances();
2284             resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap, topologyTemplateYaml,
2285                 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, nodeName);
2286             log.trace("************* Finished to create nodes, RI and Relation  from yaml {}", yamlName);
2287             // validate update vf module group names
2288             Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNames(
2289                 parsedToscaYamlInfo.getGroups(), resource.getSystemName());
2290             if (validateUpdateVfGroupNamesRes.isRight()) {
2291                 serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
2292                 throw new ComponentException(validateUpdateVfGroupNamesRes.right().value());
2293             }
2294             Map<String, GroupDefinition> groups;
2295             log.trace("************* Going to add groups from yaml {}", yamlName);
2296             if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
2297                 groups = validateUpdateVfGroupNamesRes.left().value();
2298             } else {
2299                 groups = parsedToscaYamlInfo.getGroups();
2300             }
2301             Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource, groups);
2302             if (createGroupsOnResource.isRight()) {
2303                 serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
2304                 throw new ComponentException(createGroupsOnResource.right().value());
2305             }
2306             resource = createGroupsOnResource.left().value();
2307             log.trace("************* Going to add artifacts from yaml {}", yamlName);
2308             NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToCreate);
2309             Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE,
2310                 createdArtifacts, yamlName, csarInfo, resource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
2311             if (createArtifactsEither.isRight()) {
2312                 serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
2313                 throw new ComponentException(createArtifactsEither.right().value());
2314             }
2315             resource = serviceImportParseLogic.getResourceWithGroups(createArtifactsEither.left().value().getUniqueId());
2316             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
2317             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum);
2318             ASDCKpiApi.countCreatedResourcesKPI();
2319             return resource;
2320         } catch (ComponentException | StorageException e) {
2321             serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
2322             throw e;
2323         } finally {
2324             if (!inTransaction) {
2325                 janusGraphDao.commit();
2326             }
2327             if (shouldLock) {
2328                 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource);
2329             }
2330         }
2331     }
2332
2333     protected Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
2334         if (groups != null && !groups.isEmpty()) {
2335             List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
2336             serviceImportParseLogic.handleGroupsProperties(resource, groups);
2337             serviceImportParseLogic.fillGroupsFinalFields(groupsAsList);
2338             Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource, groupsAsList, true);
2339             if (createGroups.isRight()) {
2340                 return Either.right(createGroups.right().value());
2341             }
2342         } else {
2343             return Either.left(resource);
2344         }
2345         Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
2346         if (updatedResource.isRight()) {
2347             ResponseFormat responseFormat = componentsUtils
2348                 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
2349             return Either.right(responseFormat);
2350         }
2351         return Either.left(updatedResource.left().value());
2352     }
2353
2354     protected List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, Resource component) {
2355         List<GroupDefinition> result = new ArrayList<>();
2356         List<ComponentInstance> componentInstances = component.getComponentInstances();
2357         if (groups != null) {
2358             for (Map.Entry<String, GroupDefinition> entry : groups.entrySet()) {
2359                 String groupName = entry.getKey();
2360                 GroupDefinition groupDefinition = entry.getValue();
2361                 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
2362                 updatedGroupDefinition.setMembers(null);
2363                 Map<String, String> members = groupDefinition.getMembers();
2364                 if (members != null) {
2365                     updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members);
2366                 }
2367                 result.add(updatedGroupDefinition);
2368             }
2369         }
2370         return result;
2371     }
2372
2373     protected void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition, Resource component,
2374                                       List<ComponentInstance> componentInstances, String groupName, Map<String, String> members) {
2375         Set<String> compInstancesNames = members.keySet();
2376         if (CollectionUtils.isEmpty(componentInstances)) {
2377             String membersAstString = compInstancesNames.stream().collect(joining(","));
2378             log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", membersAstString,
2379                 groupName, component.getNormalizedName());
2380             throw new ComponentException(componentsUtils
2381                 .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(),
2382                     serviceImportParseLogic.getComponentTypeForResponse(component)));
2383         }
2384         Map<String, String> memberNames = componentInstances.stream().collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
2385         memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> "")));
2386         Map<String, String> relevantInstances = memberNames.entrySet().stream().filter(n -> compInstancesNames.contains(n.getKey()))
2387             .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
2388         if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
2389             List<String> foundMembers = new ArrayList<>();
2390             if (relevantInstances != null) {
2391                 foundMembers = relevantInstances.keySet().stream().collect(toList());
2392             }
2393             compInstancesNames.removeAll(foundMembers);
2394             String membersAstString = compInstancesNames.stream().collect(joining(","));
2395             throw new ComponentException(componentsUtils
2396                 .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(),
2397                     serviceImportParseLogic.getComponentTypeForResponse(component)));
2398         }
2399         updatedGroupDefinition.setMembers(relevantInstances);
2400     }
2401
2402     protected Resource createResourceTransaction(Resource resource, User user, boolean isNormative) {
2403         Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade
2404             .validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType());
2405         if (eitherValidation.isRight()) {
2406             ResponseFormat errorResponse = componentsUtils
2407                 .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
2408             throw new ComponentException(errorResponse);
2409         }
2410         if (eitherValidation.left().value()) {
2411             log.debug("resource with name: {}, already exists", resource.getName());
2412             ResponseFormat errorResponse = componentsUtils
2413                 .getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
2414             throw new ComponentException(errorResponse);
2415         }
2416         log.debug("send resource {} to dao for create", resource.getName());
2417         serviceImportParseLogic.createArtifactsPlaceHolderData(resource, user);
2418         if (!isNormative) {
2419             log.debug("enrich resource with creator, version and state");
2420             resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
2421             resource.setVersion(INITIAL_VERSION);
2422             resource.setHighestVersion(true);
2423             if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.VF) {
2424                 resource.setAbstract(false);
2425             }
2426         }
2427         return toscaOperationFacade.createToscaComponent(resource).left()
2428             .on(r -> serviceImportParseLogic.throwComponentExceptionByResource(r, resource));
2429     }
2430
2431     protected ImmutablePair<Resource, ActionStatus> updateExistingResourceByImport(Resource newResource, Resource oldResource, User user,
2432                                                                                    boolean inTransaction, boolean needLock, boolean isNested) {
2433         String lockedResourceId = oldResource.getUniqueId();
2434         log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId, oldResource.getVersion(),
2435             oldResource.getLifecycleState());
2436         ImmutablePair<Resource, ActionStatus> resourcePair = null;
2437         try {
2438             serviceBusinessLogic.lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import");
2439             oldResource = serviceImportParseLogic.prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false);
2440             serviceImportParseLogic.mergeOldResourceMetadataWithNew(oldResource, newResource);
2441             serviceImportParseLogic.validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested);
2442             serviceImportParseLogic.validateCapabilityTypesCreate(user, serviceImportParseLogic.getCapabilityTypeOperation(), newResource,
2443                 AuditingActionEnum.IMPORT_RESOURCE, inTransaction);
2444             createNewResourceToOldResource(newResource, oldResource, user);
2445             Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade.overrideComponent(newResource, oldResource);
2446             if (overrideResource.isRight()) {
2447                 ResponseFormat responseFormat = new ResponseFormat();
2448                 serviceBusinessLogic.throwComponentException(responseFormat);
2449             }
2450             log.debug("Resource updated successfully!!!");
2451             resourcePair = new ImmutablePair<>(overrideResource.left().value(), ActionStatus.OK);
2452             return resourcePair;
2453         } finally {
2454             if (resourcePair == null) {
2455                 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
2456                 janusGraphDao.rollback();
2457             } else if (!inTransaction) {
2458                 janusGraphDao.commit();
2459             }
2460             if (needLock) {
2461                 log.debug("unlock resource {}", lockedResourceId);
2462                 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
2463             }
2464         }
2465     }
2466
2467     protected void createNewResourceToOldResource(Resource newResource, Resource oldResource, User user) {
2468         newResource.setContactId(newResource.getContactId().toLowerCase());
2469         newResource.setCreatorUserId(user.getUserId());
2470         newResource.setCreatorFullName(user.getFullName());
2471         newResource.setLastUpdaterUserId(user.getUserId());
2472         newResource.setLastUpdaterFullName(user.getFullName());
2473         newResource.setUniqueId(oldResource.getUniqueId());
2474         newResource.setVersion(oldResource.getVersion());
2475         newResource.setInvariantUUID(oldResource.getInvariantUUID());
2476         newResource.setLifecycleState(oldResource.getLifecycleState());
2477         newResource.setUUID(oldResource.getUUID());
2478         newResource.setNormalizedName(oldResource.getNormalizedName());
2479         newResource.setSystemName(oldResource.getSystemName());
2480         if (oldResource.getCsarUUID() != null) {
2481             newResource.setCsarUUID(oldResource.getCsarUUID());
2482         }
2483         if (oldResource.getCsarVersionId() != null) {
2484             newResource.setCsarVersionId(oldResource.getCsarVersionId());
2485         }
2486         if (oldResource.getImportedToscaChecksum() != null) {
2487             newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
2488         }
2489         if (newResource.getDerivedFromGenericType() == null || newResource.getDerivedFromGenericType().isEmpty()) {
2490             newResource.setDerivedFromGenericType(oldResource.getDerivedFromGenericType());
2491         }
2492         if (newResource.getDerivedFromGenericVersion() == null || newResource.getDerivedFromGenericVersion().isEmpty()) {
2493             newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion());
2494         }
2495         if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts().isEmpty()) {
2496             serviceBusinessLogic.setToscaArtifactsPlaceHolders(newResource, user);
2497         }
2498         if (newResource.getInterfaces() == null || newResource.getInterfaces().isEmpty()) {
2499             newResource.setInterfaces(oldResource.getInterfaces());
2500         }
2501         if (CollectionUtils.isEmpty(newResource.getProperties())) {
2502             newResource.setProperties(oldResource.getProperties());
2503         }
2504         if (newResource.getModel() == null) {
2505             newResource.setModel(oldResource.getModel());
2506         }
2507     }
2508
2509     protected Map<String, Resource> createResourcesFromYamlNodeTypesList(String yamlName, Service service, Map<String, Object> mappedToscaTemplate,
2510                                                                          boolean needLock,
2511                                                                          Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
2512                                                                          List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
2513                                                                          Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
2514         try {
2515             Either<String, ImportUtils.ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate,
2516                 TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
2517             if (toscaVersion.isRight()) {
2518                 throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE);
2519             }
2520             Map<String, Object> mapToConvert = new HashMap<>();
2521             mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left().value());
2522             Map<String, Object> nodeTypes = serviceImportParseLogic.getNodeTypesFromTemplate(mappedToscaTemplate);
2523             createNodeTypes(yamlName, service, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
2524                 mapToConvert, nodeTypes);
2525             return csarInfo.getCreatedNodes();
2526         } catch (Exception e) {
2527             log.debug("Exception occured when createResourcesFromYamlNodeTypesList,error is:{}", e.getMessage(), e);
2528             throw new ComponentException(ActionStatus.GENERAL_ERROR);
2529         }
2530     }
2531
2532     protected void createNodeTypes(String yamlName, Service service, boolean needLock,
2533                                    Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
2534                                    List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
2535                                    Map<String, Object> mapToConvert, Map<String, Object> nodeTypes) {
2536         Iterator<Map.Entry<String, Object>> nodesNameValueIter = nodeTypes.entrySet().iterator();
2537         Resource vfcCreated = null;
2538         while (nodesNameValueIter.hasNext()) {
2539             Map.Entry<String, Object> nodeType = nodesNameValueIter.next();
2540             String nodeTypeKey = nodeType.getKey();
2541             Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle =
2542                 nodeTypesArtifactsToHandle == null || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeTypeKey);
2543             if (nodeTypesInfo.containsKey(nodeTypeKey)) {
2544                 vfcCreated = handleNestedVfc(service, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
2545                     nodeTypeKey);
2546                 log.trace("************* Finished to handle nested vfc {}", nodeTypeKey);
2547             } else if (csarInfo.getCreatedNodesToscaResourceNames() != null && !csarInfo.getCreatedNodesToscaResourceNames()
2548                 .containsKey(nodeTypeKey)) {
2549                 ImmutablePair<Resource, ActionStatus> resourceCreated = serviceImportParseLogic
2550                     .createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert, service, needLock,
2551                         nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, csarInfo, true);
2552                 log.debug("************* Finished to create node {}", nodeTypeKey);
2553                 vfcCreated = resourceCreated.getLeft();
2554                 csarInfo.getCreatedNodesToscaResourceNames().put(nodeTypeKey, vfcCreated.getName());
2555             }
2556             if (vfcCreated != null) {
2557                 csarInfo.getCreatedNodes().put(nodeTypeKey, vfcCreated);
2558             }
2559             mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName());
2560         }
2561     }
2562 }