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